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 "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTMutationListener.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/CharUnits.h"
18#include "clang/AST/ComparisonCategories.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/DynamicRecursiveASTVisitor.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/AST/StmtVisitor.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/AST/TypeOrdering.h"
29#include "clang/Basic/AttributeCommonInfo.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Lex/LiteralSupport.h"
34#include "clang/Lex/Preprocessor.h"
35#include "clang/Sema/CXXFieldCollector.h"
36#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/EnterExpressionEvaluationContext.h"
38#include "clang/Sema/Initialization.h"
39#include "clang/Sema/Lookup.h"
40#include "clang/Sema/Ownership.h"
41#include "clang/Sema/ParsedTemplate.h"
42#include "clang/Sema/Scope.h"
43#include "clang/Sema/ScopeInfo.h"
44#include "clang/Sema/SemaCUDA.h"
45#include "clang/Sema/SemaInternal.h"
46#include "clang/Sema/SemaObjC.h"
47#include "clang/Sema/SemaOpenMP.h"
48#include "clang/Sema/Template.h"
49#include "clang/Sema/TemplateDeduction.h"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/STLExtras.h"
52#include "llvm/ADT/StringExtras.h"
53#include "llvm/Support/ConvertUTF.h"
54#include "llvm/Support/SaveAndRestore.h"
55#include <map>
56#include <optional>
57#include <set>
58
59using namespace clang;
60
61//===----------------------------------------------------------------------===//
62// CheckDefaultArgumentVisitor
63//===----------------------------------------------------------------------===//
64
65namespace {
66/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
67/// the default argument of a parameter to determine whether it
68/// contains any ill-formed subexpressions. For example, this will
69/// diagnose the use of local variables or parameters within the
70/// default argument expression.
71class CheckDefaultArgumentVisitor
72 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
73 Sema &S;
74 const Expr *DefaultArg;
75
76public:
77 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
78 : S(S), DefaultArg(DefaultArg) {}
79
80 bool VisitExpr(const Expr *Node);
81 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
82 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
83 bool VisitLambdaExpr(const LambdaExpr *Lambda);
84 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
85};
86
87/// VisitExpr - Visit all of the children of this expression.
88bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
89 bool IsInvalid = false;
90 for (const Stmt *SubStmt : Node->children())
91 if (SubStmt)
92 IsInvalid |= Visit(S: SubStmt);
93 return IsInvalid;
94}
95
96/// VisitDeclRefExpr - Visit a reference to a declaration, to
97/// determine whether this declaration can be used in the default
98/// argument expression.
99bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
100 const ValueDecl *Decl = dyn_cast<ValueDecl>(Val: DRE->getDecl());
101
102 if (!isa<VarDecl, BindingDecl>(Val: Decl))
103 return false;
104
105 if (const auto *Param = dyn_cast<ParmVarDecl>(Val: Decl)) {
106 // C++ [dcl.fct.default]p9:
107 // [...] parameters of a function shall not be used in default
108 // argument expressions, even if they are not evaluated. [...]
109 //
110 // C++17 [dcl.fct.default]p9 (by CWG 2082):
111 // [...] A parameter shall not appear as a potentially-evaluated
112 // expression in a default argument. [...]
113 //
114 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
115 return S.Diag(Loc: DRE->getBeginLoc(),
116 DiagID: diag::err_param_default_argument_references_param)
117 << Param->getDeclName() << DefaultArg->getSourceRange();
118 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
119 // C++ [dcl.fct.default]p7:
120 // Local variables shall not be used in default argument
121 // expressions.
122 //
123 // C++17 [dcl.fct.default]p7 (by CWG 2082):
124 // A local variable shall not appear as a potentially-evaluated
125 // expression in a default argument.
126 //
127 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
128 // Note: A local variable cannot be odr-used (6.3) in a default
129 // argument.
130 //
131 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
132 return S.Diag(Loc: DRE->getBeginLoc(),
133 DiagID: diag::err_param_default_argument_references_local)
134 << Decl << DefaultArg->getSourceRange();
135 }
136 return false;
137}
138
139/// VisitCXXThisExpr - Visit a C++ "this" expression.
140bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
141 // C++ [dcl.fct.default]p8:
142 // The keyword this shall not be used in a default argument of a
143 // member function.
144 return S.Diag(Loc: ThisE->getBeginLoc(),
145 DiagID: diag::err_param_default_argument_references_this)
146 << ThisE->getSourceRange();
147}
148
149bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
150 const PseudoObjectExpr *POE) {
151 bool Invalid = false;
152 for (const Expr *E : POE->semantics()) {
153 // Look through bindings.
154 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
155 E = OVE->getSourceExpr();
156 assert(E && "pseudo-object binding without source expression?");
157 }
158
159 Invalid |= Visit(S: E);
160 }
161 return Invalid;
162}
163
164bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
165 // [expr.prim.lambda.capture]p9
166 // a lambda-expression appearing in a default argument cannot implicitly or
167 // explicitly capture any local entity. Such a lambda-expression can still
168 // have an init-capture if any full-expression in its initializer satisfies
169 // the constraints of an expression appearing in a default argument.
170 bool Invalid = false;
171 for (const LambdaCapture &LC : Lambda->captures()) {
172 if (!Lambda->isInitCapture(Capture: &LC))
173 return S.Diag(Loc: LC.getLocation(), DiagID: diag::err_lambda_capture_default_arg);
174 // Init captures are always VarDecl.
175 auto *D = cast<VarDecl>(Val: LC.getCapturedVar());
176 Invalid |= Visit(S: D->getInit());
177 }
178 return Invalid;
179}
180} // namespace
181
182void
183Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
184 const CXXMethodDecl *Method) {
185 // If we have an MSAny spec already, don't bother.
186 if (!Method || ComputedEST == EST_MSAny)
187 return;
188
189 const FunctionProtoType *Proto
190 = Method->getType()->getAs<FunctionProtoType>();
191 Proto = Self->ResolveExceptionSpec(Loc: CallLoc, FPT: Proto);
192 if (!Proto)
193 return;
194
195 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
196
197 // If we have a throw-all spec at this point, ignore the function.
198 if (ComputedEST == EST_None)
199 return;
200
201 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
202 EST = EST_BasicNoexcept;
203
204 switch (EST) {
205 case EST_Unparsed:
206 case EST_Uninstantiated:
207 case EST_Unevaluated:
208 llvm_unreachable("should not see unresolved exception specs here");
209
210 // If this function can throw any exceptions, make a note of that.
211 case EST_MSAny:
212 case EST_None:
213 // FIXME: Whichever we see last of MSAny and None determines our result.
214 // We should make a consistent, order-independent choice here.
215 ClearExceptions();
216 ComputedEST = EST;
217 return;
218 case EST_NoexceptFalse:
219 ClearExceptions();
220 ComputedEST = EST_None;
221 return;
222 // FIXME: If the call to this decl is using any of its default arguments, we
223 // need to search them for potentially-throwing calls.
224 // If this function has a basic noexcept, it doesn't affect the outcome.
225 case EST_BasicNoexcept:
226 case EST_NoexceptTrue:
227 case EST_NoThrow:
228 return;
229 // If we're still at noexcept(true) and there's a throw() callee,
230 // change to that specification.
231 case EST_DynamicNone:
232 if (ComputedEST == EST_BasicNoexcept)
233 ComputedEST = EST_DynamicNone;
234 return;
235 case EST_DependentNoexcept:
236 llvm_unreachable(
237 "should not generate implicit declarations for dependent cases");
238 case EST_Dynamic:
239 break;
240 }
241 assert(EST == EST_Dynamic && "EST case not considered earlier.");
242 assert(ComputedEST != EST_None &&
243 "Shouldn't collect exceptions when throw-all is guaranteed.");
244 ComputedEST = EST_Dynamic;
245 // Record the exceptions in this function's exception specification.
246 for (const auto &E : Proto->exceptions())
247 if (ExceptionsSeen.insert(Ptr: Self->Context.getCanonicalType(T: E)).second)
248 Exceptions.push_back(Elt: E);
249}
250
251void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
252 if (!S || ComputedEST == EST_MSAny)
253 return;
254
255 // FIXME:
256 //
257 // C++0x [except.spec]p14:
258 // [An] implicit exception-specification specifies the type-id T if and
259 // only if T is allowed by the exception-specification of a function directly
260 // invoked by f's implicit definition; f shall allow all exceptions if any
261 // function it directly invokes allows all exceptions, and f shall allow no
262 // exceptions if every function it directly invokes allows no exceptions.
263 //
264 // Note in particular that if an implicit exception-specification is generated
265 // for a function containing a throw-expression, that specification can still
266 // be noexcept(true).
267 //
268 // Note also that 'directly invoked' is not defined in the standard, and there
269 // is no indication that we should only consider potentially-evaluated calls.
270 //
271 // Ultimately we should implement the intent of the standard: the exception
272 // specification should be the set of exceptions which can be thrown by the
273 // implicit definition. For now, we assume that any non-nothrow expression can
274 // throw any exception.
275
276 if (Self->canThrow(E: S))
277 ComputedEST = EST_None;
278}
279
280ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
281 SourceLocation EqualLoc) {
282 if (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
283 DiagID: diag::err_typecheck_decl_incomplete_type))
284 return true;
285
286 // C++ [dcl.fct.default]p5
287 // A default argument expression is implicitly converted (clause
288 // 4) to the parameter type. The default argument expression has
289 // the same semantic constraints as the initializer expression in
290 // a declaration of a variable of the parameter type, using the
291 // copy-initialization semantics (8.5).
292 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
293 Parm: Param);
294 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Param->getLocation(),
295 EqualLoc);
296 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
297 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Arg);
298 if (Result.isInvalid())
299 return true;
300 Arg = Result.getAs<Expr>();
301
302 CheckCompletedExpr(E: Arg, CheckLoc: EqualLoc);
303 Arg = MaybeCreateExprWithCleanups(SubExpr: Arg);
304
305 return Arg;
306}
307
308void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
309 SourceLocation EqualLoc) {
310 // Add the default argument to the parameter
311 Param->setDefaultArg(Arg);
312
313 // We have already instantiated this parameter; provide each of the
314 // instantiations with the uninstantiated default argument.
315 UnparsedDefaultArgInstantiationsMap::iterator InstPos
316 = UnparsedDefaultArgInstantiations.find(Val: Param);
317 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
318 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
319 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
320
321 // We're done tracking this parameter's instantiations.
322 UnparsedDefaultArgInstantiations.erase(I: InstPos);
323 }
324}
325
326void
327Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
328 Expr *DefaultArg) {
329 if (!param || !DefaultArg)
330 return;
331
332 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
333 UnparsedDefaultArgLocs.erase(Val: Param);
334
335 // Default arguments are only permitted in C++
336 if (!getLangOpts().CPlusPlus) {
337 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument)
338 << DefaultArg->getSourceRange();
339 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
340 }
341
342 // Check for unexpanded parameter packs.
343 if (DiagnoseUnexpandedParameterPack(E: DefaultArg, UPPC: UPPC_DefaultArgument))
344 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
345
346 // C++11 [dcl.fct.default]p3
347 // A default argument expression [...] shall not be specified for a
348 // parameter pack.
349 if (Param->isParameterPack()) {
350 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument_on_parameter_pack)
351 << DefaultArg->getSourceRange();
352 // Recover by discarding the default argument.
353 Param->setDefaultArg(nullptr);
354 return;
355 }
356
357 ExprResult Result = ConvertParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
358 if (Result.isInvalid())
359 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
360
361 DefaultArg = Result.getAs<Expr>();
362
363 // Check that the default argument is well-formed
364 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
365 if (DefaultArgChecker.Visit(S: DefaultArg))
366 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
367
368 SetParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
369}
370
371void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
372 SourceLocation EqualLoc,
373 SourceLocation ArgLoc) {
374 if (!param)
375 return;
376
377 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
378 Param->setUnparsedDefaultArg();
379 UnparsedDefaultArgLocs[Param] = ArgLoc;
380}
381
382void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
383 Expr *DefaultArg) {
384 if (!param)
385 return;
386
387 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
388 Param->setInvalidDecl();
389 UnparsedDefaultArgLocs.erase(Val: Param);
390 ExprResult RE;
391 if (DefaultArg) {
392 RE = CreateRecoveryExpr(Begin: EqualLoc, End: DefaultArg->getEndLoc(), SubExprs: {DefaultArg},
393 T: Param->getType().getNonReferenceType());
394 } else {
395 RE = CreateRecoveryExpr(Begin: EqualLoc, End: EqualLoc, SubExprs: {},
396 T: Param->getType().getNonReferenceType());
397 }
398 Param->setDefaultArg(RE.get());
399}
400
401void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
402 // C++ [dcl.fct.default]p3
403 // A default argument expression shall be specified only in the
404 // parameter-declaration-clause of a function declaration or in a
405 // template-parameter (14.1). It shall not be specified for a
406 // parameter pack. If it is specified in a
407 // parameter-declaration-clause, it shall not occur within a
408 // declarator or abstract-declarator of a parameter-declaration.
409 bool MightBeFunction = D.isFunctionDeclarationContext();
410 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
411 DeclaratorChunk &chunk = D.getTypeObject(i);
412 if (chunk.Kind == DeclaratorChunk::Function) {
413 if (MightBeFunction) {
414 // This is a function declaration. It can have default arguments, but
415 // keep looking in case its return type is a function type with default
416 // arguments.
417 MightBeFunction = false;
418 continue;
419 }
420 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
421 ++argIdx) {
422 ParmVarDecl *Param = cast<ParmVarDecl>(Val: chunk.Fun.Params[argIdx].Param);
423 if (Param->hasUnparsedDefaultArg()) {
424 std::unique_ptr<CachedTokens> Toks =
425 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
426 SourceRange SR;
427 if (Toks->size() > 1)
428 SR = SourceRange((*Toks)[1].getLocation(),
429 Toks->back().getLocation());
430 else
431 SR = UnparsedDefaultArgLocs[Param];
432 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
433 << SR;
434 } else if (Param->getDefaultArg()) {
435 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
436 << Param->getDefaultArg()->getSourceRange();
437 Param->setDefaultArg(nullptr);
438 }
439 }
440 } else if (chunk.Kind != DeclaratorChunk::Paren) {
441 MightBeFunction = false;
442 }
443 }
444}
445
446static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
447 return llvm::any_of(Range: FD->parameters(), P: [](ParmVarDecl *P) {
448 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
449 });
450}
451
452bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
453 Scope *S) {
454 bool Invalid = false;
455
456 // The declaration context corresponding to the scope is the semantic
457 // parent, unless this is a local function declaration, in which case
458 // it is that surrounding function.
459 DeclContext *ScopeDC = New->isLocalExternDecl()
460 ? New->getLexicalDeclContext()
461 : New->getDeclContext();
462
463 // Find the previous declaration for the purpose of default arguments.
464 FunctionDecl *PrevForDefaultArgs = Old;
465 for (/**/; PrevForDefaultArgs;
466 // Don't bother looking back past the latest decl if this is a local
467 // extern declaration; nothing else could work.
468 PrevForDefaultArgs = New->isLocalExternDecl()
469 ? nullptr
470 : PrevForDefaultArgs->getPreviousDecl()) {
471 // Ignore hidden declarations.
472 if (!LookupResult::isVisible(SemaRef&: *this, D: PrevForDefaultArgs))
473 continue;
474
475 if (S && !isDeclInScope(D: PrevForDefaultArgs, Ctx: ScopeDC, S) &&
476 !New->isCXXClassMember()) {
477 // Ignore default arguments of old decl if they are not in
478 // the same scope and this is not an out-of-line definition of
479 // a member function.
480 continue;
481 }
482
483 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
484 // If only one of these is a local function declaration, then they are
485 // declared in different scopes, even though isDeclInScope may think
486 // they're in the same scope. (If both are local, the scope check is
487 // sufficient, and if neither is local, then they are in the same scope.)
488 continue;
489 }
490
491 // We found the right previous declaration.
492 break;
493 }
494
495 // C++ [dcl.fct.default]p4:
496 // For non-template functions, default arguments can be added in
497 // later declarations of a function in the same
498 // scope. Declarations in different scopes have completely
499 // distinct sets of default arguments. That is, declarations in
500 // inner scopes do not acquire default arguments from
501 // declarations in outer scopes, and vice versa. In a given
502 // function declaration, all parameters subsequent to a
503 // parameter with a default argument shall have default
504 // arguments supplied in this or previous declarations. A
505 // default argument shall not be redefined by a later
506 // declaration (not even to the same value).
507 //
508 // C++ [dcl.fct.default]p6:
509 // Except for member functions of class templates, the default arguments
510 // in a member function definition that appears outside of the class
511 // definition are added to the set of default arguments provided by the
512 // member function declaration in the class definition.
513 for (unsigned p = 0, NumParams = PrevForDefaultArgs
514 ? PrevForDefaultArgs->getNumParams()
515 : 0;
516 p < NumParams; ++p) {
517 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(i: p);
518 ParmVarDecl *NewParam = New->getParamDecl(i: p);
519
520 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
521 bool NewParamHasDfl = NewParam->hasDefaultArg();
522
523 if (OldParamHasDfl && NewParamHasDfl) {
524 unsigned DiagDefaultParamID =
525 diag::err_param_default_argument_redefinition;
526
527 // MSVC accepts that default parameters be redefined for member functions
528 // of template class. The new default parameter's value is ignored.
529 Invalid = true;
530 if (getLangOpts().MicrosoftExt) {
531 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: New);
532 if (MD && MD->getParent()->getDescribedClassTemplate()) {
533 // Merge the old default argument into the new parameter.
534 NewParam->setHasInheritedDefaultArg();
535 if (OldParam->hasUninstantiatedDefaultArg())
536 NewParam->setUninstantiatedDefaultArg(
537 OldParam->getUninstantiatedDefaultArg());
538 else
539 NewParam->setDefaultArg(OldParam->getInit());
540 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
541 Invalid = false;
542 }
543 }
544
545 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
546 // hint here. Alternatively, we could walk the type-source information
547 // for NewParam to find the last source location in the type... but it
548 // isn't worth the effort right now. This is the kind of test case that
549 // is hard to get right:
550 // int f(int);
551 // void g(int (*fp)(int) = f);
552 // void g(int (*fp)(int) = &f);
553 Diag(Loc: NewParam->getLocation(), DiagID: DiagDefaultParamID)
554 << NewParam->getDefaultArgRange();
555
556 // Look for the function declaration where the default argument was
557 // actually written, which may be a declaration prior to Old.
558 for (auto Older = PrevForDefaultArgs;
559 OldParam->hasInheritedDefaultArg(); /**/) {
560 Older = Older->getPreviousDecl();
561 OldParam = Older->getParamDecl(i: p);
562 }
563
564 Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_definition)
565 << OldParam->getDefaultArgRange();
566 } else if (OldParamHasDfl) {
567 // Merge the old default argument into the new parameter unless the new
568 // function is a friend declaration in a template class. In the latter
569 // case the default arguments will be inherited when the friend
570 // declaration will be instantiated.
571 if (New->getFriendObjectKind() == Decl::FOK_None ||
572 !New->getLexicalDeclContext()->isDependentContext()) {
573 // It's important to use getInit() here; getDefaultArg()
574 // strips off any top-level ExprWithCleanups.
575 NewParam->setHasInheritedDefaultArg();
576 if (OldParam->hasUnparsedDefaultArg())
577 NewParam->setUnparsedDefaultArg();
578 else if (OldParam->hasUninstantiatedDefaultArg())
579 NewParam->setUninstantiatedDefaultArg(
580 OldParam->getUninstantiatedDefaultArg());
581 else
582 NewParam->setDefaultArg(OldParam->getInit());
583 }
584 } else if (NewParamHasDfl) {
585 if (New->getDescribedFunctionTemplate()) {
586 // Paragraph 4, quoted above, only applies to non-template functions.
587 Diag(Loc: NewParam->getLocation(),
588 DiagID: diag::err_param_default_argument_template_redecl)
589 << NewParam->getDefaultArgRange();
590 Diag(Loc: PrevForDefaultArgs->getLocation(),
591 DiagID: diag::note_template_prev_declaration)
592 << false;
593 } else if (New->getTemplateSpecializationKind()
594 != TSK_ImplicitInstantiation &&
595 New->getTemplateSpecializationKind() != TSK_Undeclared) {
596 // C++ [temp.expr.spec]p21:
597 // Default function arguments shall not be specified in a declaration
598 // or a definition for one of the following explicit specializations:
599 // - the explicit specialization of a function template;
600 // - the explicit specialization of a member function template;
601 // - the explicit specialization of a member function of a class
602 // template where the class template specialization to which the
603 // member function specialization belongs is implicitly
604 // instantiated.
605 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_template_spec_default_arg)
606 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
607 << New->getDeclName()
608 << NewParam->getDefaultArgRange();
609 } else if (New->getDeclContext()->isDependentContext()) {
610 // C++ [dcl.fct.default]p6 (DR217):
611 // Default arguments for a member function of a class template shall
612 // be specified on the initial declaration of the member function
613 // within the class template.
614 //
615 // Reading the tea leaves a bit in DR217 and its reference to DR205
616 // leads me to the conclusion that one cannot add default function
617 // arguments for an out-of-line definition of a member function of a
618 // dependent type.
619 int WhichKind = 2;
620 if (CXXRecordDecl *Record
621 = dyn_cast<CXXRecordDecl>(Val: New->getDeclContext())) {
622 if (Record->getDescribedClassTemplate())
623 WhichKind = 0;
624 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Record))
625 WhichKind = 1;
626 else
627 WhichKind = 2;
628 }
629
630 Diag(Loc: NewParam->getLocation(),
631 DiagID: diag::err_param_default_argument_member_template_redecl)
632 << WhichKind
633 << NewParam->getDefaultArgRange();
634 }
635 }
636 }
637
638 // DR1344: If a default argument is added outside a class definition and that
639 // default argument makes the function a special member function, the program
640 // is ill-formed. This can only happen for constructors.
641 if (isa<CXXConstructorDecl>(Val: New) &&
642 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
643 CXXSpecialMemberKind NewSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: New)),
644 OldSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: Old));
645 if (NewSM != OldSM) {
646 ParmVarDecl *NewParam = New->getParamDecl(i: New->getMinRequiredArguments());
647 assert(NewParam->hasDefaultArg());
648 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_default_arg_makes_ctor_special)
649 << NewParam->getDefaultArgRange() << NewSM;
650 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
651 }
652 }
653
654 const FunctionDecl *Def;
655 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
656 // template has a constexpr specifier then all its declarations shall
657 // contain the constexpr specifier.
658 if (New->getConstexprKind() != Old->getConstexprKind()) {
659 Diag(Loc: New->getLocation(), DiagID: diag::err_constexpr_redecl_mismatch)
660 << New << static_cast<int>(New->getConstexprKind())
661 << static_cast<int>(Old->getConstexprKind());
662 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
663 Invalid = true;
664 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
665 Old->isDefined(Definition&: Def) &&
666 // If a friend function is inlined but does not have 'inline'
667 // specifier, it is a definition. Do not report attribute conflict
668 // in this case, redefinition will be diagnosed later.
669 (New->isInlineSpecified() ||
670 New->getFriendObjectKind() == Decl::FOK_None)) {
671 // C++11 [dcl.fcn.spec]p4:
672 // If the definition of a function appears in a translation unit before its
673 // first declaration as inline, the program is ill-formed.
674 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
675 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
676 Invalid = true;
677 }
678
679 // C++17 [temp.deduct.guide]p3:
680 // Two deduction guide declarations in the same translation unit
681 // for the same class template shall not have equivalent
682 // parameter-declaration-clauses.
683 if (isa<CXXDeductionGuideDecl>(Val: New) &&
684 !New->isFunctionTemplateSpecialization() && isVisible(D: Old)) {
685 Diag(Loc: New->getLocation(), DiagID: diag::err_deduction_guide_redeclared);
686 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
687 }
688
689 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
690 // argument expression, that declaration shall be a definition and shall be
691 // the only declaration of the function or function template in the
692 // translation unit.
693 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
694 functionDeclHasDefaultArgument(FD: Old)) {
695 Diag(Loc: New->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
696 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
697 Invalid = true;
698 }
699
700 // C++11 [temp.friend]p4 (DR329):
701 // When a function is defined in a friend function declaration in a class
702 // template, the function is instantiated when the function is odr-used.
703 // The same restrictions on multiple declarations and definitions that
704 // apply to non-template function declarations and definitions also apply
705 // to these implicit definitions.
706 const FunctionDecl *OldDefinition = nullptr;
707 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
708 Old->isDefined(Definition&: OldDefinition, CheckForPendingFriendDefinition: true))
709 CheckForFunctionRedefinition(FD: New, EffectiveDefinition: OldDefinition);
710
711 return Invalid;
712}
713
714void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
715 Diag(Loc, DiagID: getLangOpts().CPlusPlus26
716 ? diag::warn_cxx23_placeholder_var_definition
717 : diag::ext_placeholder_var_definition);
718}
719
720NamedDecl *
721Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
722 MultiTemplateParamsArg TemplateParamLists) {
723 assert(D.isDecompositionDeclarator());
724 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
725
726 // The syntax only allows a decomposition declarator as a simple-declaration,
727 // a for-range-declaration, or a condition in Clang, but we parse it in more
728 // cases than that.
729 if (!D.mayHaveDecompositionDeclarator()) {
730 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
731 << Decomp.getSourceRange();
732 return nullptr;
733 }
734
735 if (!TemplateParamLists.empty()) {
736 // C++17 [temp]/1:
737 // A template defines a family of class, functions, or variables, or an
738 // alias for a family of types.
739 //
740 // Structured bindings are not included.
741 Diag(Loc: TemplateParamLists.front()->getTemplateLoc(),
742 DiagID: diag::err_decomp_decl_template);
743 return nullptr;
744 }
745
746 unsigned DiagID;
747 if (!getLangOpts().CPlusPlus17)
748 DiagID = diag::compat_pre_cxx17_decomp_decl;
749 else if (D.getContext() == DeclaratorContext::Condition)
750 DiagID = getLangOpts().CPlusPlus26
751 ? diag::compat_cxx26_decomp_decl_cond
752 : diag::compat_pre_cxx26_decomp_decl_cond;
753 else
754 DiagID = diag::compat_cxx17_decomp_decl;
755
756 Diag(Loc: Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
757
758 // The semantic context is always just the current context.
759 DeclContext *const DC = CurContext;
760
761 // C++17 [dcl.dcl]/8:
762 // The decl-specifier-seq shall contain only the type-specifier auto
763 // and cv-qualifiers.
764 // C++20 [dcl.dcl]/8:
765 // If decl-specifier-seq contains any decl-specifier other than static,
766 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
767 // C++23 [dcl.pre]/6:
768 // Each decl-specifier in the decl-specifier-seq shall be static,
769 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
770 auto &DS = D.getDeclSpec();
771 {
772 // Note: While constrained-auto needs to be checked, we do so separately so
773 // we can emit a better diagnostic.
774 SmallVector<StringRef, 8> BadSpecifiers;
775 SmallVector<SourceLocation, 8> BadSpecifierLocs;
776 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
777 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
778 if (auto SCS = DS.getStorageClassSpec()) {
779 if (SCS == DeclSpec::SCS_static) {
780 CPlusPlus20Specifiers.push_back(Elt: DeclSpec::getSpecifierName(S: SCS));
781 CPlusPlus20SpecifierLocs.push_back(Elt: DS.getStorageClassSpecLoc());
782 } else {
783 BadSpecifiers.push_back(Elt: DeclSpec::getSpecifierName(S: SCS));
784 BadSpecifierLocs.push_back(Elt: DS.getStorageClassSpecLoc());
785 }
786 }
787 if (auto TSCS = DS.getThreadStorageClassSpec()) {
788 CPlusPlus20Specifiers.push_back(Elt: DeclSpec::getSpecifierName(S: TSCS));
789 CPlusPlus20SpecifierLocs.push_back(Elt: DS.getThreadStorageClassSpecLoc());
790 }
791 if (DS.hasConstexprSpecifier()) {
792 BadSpecifiers.push_back(
793 Elt: DeclSpec::getSpecifierName(C: DS.getConstexprSpecifier()));
794 BadSpecifierLocs.push_back(Elt: DS.getConstexprSpecLoc());
795 }
796 if (DS.isInlineSpecified()) {
797 BadSpecifiers.push_back(Elt: "inline");
798 BadSpecifierLocs.push_back(Elt: DS.getInlineSpecLoc());
799 }
800
801 if (!BadSpecifiers.empty()) {
802 auto &&Err = Diag(Loc: BadSpecifierLocs.front(), DiagID: diag::err_decomp_decl_spec);
803 Err << (int)BadSpecifiers.size()
804 << llvm::join(Begin: BadSpecifiers.begin(), End: BadSpecifiers.end(), Separator: " ");
805 // Don't add FixItHints to remove the specifiers; we do still respect
806 // them when building the underlying variable.
807 for (auto Loc : BadSpecifierLocs)
808 Err << SourceRange(Loc, Loc);
809 } else if (!CPlusPlus20Specifiers.empty()) {
810 auto &&Warn = DiagCompat(Loc: CPlusPlus20SpecifierLocs.front(),
811 CompatDiagId: diag_compat::decomp_decl_spec);
812 Warn << (int)CPlusPlus20Specifiers.size()
813 << llvm::join(Begin: CPlusPlus20Specifiers.begin(),
814 End: CPlusPlus20Specifiers.end(), Separator: " ");
815 for (auto Loc : CPlusPlus20SpecifierLocs)
816 Warn << SourceRange(Loc, Loc);
817 }
818 // We can't recover from it being declared as a typedef.
819 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
820 return nullptr;
821 }
822
823 // C++2a [dcl.struct.bind]p1:
824 // A cv that includes volatile is deprecated
825 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
826 getLangOpts().CPlusPlus20)
827 Diag(Loc: DS.getVolatileSpecLoc(),
828 DiagID: diag::warn_deprecated_volatile_structured_binding);
829
830 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
831 QualType R = TInfo->getType();
832
833 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
834 UPPC: UPPC_DeclarationType))
835 D.setInvalidType();
836
837 // The syntax only allows a single ref-qualifier prior to the decomposition
838 // declarator. No other declarator chunks are permitted. Also check the type
839 // specifier here.
840 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
841 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
842 (D.getNumTypeObjects() == 1 &&
843 D.getTypeObject(i: 0).Kind != DeclaratorChunk::Reference)) {
844 Diag(Loc: Decomp.getLSquareLoc(),
845 DiagID: (D.hasGroupingParens() ||
846 (D.getNumTypeObjects() &&
847 D.getTypeObject(i: 0).Kind == DeclaratorChunk::Paren))
848 ? diag::err_decomp_decl_parens
849 : diag::err_decomp_decl_type)
850 << R;
851
852 // In most cases, there's no actual problem with an explicitly-specified
853 // type, but a function type won't work here, and ActOnVariableDeclarator
854 // shouldn't be called for such a type.
855 if (R->isFunctionType())
856 D.setInvalidType();
857 }
858
859 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
860 if (DS.isConstrainedAuto()) {
861 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
862 assert(TemplRep->Kind == TNK_Concept_template &&
863 "No other template kind should be possible for a constrained auto");
864
865 SourceRange TemplRange{TemplRep->TemplateNameLoc,
866 TemplRep->RAngleLoc.isValid()
867 ? TemplRep->RAngleLoc
868 : TemplRep->TemplateNameLoc};
869 Diag(Loc: TemplRep->TemplateNameLoc, DiagID: diag::err_decomp_decl_constraint)
870 << TemplRange << FixItHint::CreateRemoval(RemoveRange: TemplRange);
871 }
872
873 // Build the BindingDecls.
874 SmallVector<BindingDecl*, 8> Bindings;
875
876 // Build the BindingDecls.
877 for (auto &B : D.getDecompositionDeclarator().bindings()) {
878 // Check for name conflicts.
879 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
880 IdentifierInfo *VarName = B.Name;
881 assert(VarName && "Cannot have an unnamed binding declaration");
882
883 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
884 RedeclarationKind::ForVisibleRedeclaration);
885 LookupName(R&: Previous, S,
886 /*CreateBuiltins*/AllowBuiltinCreation: DC->getRedeclContext()->isTranslationUnit());
887
888 // It's not permitted to shadow a template parameter name.
889 if (Previous.isSingleResult() &&
890 Previous.getFoundDecl()->isTemplateParameter()) {
891 DiagnoseTemplateParameterShadow(Loc: B.NameLoc, PrevDecl: Previous.getFoundDecl());
892 Previous.clear();
893 }
894
895 QualType QT;
896 if (B.EllipsisLoc.isValid()) {
897 if (!cast<Decl>(Val: DC)->isTemplated())
898 Diag(Loc: B.EllipsisLoc, DiagID: diag::err_pack_outside_template);
899 QT = Context.getPackExpansionType(Pattern: Context.DependentTy, NumExpansions: std::nullopt,
900 /*ExpectsPackInType=*/ExpectPackInType: false);
901 }
902
903 auto *BD = BindingDecl::Create(C&: Context, DC, IdLoc: B.NameLoc, Id: B.Name, T: QT);
904
905 ProcessDeclAttributeList(S, D: BD, AttrList: *B.Attrs);
906
907 // Find the shadowed declaration before filtering for scope.
908 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
909 ? getShadowedDeclaration(D: BD, R: Previous)
910 : nullptr;
911
912 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
913 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
914 FilterLookupForScope(R&: Previous, Ctx: DC, S, ConsiderLinkage,
915 /*AllowInlineNamespace*/false);
916
917 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
918 DC->isFunctionOrMethod() && VarName->isPlaceholder();
919 if (!Previous.empty()) {
920 if (IsPlaceholder) {
921 bool sameDC = (Previous.end() - 1)
922 ->getDeclContext()
923 ->getRedeclContext()
924 ->Equals(DC: DC->getRedeclContext());
925 if (sameDC &&
926 isDeclInScope(D: *(Previous.end() - 1), Ctx: CurContext, S, AllowInlineNamespace: false)) {
927 Previous.clear();
928 DiagPlaceholderVariableDefinition(Loc: B.NameLoc);
929 }
930 } else {
931 auto *Old = Previous.getRepresentativeDecl();
932 Diag(Loc: B.NameLoc, DiagID: diag::err_redefinition) << B.Name;
933 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
934 }
935 } else if (ShadowedDecl && !D.isRedeclaration()) {
936 CheckShadow(D: BD, ShadowedDecl, R: Previous);
937 }
938 PushOnScopeChains(D: BD, S, AddToContext: true);
939 Bindings.push_back(Elt: BD);
940 ParsingInitForAutoVars.insert(Ptr: BD);
941 }
942
943 // There are no prior lookup results for the variable itself, because it
944 // is unnamed.
945 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
946 Decomp.getLSquareLoc());
947 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
948 RedeclarationKind::ForVisibleRedeclaration);
949
950 // Build the variable that holds the non-decomposed object.
951 bool AddToScope = true;
952 NamedDecl *New =
953 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
954 TemplateParamLists: MultiTemplateParamsArg(), AddToScope, Bindings);
955 if (AddToScope) {
956 S->AddDecl(D: New);
957 CurContext->addHiddenDecl(D: New);
958 }
959
960 if (OpenMP().isInOpenMPDeclareTargetContext())
961 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
962
963 return New;
964}
965
966// Check the arity of the structured bindings.
967// Create the resolved pack expr if needed.
968static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD,
969 QualType DecompType,
970 ArrayRef<BindingDecl *> Bindings,
971 unsigned MemberCount) {
972 auto BindingWithPackItr = llvm::find_if(
973 Range&: Bindings, P: [](BindingDecl *D) -> bool { return D->isParameterPack(); });
974 bool HasPack = BindingWithPackItr != Bindings.end();
975 bool IsValid;
976 if (!HasPack) {
977 IsValid = Bindings.size() == MemberCount;
978 } else {
979 // There may not be more members than non-pack bindings.
980 IsValid = MemberCount >= Bindings.size() - 1;
981 }
982
983 if (IsValid && HasPack) {
984 // Create the pack expr and assign it to the binding.
985 unsigned PackSize = MemberCount - Bindings.size() + 1;
986
987 BindingDecl *BPack = *BindingWithPackItr;
988 BPack->setDecomposedDecl(DD);
989 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
990 // Create the nested BindingDecls.
991 for (unsigned I = 0; I < PackSize; ++I) {
992 BindingDecl *NestedBD = BindingDecl::Create(
993 C&: S.Context, DC: BPack->getDeclContext(), IdLoc: BPack->getLocation(),
994 Id: BPack->getIdentifier(), T: QualType());
995 NestedBD->setDecomposedDecl(DD);
996 NestedBDs[I] = NestedBD;
997 }
998
999 QualType PackType = S.Context.getPackExpansionType(
1000 Pattern: S.Context.DependentTy, NumExpansions: PackSize, /*ExpectsPackInType=*/ExpectPackInType: false);
1001 auto *PackExpr = FunctionParmPackExpr::Create(
1002 Context: S.Context, T: PackType, ParamPack: BPack, NameLoc: BPack->getBeginLoc(), Params: NestedBDs);
1003 BPack->setBinding(DeclaredType: PackType, Binding: PackExpr);
1004 }
1005
1006 if (IsValid)
1007 return false;
1008
1009 S.Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_wrong_number_bindings)
1010 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1011 << (MemberCount < Bindings.size());
1012 return true;
1013}
1014
1015static bool checkSimpleDecomposition(
1016 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
1017 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1018 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1019 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1020 auto *DD = cast<DecompositionDecl>(Val: Src);
1021
1022 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1023 return true;
1024
1025 unsigned I = 0;
1026 for (auto *B : DD->flat_bindings()) {
1027 SourceLocation Loc = B->getLocation();
1028 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1029 if (E.isInvalid())
1030 return true;
1031 E = GetInit(Loc, E.get(), I++);
1032 if (E.isInvalid())
1033 return true;
1034 B->setBinding(DeclaredType: ElemType, Binding: E.get());
1035 }
1036
1037 return false;
1038}
1039
1040static bool checkArrayLikeDecomposition(Sema &S,
1041 ArrayRef<BindingDecl *> Bindings,
1042 ValueDecl *Src, QualType DecompType,
1043 const llvm::APSInt &NumElems,
1044 QualType ElemType) {
1045 return checkSimpleDecomposition(
1046 S, Bindings, Src, DecompType, NumElemsAPS: NumElems, ElemType,
1047 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1048 ExprResult E = S.ActOnIntegerConstant(Loc, Val: I);
1049 if (E.isInvalid())
1050 return ExprError();
1051 return S.CreateBuiltinArraySubscriptExpr(Base, LLoc: Loc, Idx: E.get(), RLoc: Loc);
1052 });
1053}
1054
1055static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1056 ValueDecl *Src, QualType DecompType,
1057 const ConstantArrayType *CAT) {
1058 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1059 NumElems: llvm::APSInt(CAT->getSize()),
1060 ElemType: CAT->getElementType());
1061}
1062
1063static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1064 ValueDecl *Src, QualType DecompType,
1065 const VectorType *VT) {
1066 return checkArrayLikeDecomposition(
1067 S, Bindings, Src, DecompType, NumElems: llvm::APSInt::get(X: VT->getNumElements()),
1068 ElemType: S.Context.getQualifiedType(T: VT->getElementType(),
1069 Qs: DecompType.getQualifiers()));
1070}
1071
1072static bool checkComplexDecomposition(Sema &S,
1073 ArrayRef<BindingDecl *> Bindings,
1074 ValueDecl *Src, QualType DecompType,
1075 const ComplexType *CT) {
1076 return checkSimpleDecomposition(
1077 S, Bindings, Src, DecompType, NumElemsAPS: llvm::APSInt::get(X: 2),
1078 ElemType: S.Context.getQualifiedType(T: CT->getElementType(),
1079 Qs: DecompType.getQualifiers()),
1080 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1081 return S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: I ? UO_Imag : UO_Real, InputExpr: Base);
1082 });
1083}
1084
1085static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1086 TemplateArgumentListInfo &Args,
1087 const TemplateParameterList *Params) {
1088 SmallString<128> SS;
1089 llvm::raw_svector_ostream OS(SS);
1090 bool First = true;
1091 unsigned I = 0;
1092 for (auto &Arg : Args.arguments()) {
1093 if (!First)
1094 OS << ", ";
1095 Arg.getArgument().print(Policy: PrintingPolicy, Out&: OS,
1096 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
1097 Policy: PrintingPolicy, TPL: Params, Idx: I));
1098 First = false;
1099 I++;
1100 }
1101 return std::string(OS.str());
1102}
1103
1104static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1105 SourceLocation Loc, StringRef Trait,
1106 TemplateArgumentListInfo &Args,
1107 unsigned DiagID) {
1108 auto DiagnoseMissing = [&] {
1109 if (DiagID)
1110 S.Diag(Loc, DiagID) << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(),
1111 Args, /*Params*/ nullptr);
1112 return true;
1113 };
1114
1115 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1116 NamespaceDecl *Std = S.getStdNamespace();
1117 if (!Std)
1118 return DiagnoseMissing();
1119
1120 // Look up the trait itself, within namespace std. We can diagnose various
1121 // problems with this lookup even if we've been asked to not diagnose a
1122 // missing specialization, because this can only fail if the user has been
1123 // declaring their own names in namespace std or we don't support the
1124 // standard library implementation in use.
1125 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: Trait),
1126 Loc, Sema::LookupOrdinaryName);
1127 if (!S.LookupQualifiedName(R&: Result, LookupCtx: Std))
1128 return DiagnoseMissing();
1129 if (Result.isAmbiguous())
1130 return true;
1131
1132 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1133 if (!TraitTD) {
1134 Result.suppressDiagnostics();
1135 NamedDecl *Found = *Result.begin();
1136 S.Diag(Loc, DiagID: diag::err_std_type_trait_not_class_template) << Trait;
1137 S.Diag(Loc: Found->getLocation(), DiagID: diag::note_declared_at);
1138 return true;
1139 }
1140
1141 // Build the template-id.
1142 QualType TraitTy = S.CheckTemplateIdType(Template: TemplateName(TraitTD), TemplateLoc: Loc, TemplateArgs&: Args);
1143 if (TraitTy.isNull())
1144 return true;
1145 if (!S.isCompleteType(Loc, T: TraitTy)) {
1146 if (DiagID)
1147 S.RequireCompleteType(
1148 Loc, T: TraitTy, DiagID,
1149 Args: printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1150 Params: TraitTD->getTemplateParameters()));
1151 return true;
1152 }
1153
1154 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1155 assert(RD && "specialization of class template is not a class?");
1156
1157 // Look up the member of the trait type.
1158 S.LookupQualifiedName(R&: TraitMemberLookup, LookupCtx: RD);
1159 return TraitMemberLookup.isAmbiguous();
1160}
1161
1162static TemplateArgumentLoc
1163getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1164 uint64_t I) {
1165 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(Value: I, Type: T), T);
1166 return S.getTrivialTemplateArgumentLoc(Arg, NTTPType: T, Loc);
1167}
1168
1169static TemplateArgumentLoc
1170getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1171 return S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(T), NTTPType: QualType(), Loc);
1172}
1173
1174namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1175
1176static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1177 llvm::APSInt &Size) {
1178 EnterExpressionEvaluationContext ContextRAII(
1179 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1180
1181 DeclarationName Value = S.PP.getIdentifierInfo(Name: "value");
1182 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1183
1184 // Form template argument list for tuple_size<T>.
1185 TemplateArgumentListInfo Args(Loc, Loc);
1186 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1187
1188 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1189 // it's not tuple-like.
1190 if (lookupStdTypeTraitMember(S, TraitMemberLookup&: R, Loc, Trait: "tuple_size", Args, /*DiagID*/ 0) ||
1191 R.empty())
1192 return IsTupleLike::NotTupleLike;
1193
1194 // If we get this far, we've committed to the tuple interpretation, but
1195 // we can still fail if there actually isn't a usable ::value.
1196
1197 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1198 LookupResult &R;
1199 TemplateArgumentListInfo &Args;
1200 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1201 : R(R), Args(Args) {}
1202 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1203 SourceLocation Loc) override {
1204 return S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_not_constant)
1205 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1206 /*Params*/ nullptr);
1207 }
1208 } Diagnoser(R, Args);
1209
1210 ExprResult E =
1211 S.BuildDeclarationNameExpr(SS: CXXScopeSpec(), R, /*NeedsADL*/false);
1212 if (E.isInvalid())
1213 return IsTupleLike::Error;
1214
1215 E = S.VerifyIntegerConstantExpression(E: E.get(), Result: &Size, Diagnoser);
1216 if (E.isInvalid())
1217 return IsTupleLike::Error;
1218
1219 return IsTupleLike::TupleLike;
1220}
1221
1222/// \return std::tuple_element<I, T>::type.
1223static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1224 unsigned I, QualType T) {
1225 // Form template argument list for tuple_element<I, T>.
1226 TemplateArgumentListInfo Args(Loc, Loc);
1227 Args.addArgument(
1228 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1229 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1230
1231 DeclarationName TypeDN = S.PP.getIdentifierInfo(Name: "type");
1232 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1233 if (lookupStdTypeTraitMember(
1234 S, TraitMemberLookup&: R, Loc, Trait: "tuple_element", Args,
1235 DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized))
1236 return QualType();
1237
1238 auto *TD = R.getAsSingle<TypeDecl>();
1239 if (!TD) {
1240 R.suppressDiagnostics();
1241 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized)
1242 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1243 /*Params*/ nullptr);
1244 if (!R.empty())
1245 S.Diag(Loc: R.getRepresentativeDecl()->getLocation(), DiagID: diag::note_declared_at);
1246 return QualType();
1247 }
1248
1249 return S.Context.getTypeDeclType(Decl: TD);
1250}
1251
1252namespace {
1253struct InitializingBinding {
1254 Sema &S;
1255 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1256 Sema::CodeSynthesisContext Ctx;
1257 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1258 Ctx.PointOfInstantiation = BD->getLocation();
1259 Ctx.Entity = BD;
1260 S.pushCodeSynthesisContext(Ctx);
1261 }
1262 ~InitializingBinding() {
1263 S.popCodeSynthesisContext();
1264 }
1265};
1266}
1267
1268static bool checkTupleLikeDecomposition(Sema &S,
1269 ArrayRef<BindingDecl *> Bindings,
1270 VarDecl *Src, QualType DecompType,
1271 const llvm::APSInt &TupleSize) {
1272 auto *DD = cast<DecompositionDecl>(Val: Src);
1273 unsigned NumElems = (unsigned)TupleSize.getLimitedValue(UINT_MAX);
1274 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1275 return true;
1276
1277 if (Bindings.empty())
1278 return false;
1279
1280 DeclarationName GetDN = S.PP.getIdentifierInfo(Name: "get");
1281
1282 // [dcl.decomp]p3:
1283 // The unqualified-id get is looked up in the scope of E by class member
1284 // access lookup ...
1285 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1286 bool UseMemberGet = false;
1287 if (S.isCompleteType(Loc: Src->getLocation(), T: DecompType)) {
1288 if (auto *RD = DecompType->getAsCXXRecordDecl())
1289 S.LookupQualifiedName(R&: MemberGet, LookupCtx: RD);
1290 if (MemberGet.isAmbiguous())
1291 return true;
1292 // ... and if that finds at least one declaration that is a function
1293 // template whose first template parameter is a non-type parameter ...
1294 for (NamedDecl *D : MemberGet) {
1295 if (FunctionTemplateDecl *FTD =
1296 dyn_cast<FunctionTemplateDecl>(Val: D->getUnderlyingDecl())) {
1297 TemplateParameterList *TPL = FTD->getTemplateParameters();
1298 if (TPL->size() != 0 &&
1299 isa<NonTypeTemplateParmDecl>(Val: TPL->getParam(Idx: 0))) {
1300 // ... the initializer is e.get<i>().
1301 UseMemberGet = true;
1302 break;
1303 }
1304 }
1305 }
1306 }
1307
1308 unsigned I = 0;
1309 for (auto *B : DD->flat_bindings()) {
1310 InitializingBinding InitContext(S, B);
1311 SourceLocation Loc = B->getLocation();
1312
1313 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1314 if (E.isInvalid())
1315 return true;
1316
1317 // e is an lvalue if the type of the entity is an lvalue reference and
1318 // an xvalue otherwise
1319 if (!Src->getType()->isLValueReferenceType())
1320 E = ImplicitCastExpr::Create(Context: S.Context, T: E.get()->getType(), Kind: CK_NoOp,
1321 Operand: E.get(), BasePath: nullptr, Cat: VK_XValue,
1322 FPO: FPOptionsOverride());
1323
1324 TemplateArgumentListInfo Args(Loc, Loc);
1325 Args.addArgument(
1326 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1327
1328 if (UseMemberGet) {
1329 // if [lookup of member get] finds at least one declaration, the
1330 // initializer is e.get<i-1>().
1331 E = S.BuildMemberReferenceExpr(Base: E.get(), BaseType: DecompType, OpLoc: Loc, IsArrow: false,
1332 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr,
1333 R&: MemberGet, TemplateArgs: &Args, S: nullptr);
1334 if (E.isInvalid())
1335 return true;
1336
1337 E = S.BuildCallExpr(S: nullptr, Fn: E.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
1338 } else {
1339 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1340 // in the associated namespaces.
1341 Expr *Get = UnresolvedLookupExpr::Create(
1342 Context: S.Context, NamingClass: nullptr, QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(),
1343 NameInfo: DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, Args: &Args,
1344 Begin: UnresolvedSetIterator(), End: UnresolvedSetIterator(),
1345 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1346
1347 Expr *Arg = E.get();
1348 E = S.BuildCallExpr(S: nullptr, Fn: Get, LParenLoc: Loc, ArgExprs: Arg, RParenLoc: Loc);
1349 }
1350 if (E.isInvalid())
1351 return true;
1352 Expr *Init = E.get();
1353
1354 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1355 QualType T = getTupleLikeElementType(S, Loc, I, T: DecompType);
1356 if (T.isNull())
1357 return true;
1358
1359 // each vi is a variable of type "reference to T" initialized with the
1360 // initializer, where the reference is an lvalue reference if the
1361 // initializer is an lvalue and an rvalue reference otherwise
1362 QualType RefType =
1363 S.BuildReferenceType(T, LValueRef: E.get()->isLValue(), Loc, Entity: B->getDeclName());
1364 if (RefType.isNull())
1365 return true;
1366 auto *RefVD = VarDecl::Create(
1367 C&: S.Context, DC: Src->getDeclContext(), StartLoc: Loc, IdLoc: Loc,
1368 Id: B->getDeclName().getAsIdentifierInfo(), T: RefType,
1369 TInfo: S.Context.getTrivialTypeSourceInfo(T, Loc), S: Src->getStorageClass());
1370 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1371 RefVD->setTSCSpec(Src->getTSCSpec());
1372 RefVD->setImplicit();
1373 if (Src->isInlineSpecified())
1374 RefVD->setInlineSpecified();
1375 RefVD->getLexicalDeclContext()->addHiddenDecl(D: RefVD);
1376
1377 InitializedEntity Entity = InitializedEntity::InitializeBinding(Binding: RefVD);
1378 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc);
1379 InitializationSequence Seq(S, Entity, Kind, Init);
1380 E = Seq.Perform(S, Entity, Kind, Args: Init);
1381 if (E.isInvalid())
1382 return true;
1383 E = S.ActOnFinishFullExpr(Expr: E.get(), CC: Loc, /*DiscardedValue*/ false);
1384 if (E.isInvalid())
1385 return true;
1386 RefVD->setInit(E.get());
1387 S.CheckCompleteVariableDeclaration(VD: RefVD);
1388
1389 E = S.BuildDeclarationNameExpr(SS: CXXScopeSpec(),
1390 NameInfo: DeclarationNameInfo(B->getDeclName(), Loc),
1391 D: RefVD);
1392 if (E.isInvalid())
1393 return true;
1394
1395 B->setBinding(DeclaredType: T, Binding: E.get());
1396 I++;
1397 }
1398
1399 return false;
1400}
1401
1402/// Find the base class to decompose in a built-in decomposition of a class type.
1403/// This base class search is, unfortunately, not quite like any other that we
1404/// perform anywhere else in C++.
1405static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1406 const CXXRecordDecl *RD,
1407 CXXCastPath &BasePath) {
1408 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1409 CXXBasePath &Path) {
1410 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1411 };
1412
1413 const CXXRecordDecl *ClassWithFields = nullptr;
1414 AccessSpecifier AS = AS_public;
1415 if (RD->hasDirectFields())
1416 // [dcl.decomp]p4:
1417 // Otherwise, all of E's non-static data members shall be public direct
1418 // members of E ...
1419 ClassWithFields = RD;
1420 else {
1421 // ... or of ...
1422 CXXBasePaths Paths;
1423 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1424 if (!RD->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1425 // If no classes have fields, just decompose RD itself. (This will work
1426 // if and only if zero bindings were provided.)
1427 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(RD), AS: AS_public);
1428 }
1429
1430 CXXBasePath *BestPath = nullptr;
1431 for (auto &P : Paths) {
1432 if (!BestPath)
1433 BestPath = &P;
1434 else if (!S.Context.hasSameType(T1: P.back().Base->getType(),
1435 T2: BestPath->back().Base->getType())) {
1436 // ... the same ...
1437 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1438 << false << RD << BestPath->back().Base->getType()
1439 << P.back().Base->getType();
1440 return DeclAccessPair();
1441 } else if (P.Access < BestPath->Access) {
1442 BestPath = &P;
1443 }
1444 }
1445
1446 // ... unambiguous ...
1447 QualType BaseType = BestPath->back().Base->getType();
1448 if (Paths.isAmbiguous(BaseType: S.Context.getCanonicalType(T: BaseType))) {
1449 S.Diag(Loc, DiagID: diag::err_decomp_decl_ambiguous_base)
1450 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1451 return DeclAccessPair();
1452 }
1453
1454 // ... [accessible, implied by other rules] base class of E.
1455 S.CheckBaseClassAccess(AccessLoc: Loc, Base: BaseType, Derived: S.Context.getRecordType(Decl: RD),
1456 Path: *BestPath, DiagID: diag::err_decomp_decl_inaccessible_base);
1457 AS = BestPath->Access;
1458
1459 ClassWithFields = BaseType->getAsCXXRecordDecl();
1460 S.BuildBasePathArray(Paths, BasePath);
1461 }
1462
1463 // The above search did not check whether the selected class itself has base
1464 // classes with fields, so check that now.
1465 CXXBasePaths Paths;
1466 if (ClassWithFields->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1467 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1468 << (ClassWithFields == RD) << RD << ClassWithFields
1469 << Paths.front().back().Base->getType();
1470 return DeclAccessPair();
1471 }
1472
1473 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1474}
1475
1476static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc,
1477 const CXXRecordDecl *OrigRD,
1478 QualType DecompType,
1479 DeclAccessPair BasePair) {
1480 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1481 if (!RD)
1482 return true;
1483
1484 for (auto *FD : RD->fields()) {
1485 if (FD->isUnnamedBitField())
1486 continue;
1487
1488 // All the non-static data members are required to be nameable, so they
1489 // must all have names.
1490 if (!FD->getDeclName()) {
1491 if (RD->isLambda()) {
1492 S.Diag(Loc, DiagID: diag::err_decomp_decl_lambda);
1493 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
1494 return true;
1495 }
1496
1497 if (FD->isAnonymousStructOrUnion()) {
1498 S.Diag(Loc, DiagID: diag::err_decomp_decl_anon_union_member)
1499 << DecompType << FD->getType()->isUnionType();
1500 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_declared_at);
1501 return true;
1502 }
1503
1504 // FIXME: Are there any other ways we could have an anonymous member?
1505 }
1506 // The field must be accessible in the context of the structured binding.
1507 // We already checked that the base class is accessible.
1508 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1509 // const_cast here.
1510 S.CheckStructuredBindingMemberAccess(
1511 UseLoc: Loc, DecomposedClass: const_cast<CXXRecordDecl *>(OrigRD),
1512 Field: DeclAccessPair::make(D: FD, AS: CXXRecordDecl::MergeAccess(
1513 PathAccess: BasePair.getAccess(), DeclAccess: FD->getAccess())));
1514 }
1515 return false;
1516}
1517
1518static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1519 ValueDecl *Src, QualType DecompType,
1520 const CXXRecordDecl *OrigRD) {
1521 if (S.RequireCompleteType(Loc: Src->getLocation(), T: DecompType,
1522 DiagID: diag::err_incomplete_type))
1523 return true;
1524
1525 CXXCastPath BasePath;
1526 DeclAccessPair BasePair =
1527 findDecomposableBaseClass(S, Loc: Src->getLocation(), RD: OrigRD, BasePath);
1528 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1529 if (!RD)
1530 return true;
1531 QualType BaseType = S.Context.getQualifiedType(T: S.Context.getRecordType(Decl: RD),
1532 Qs: DecompType.getQualifiers());
1533
1534 auto *DD = cast<DecompositionDecl>(Val: Src);
1535 unsigned NumFields = llvm::count_if(
1536 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1537 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumFields))
1538 return true;
1539
1540 // all of E's non-static data members shall be [...] well-formed
1541 // when named as e.name in the context of the structured binding,
1542 // E shall not have an anonymous union member, ...
1543 auto FlatBindings = DD->flat_bindings();
1544 assert(llvm::range_size(FlatBindings) == NumFields);
1545 auto FlatBindingsItr = FlatBindings.begin();
1546
1547 if (CheckMemberDecompositionFields(S, Loc: Src->getLocation(), OrigRD, DecompType,
1548 BasePair))
1549 return true;
1550
1551 for (auto *FD : RD->fields()) {
1552 if (FD->isUnnamedBitField())
1553 continue;
1554
1555 // We have a real field to bind.
1556 assert(FlatBindingsItr != FlatBindings.end());
1557 BindingDecl *B = *(FlatBindingsItr++);
1558 SourceLocation Loc = B->getLocation();
1559
1560 // Initialize the binding to Src.FD.
1561 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1562 if (E.isInvalid())
1563 return true;
1564 E = S.ImpCastExprToType(E: E.get(), Type: BaseType, CK: CK_UncheckedDerivedToBase,
1565 VK: VK_LValue, BasePath: &BasePath);
1566 if (E.isInvalid())
1567 return true;
1568 E = S.BuildFieldReferenceExpr(BaseExpr: E.get(), /*IsArrow*/ false, OpLoc: Loc,
1569 SS: CXXScopeSpec(), Field: FD,
1570 FoundDecl: DeclAccessPair::make(D: FD, AS: FD->getAccess()),
1571 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
1572 if (E.isInvalid())
1573 return true;
1574
1575 // If the type of the member is T, the referenced type is cv T, where cv is
1576 // the cv-qualification of the decomposition expression.
1577 //
1578 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1579 // 'const' to the type of the field.
1580 Qualifiers Q = DecompType.getQualifiers();
1581 if (FD->isMutable())
1582 Q.removeConst();
1583 B->setBinding(DeclaredType: S.BuildQualifiedType(T: FD->getType(), Loc, Qs: Q), Binding: E.get());
1584 }
1585
1586 return false;
1587}
1588
1589void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1590 QualType DecompType = DD->getType();
1591
1592 // If the type of the decomposition is dependent, then so is the type of
1593 // each binding.
1594 if (DecompType->isDependentType()) {
1595 // Note that all of the types are still Null or PackExpansionType.
1596 for (auto *B : DD->bindings()) {
1597 // Do not overwrite any pack type.
1598 if (B->getType().isNull())
1599 B->setType(Context.DependentTy);
1600 }
1601 return;
1602 }
1603
1604 DecompType = DecompType.getNonReferenceType();
1605 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1606
1607 // C++1z [dcl.decomp]/2:
1608 // If E is an array type [...]
1609 // As an extension, we also support decomposition of built-in complex and
1610 // vector types.
1611 if (auto *CAT = Context.getAsConstantArrayType(T: DecompType)) {
1612 if (checkArrayDecomposition(S&: *this, Bindings, Src: DD, DecompType, CAT))
1613 DD->setInvalidDecl();
1614 return;
1615 }
1616 if (auto *VT = DecompType->getAs<VectorType>()) {
1617 if (checkVectorDecomposition(S&: *this, Bindings, Src: DD, DecompType, VT))
1618 DD->setInvalidDecl();
1619 return;
1620 }
1621 if (auto *CT = DecompType->getAs<ComplexType>()) {
1622 if (checkComplexDecomposition(S&: *this, Bindings, Src: DD, DecompType, CT))
1623 DD->setInvalidDecl();
1624 return;
1625 }
1626
1627 // C++1z [dcl.decomp]/3:
1628 // if the expression std::tuple_size<E>::value is a well-formed integral
1629 // constant expression, [...]
1630 llvm::APSInt TupleSize(32);
1631 switch (isTupleLike(S&: *this, Loc: DD->getLocation(), T: DecompType, Size&: TupleSize)) {
1632 case IsTupleLike::Error:
1633 DD->setInvalidDecl();
1634 return;
1635
1636 case IsTupleLike::TupleLike:
1637 if (checkTupleLikeDecomposition(S&: *this, Bindings, Src: DD, DecompType, TupleSize))
1638 DD->setInvalidDecl();
1639 return;
1640
1641 case IsTupleLike::NotTupleLike:
1642 break;
1643 }
1644
1645 // C++1z [dcl.dcl]/8:
1646 // [E shall be of array or non-union class type]
1647 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1648 if (!RD || RD->isUnion()) {
1649 Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_unbindable_type)
1650 << DD << !RD << DecompType;
1651 DD->setInvalidDecl();
1652 return;
1653 }
1654
1655 // C++1z [dcl.decomp]/4:
1656 // all of E's non-static data members shall be [...] direct members of
1657 // E or of the same unambiguous public base class of E, ...
1658 if (checkMemberDecomposition(S&: *this, Bindings, Src: DD, DecompType, OrigRD: RD))
1659 DD->setInvalidDecl();
1660}
1661
1662UnsignedOrNone Sema::GetDecompositionElementCount(QualType T,
1663 SourceLocation Loc) {
1664 const ASTContext &Ctx = getASTContext();
1665 assert(!T->isDependentType());
1666
1667 Qualifiers Quals;
1668 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1669 Quals.removeCVRQualifiers();
1670 T = Context.getQualifiedType(T: Unqual, Qs: Quals);
1671
1672 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1673 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1674 if (auto *VT = T->getAs<VectorType>())
1675 return VT->getNumElements();
1676 if (T->getAs<ComplexType>())
1677 return 2u;
1678
1679 llvm::APSInt TupleSize(Ctx.getTypeSize(T: Ctx.getSizeType()));
1680 switch (isTupleLike(S&: *this, Loc, T, Size&: TupleSize)) {
1681 case IsTupleLike::Error:
1682 return std::nullopt;
1683 case IsTupleLike::TupleLike:
1684 return static_cast<unsigned>(TupleSize.getExtValue());
1685 case IsTupleLike::NotTupleLike:
1686 break;
1687 }
1688
1689 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1690 if (!OrigRD || OrigRD->isUnion())
1691 return std::nullopt;
1692
1693 if (RequireCompleteType(Loc, T, DiagID: diag::err_incomplete_type))
1694 return std::nullopt;
1695
1696 CXXCastPath BasePath;
1697 DeclAccessPair BasePair =
1698 findDecomposableBaseClass(S&: *this, Loc, RD: OrigRD, BasePath);
1699 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1700 if (!RD)
1701 return std::nullopt;
1702
1703 unsigned NumFields = llvm::count_if(
1704 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1705
1706 if (CheckMemberDecompositionFields(S&: *this, Loc, OrigRD, DecompType: T, BasePair))
1707 return std::nullopt;
1708
1709 return NumFields;
1710}
1711
1712void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1713 // Shortcut if exceptions are disabled.
1714 if (!getLangOpts().CXXExceptions)
1715 return;
1716
1717 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1718 "Should only be called if types are otherwise the same.");
1719
1720 QualType NewType = New->getType();
1721 QualType OldType = Old->getType();
1722
1723 // We're only interested in pointers and references to functions, as well
1724 // as pointers to member functions.
1725 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1726 NewType = R->getPointeeType();
1727 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1728 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1729 NewType = P->getPointeeType();
1730 OldType = OldType->castAs<PointerType>()->getPointeeType();
1731 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1732 NewType = M->getPointeeType();
1733 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1734 }
1735
1736 if (!NewType->isFunctionProtoType())
1737 return;
1738
1739 // There's lots of special cases for functions. For function pointers, system
1740 // libraries are hopefully not as broken so that we don't need these
1741 // workarounds.
1742 if (CheckEquivalentExceptionSpec(
1743 Old: OldType->getAs<FunctionProtoType>(), OldLoc: Old->getLocation(),
1744 New: NewType->getAs<FunctionProtoType>(), NewLoc: New->getLocation())) {
1745 New->setInvalidDecl();
1746 }
1747}
1748
1749/// CheckCXXDefaultArguments - Verify that the default arguments for a
1750/// function declaration are well-formed according to C++
1751/// [dcl.fct.default].
1752void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1753 // This checking doesn't make sense for explicit specializations; their
1754 // default arguments are determined by the declaration we're specializing,
1755 // not by FD.
1756 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1757 return;
1758 if (auto *FTD = FD->getDescribedFunctionTemplate())
1759 if (FTD->isMemberSpecialization())
1760 return;
1761
1762 unsigned NumParams = FD->getNumParams();
1763 unsigned ParamIdx = 0;
1764
1765 // Find first parameter with a default argument
1766 for (; ParamIdx < NumParams; ++ParamIdx) {
1767 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1768 if (Param->hasDefaultArg())
1769 break;
1770 }
1771
1772 // C++20 [dcl.fct.default]p4:
1773 // In a given function declaration, each parameter subsequent to a parameter
1774 // with a default argument shall have a default argument supplied in this or
1775 // a previous declaration, unless the parameter was expanded from a
1776 // parameter pack, or shall be a function parameter pack.
1777 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1778 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1779 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1780 (CurrentInstantiationScope &&
1781 CurrentInstantiationScope->isLocalPackExpansion(D: Param)))
1782 continue;
1783 if (Param->isInvalidDecl())
1784 /* We already complained about this parameter. */;
1785 else if (Param->getIdentifier())
1786 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing_name)
1787 << Param->getIdentifier();
1788 else
1789 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing);
1790 }
1791}
1792
1793/// Check that the given type is a literal type. Issue a diagnostic if not,
1794/// if Kind is Diagnose.
1795/// \return \c true if a problem has been found (and optionally diagnosed).
1796template <typename... Ts>
1797static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1798 SourceLocation Loc, QualType T, unsigned DiagID,
1799 Ts &&...DiagArgs) {
1800 if (T->isDependentType())
1801 return false;
1802
1803 switch (Kind) {
1804 case Sema::CheckConstexprKind::Diagnose:
1805 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1806 std::forward<Ts>(DiagArgs)...);
1807
1808 case Sema::CheckConstexprKind::CheckValid:
1809 return !T->isLiteralType(Ctx: SemaRef.Context);
1810 }
1811
1812 llvm_unreachable("unknown CheckConstexprKind");
1813}
1814
1815/// Determine whether a destructor cannot be constexpr due to
1816static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1817 const CXXDestructorDecl *DD,
1818 Sema::CheckConstexprKind Kind) {
1819 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1820 "this check is obsolete for C++23");
1821 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1822 const CXXRecordDecl *RD =
1823 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1824 if (!RD || RD->hasConstexprDestructor())
1825 return true;
1826
1827 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1828 SemaRef.Diag(Loc: DD->getLocation(), DiagID: diag::err_constexpr_dtor_subobject)
1829 << static_cast<int>(DD->getConstexprKind()) << !FD
1830 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1831 SemaRef.Diag(Loc, DiagID: diag::note_constexpr_dtor_subobject)
1832 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1833 }
1834 return false;
1835 };
1836
1837 const CXXRecordDecl *RD = DD->getParent();
1838 for (const CXXBaseSpecifier &B : RD->bases())
1839 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1840 return false;
1841 for (const FieldDecl *FD : RD->fields())
1842 if (!Check(FD->getLocation(), FD->getType(), FD))
1843 return false;
1844 return true;
1845}
1846
1847/// Check whether a function's parameter types are all literal types. If so,
1848/// return true. If not, produce a suitable diagnostic and return false.
1849static bool CheckConstexprParameterTypes(Sema &SemaRef,
1850 const FunctionDecl *FD,
1851 Sema::CheckConstexprKind Kind) {
1852 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1853 "this check is obsolete for C++23");
1854 unsigned ArgIndex = 0;
1855 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1856 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1857 e = FT->param_type_end();
1858 i != e; ++i, ++ArgIndex) {
1859 const ParmVarDecl *PD = FD->getParamDecl(i: ArgIndex);
1860 assert(PD && "null in a parameter list");
1861 SourceLocation ParamLoc = PD->getLocation();
1862 if (CheckLiteralType(SemaRef, Kind, Loc: ParamLoc, T: *i,
1863 DiagID: diag::err_constexpr_non_literal_param, DiagArgs: ArgIndex + 1,
1864 DiagArgs: PD->getSourceRange(), DiagArgs: isa<CXXConstructorDecl>(Val: FD),
1865 DiagArgs: FD->isConsteval()))
1866 return false;
1867 }
1868 return true;
1869}
1870
1871/// Check whether a function's return type is a literal type. If so, return
1872/// true. If not, produce a suitable diagnostic and return false.
1873static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1874 Sema::CheckConstexprKind Kind) {
1875 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1876 "this check is obsolete for C++23");
1877 if (CheckLiteralType(SemaRef, Kind, Loc: FD->getLocation(), T: FD->getReturnType(),
1878 DiagID: diag::err_constexpr_non_literal_return,
1879 DiagArgs: FD->isConsteval()))
1880 return false;
1881 return true;
1882}
1883
1884/// Get diagnostic %select index for tag kind for
1885/// record diagnostic message.
1886/// WARNING: Indexes apply to particular diagnostics only!
1887///
1888/// \returns diagnostic %select index.
1889static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1890 switch (Tag) {
1891 case TagTypeKind::Struct:
1892 return 0;
1893 case TagTypeKind::Interface:
1894 return 1;
1895 case TagTypeKind::Class:
1896 return 2;
1897 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1898 }
1899}
1900
1901static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1902 Stmt *Body,
1903 Sema::CheckConstexprKind Kind);
1904static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1905
1906bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1907 CheckConstexprKind Kind) {
1908 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
1909 if (MD && MD->isInstance()) {
1910 // C++11 [dcl.constexpr]p4:
1911 // The definition of a constexpr constructor shall satisfy the following
1912 // constraints:
1913 // - the class shall not have any virtual base classes;
1914 //
1915 // FIXME: This only applies to constructors and destructors, not arbitrary
1916 // member functions.
1917 const CXXRecordDecl *RD = MD->getParent();
1918 if (RD->getNumVBases()) {
1919 if (Kind == CheckConstexprKind::CheckValid)
1920 return false;
1921
1922 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_constexpr_virtual_base)
1923 << isa<CXXConstructorDecl>(Val: NewFD)
1924 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD->getNumVBases();
1925 for (const auto &I : RD->vbases())
1926 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here)
1927 << I.getSourceRange();
1928 return false;
1929 }
1930 }
1931
1932 if (!isa<CXXConstructorDecl>(Val: NewFD)) {
1933 // C++11 [dcl.constexpr]p3:
1934 // The definition of a constexpr function shall satisfy the following
1935 // constraints:
1936 // - it shall not be virtual; (removed in C++20)
1937 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD);
1938 if (Method && Method->isVirtual()) {
1939 if (getLangOpts().CPlusPlus20) {
1940 if (Kind == CheckConstexprKind::Diagnose)
1941 Diag(Loc: Method->getLocation(), DiagID: diag::warn_cxx17_compat_constexpr_virtual);
1942 } else {
1943 if (Kind == CheckConstexprKind::CheckValid)
1944 return false;
1945
1946 Method = Method->getCanonicalDecl();
1947 Diag(Loc: Method->getLocation(), DiagID: diag::err_constexpr_virtual);
1948
1949 // If it's not obvious why this function is virtual, find an overridden
1950 // function which uses the 'virtual' keyword.
1951 const CXXMethodDecl *WrittenVirtual = Method;
1952 while (!WrittenVirtual->isVirtualAsWritten())
1953 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1954 if (WrittenVirtual != Method)
1955 Diag(Loc: WrittenVirtual->getLocation(),
1956 DiagID: diag::note_overridden_virtual_function);
1957 return false;
1958 }
1959 }
1960
1961 // - its return type shall be a literal type; (removed in C++23)
1962 if (!getLangOpts().CPlusPlus23 &&
1963 !CheckConstexprReturnType(SemaRef&: *this, FD: NewFD, Kind))
1964 return false;
1965 }
1966
1967 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
1968 // A destructor can be constexpr only if the defaulted destructor could be;
1969 // we don't need to check the members and bases if we already know they all
1970 // have constexpr destructors. (removed in C++23)
1971 if (!getLangOpts().CPlusPlus23 &&
1972 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1973 if (Kind == CheckConstexprKind::CheckValid)
1974 return false;
1975 if (!CheckConstexprDestructorSubobjects(SemaRef&: *this, DD: Dtor, Kind))
1976 return false;
1977 }
1978 }
1979
1980 // - each of its parameter types shall be a literal type; (removed in C++23)
1981 if (!getLangOpts().CPlusPlus23 &&
1982 !CheckConstexprParameterTypes(SemaRef&: *this, FD: NewFD, Kind))
1983 return false;
1984
1985 Stmt *Body = NewFD->getBody();
1986 assert(Body &&
1987 "CheckConstexprFunctionDefinition called on function with no body");
1988 return CheckConstexprFunctionBody(SemaRef&: *this, Dcl: NewFD, Body, Kind);
1989}
1990
1991/// Check the given declaration statement is legal within a constexpr function
1992/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1993///
1994/// \return true if the body is OK (maybe only as an extension), false if we
1995/// have diagnosed a problem.
1996static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1997 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1998 Sema::CheckConstexprKind Kind) {
1999 // C++11 [dcl.constexpr]p3 and p4:
2000 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2001 // contain only
2002 for (const auto *DclIt : DS->decls()) {
2003 switch (DclIt->getKind()) {
2004 case Decl::StaticAssert:
2005 case Decl::Using:
2006 case Decl::UsingShadow:
2007 case Decl::UsingDirective:
2008 case Decl::UnresolvedUsingTypename:
2009 case Decl::UnresolvedUsingValue:
2010 case Decl::UsingEnum:
2011 // - static_assert-declarations
2012 // - using-declarations,
2013 // - using-directives,
2014 // - using-enum-declaration
2015 continue;
2016
2017 case Decl::Typedef:
2018 case Decl::TypeAlias: {
2019 // - typedef declarations and alias-declarations that do not define
2020 // classes or enumerations,
2021 const auto *TN = cast<TypedefNameDecl>(Val: DclIt);
2022 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2023 // Don't allow variably-modified types in constexpr functions.
2024 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2025 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2026 SemaRef.Diag(Loc: TL.getBeginLoc(), DiagID: diag::err_constexpr_vla)
2027 << TL.getSourceRange() << TL.getType()
2028 << isa<CXXConstructorDecl>(Val: Dcl);
2029 }
2030 return false;
2031 }
2032 continue;
2033 }
2034
2035 case Decl::Enum:
2036 case Decl::CXXRecord:
2037 // C++1y allows types to be defined, not just declared.
2038 if (cast<TagDecl>(Val: DclIt)->isThisDeclarationADefinition()) {
2039 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2040 SemaRef.DiagCompat(Loc: DS->getBeginLoc(),
2041 CompatDiagId: diag_compat::constexpr_type_definition)
2042 << isa<CXXConstructorDecl>(Val: Dcl);
2043 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2044 return false;
2045 }
2046 }
2047 continue;
2048
2049 case Decl::EnumConstant:
2050 case Decl::IndirectField:
2051 case Decl::ParmVar:
2052 // These can only appear with other declarations which are banned in
2053 // C++11 and permitted in C++1y, so ignore them.
2054 continue;
2055
2056 case Decl::Var:
2057 case Decl::Decomposition: {
2058 // C++1y [dcl.constexpr]p3 allows anything except:
2059 // a definition of a variable of non-literal type or of static or
2060 // thread storage duration or [before C++2a] for which no
2061 // initialization is performed.
2062 const auto *VD = cast<VarDecl>(Val: DclIt);
2063 if (VD->isThisDeclarationADefinition()) {
2064 if (VD->isStaticLocal()) {
2065 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2066 SemaRef.DiagCompat(Loc: VD->getLocation(),
2067 CompatDiagId: diag_compat::constexpr_static_var)
2068 << isa<CXXConstructorDecl>(Val: Dcl)
2069 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2070 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2071 return false;
2072 }
2073 }
2074 if (SemaRef.LangOpts.CPlusPlus23) {
2075 CheckLiteralType(SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2076 DiagID: diag::warn_cxx20_compat_constexpr_var,
2077 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl));
2078 } else if (CheckLiteralType(
2079 SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2080 DiagID: diag::err_constexpr_local_var_non_literal_type,
2081 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl))) {
2082 return false;
2083 }
2084 if (!VD->getType()->isDependentType() &&
2085 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2086 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2087 SemaRef.DiagCompat(Loc: VD->getLocation(),
2088 CompatDiagId: diag_compat::constexpr_local_var_no_init)
2089 << isa<CXXConstructorDecl>(Val: Dcl);
2090 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2091 return false;
2092 }
2093 continue;
2094 }
2095 }
2096 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2097 SemaRef.DiagCompat(Loc: VD->getLocation(), CompatDiagId: diag_compat::constexpr_local_var)
2098 << isa<CXXConstructorDecl>(Val: Dcl);
2099 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2100 return false;
2101 }
2102 continue;
2103 }
2104
2105 case Decl::NamespaceAlias:
2106 case Decl::Function:
2107 // These are disallowed in C++11 and permitted in C++1y. Allow them
2108 // everywhere as an extension.
2109 if (!Cxx1yLoc.isValid())
2110 Cxx1yLoc = DS->getBeginLoc();
2111 continue;
2112
2113 default:
2114 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2115 SemaRef.Diag(Loc: DS->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2116 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2117 }
2118 return false;
2119 }
2120 }
2121
2122 return true;
2123}
2124
2125/// Check that the given field is initialized within a constexpr constructor.
2126///
2127/// \param Dcl The constexpr constructor being checked.
2128/// \param Field The field being checked. This may be a member of an anonymous
2129/// struct or union nested within the class being checked.
2130/// \param Inits All declarations, including anonymous struct/union members and
2131/// indirect members, for which any initialization was provided.
2132/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2133/// multiple notes for different members to the same error.
2134/// \param Kind Whether we're diagnosing a constructor as written or determining
2135/// whether the formal requirements are satisfied.
2136/// \return \c false if we're checking for validity and the constructor does
2137/// not satisfy the requirements on a constexpr constructor.
2138static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2139 const FunctionDecl *Dcl,
2140 FieldDecl *Field,
2141 llvm::SmallSet<Decl*, 16> &Inits,
2142 bool &Diagnosed,
2143 Sema::CheckConstexprKind Kind) {
2144 // In C++20 onwards, there's nothing to check for validity.
2145 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2146 SemaRef.getLangOpts().CPlusPlus20)
2147 return true;
2148
2149 if (Field->isInvalidDecl())
2150 return true;
2151
2152 if (Field->isUnnamedBitField())
2153 return true;
2154
2155 // Anonymous unions with no variant members and empty anonymous structs do not
2156 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2157 // indirect fields don't need initializing.
2158 if (Field->isAnonymousStructOrUnion() &&
2159 (Field->getType()->isUnionType()
2160 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2161 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2162 return true;
2163
2164 if (!Inits.count(Ptr: Field)) {
2165 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2166 if (!Diagnosed) {
2167 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2168 CompatDiagId: diag_compat::constexpr_ctor_missing_init);
2169 Diagnosed = true;
2170 }
2171 SemaRef.Diag(Loc: Field->getLocation(),
2172 DiagID: diag::note_constexpr_ctor_missing_init);
2173 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2174 return false;
2175 }
2176 } else if (Field->isAnonymousStructOrUnion()) {
2177 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2178 for (auto *I : RD->fields())
2179 // If an anonymous union contains an anonymous struct of which any member
2180 // is initialized, all members must be initialized.
2181 if (!RD->isUnion() || Inits.count(Ptr: I))
2182 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2183 Kind))
2184 return false;
2185 }
2186 return true;
2187}
2188
2189/// Check the provided statement is allowed in a constexpr function
2190/// definition.
2191static bool
2192CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2193 SmallVectorImpl<SourceLocation> &ReturnStmts,
2194 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2195 SourceLocation &Cxx2bLoc,
2196 Sema::CheckConstexprKind Kind) {
2197 // - its function-body shall be [...] a compound-statement that contains only
2198 switch (S->getStmtClass()) {
2199 case Stmt::NullStmtClass:
2200 // - null statements,
2201 return true;
2202
2203 case Stmt::DeclStmtClass:
2204 // - static_assert-declarations
2205 // - using-declarations,
2206 // - using-directives,
2207 // - typedef declarations and alias-declarations that do not define
2208 // classes or enumerations,
2209 if (!CheckConstexprDeclStmt(SemaRef, Dcl, DS: cast<DeclStmt>(Val: S), Cxx1yLoc, Kind))
2210 return false;
2211 return true;
2212
2213 case Stmt::ReturnStmtClass:
2214 // - and exactly one return statement;
2215 if (isa<CXXConstructorDecl>(Val: Dcl)) {
2216 // C++1y allows return statements in constexpr constructors.
2217 if (!Cxx1yLoc.isValid())
2218 Cxx1yLoc = S->getBeginLoc();
2219 return true;
2220 }
2221
2222 ReturnStmts.push_back(Elt: S->getBeginLoc());
2223 return true;
2224
2225 case Stmt::AttributedStmtClass:
2226 // Attributes on a statement don't affect its formal kind and hence don't
2227 // affect its validity in a constexpr function.
2228 return CheckConstexprFunctionStmt(
2229 SemaRef, Dcl, S: cast<AttributedStmt>(Val: S)->getSubStmt(), ReturnStmts,
2230 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2231
2232 case Stmt::CompoundStmtClass: {
2233 // C++1y allows compound-statements.
2234 if (!Cxx1yLoc.isValid())
2235 Cxx1yLoc = S->getBeginLoc();
2236
2237 CompoundStmt *CompStmt = cast<CompoundStmt>(Val: S);
2238 for (auto *BodyIt : CompStmt->body()) {
2239 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts,
2240 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2241 return false;
2242 }
2243 return true;
2244 }
2245
2246 case Stmt::IfStmtClass: {
2247 // C++1y allows if-statements.
2248 if (!Cxx1yLoc.isValid())
2249 Cxx1yLoc = S->getBeginLoc();
2250
2251 IfStmt *If = cast<IfStmt>(Val: S);
2252 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getThen(), ReturnStmts,
2253 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2254 return false;
2255 if (If->getElse() &&
2256 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getElse(), ReturnStmts,
2257 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2258 return false;
2259 return true;
2260 }
2261
2262 case Stmt::WhileStmtClass:
2263 case Stmt::DoStmtClass:
2264 case Stmt::ForStmtClass:
2265 case Stmt::CXXForRangeStmtClass:
2266 case Stmt::ContinueStmtClass:
2267 // C++1y allows all of these. We don't allow them as extensions in C++11,
2268 // because they don't make sense without variable mutation.
2269 if (!SemaRef.getLangOpts().CPlusPlus14)
2270 break;
2271 if (!Cxx1yLoc.isValid())
2272 Cxx1yLoc = S->getBeginLoc();
2273 for (Stmt *SubStmt : S->children()) {
2274 if (SubStmt &&
2275 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2276 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2277 return false;
2278 }
2279 return true;
2280
2281 case Stmt::SwitchStmtClass:
2282 case Stmt::CaseStmtClass:
2283 case Stmt::DefaultStmtClass:
2284 case Stmt::BreakStmtClass:
2285 // C++1y allows switch-statements, and since they don't need variable
2286 // mutation, we can reasonably allow them in C++11 as an extension.
2287 if (!Cxx1yLoc.isValid())
2288 Cxx1yLoc = S->getBeginLoc();
2289 for (Stmt *SubStmt : S->children()) {
2290 if (SubStmt &&
2291 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2292 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2293 return false;
2294 }
2295 return true;
2296
2297 case Stmt::LabelStmtClass:
2298 case Stmt::GotoStmtClass:
2299 if (Cxx2bLoc.isInvalid())
2300 Cxx2bLoc = S->getBeginLoc();
2301 for (Stmt *SubStmt : S->children()) {
2302 if (SubStmt &&
2303 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2304 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2305 return false;
2306 }
2307 return true;
2308
2309 case Stmt::GCCAsmStmtClass:
2310 case Stmt::MSAsmStmtClass:
2311 // C++2a allows inline assembly statements.
2312 case Stmt::CXXTryStmtClass:
2313 if (Cxx2aLoc.isInvalid())
2314 Cxx2aLoc = S->getBeginLoc();
2315 for (Stmt *SubStmt : S->children()) {
2316 if (SubStmt &&
2317 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2318 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2319 return false;
2320 }
2321 return true;
2322
2323 case Stmt::CXXCatchStmtClass:
2324 // Do not bother checking the language mode (already covered by the
2325 // try block check).
2326 if (!CheckConstexprFunctionStmt(
2327 SemaRef, Dcl, S: cast<CXXCatchStmt>(Val: S)->getHandlerBlock(), ReturnStmts,
2328 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2329 return false;
2330 return true;
2331
2332 default:
2333 if (!isa<Expr>(Val: S))
2334 break;
2335
2336 // C++1y allows expression-statements.
2337 if (!Cxx1yLoc.isValid())
2338 Cxx1yLoc = S->getBeginLoc();
2339 return true;
2340 }
2341
2342 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2343 SemaRef.Diag(Loc: S->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2344 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2345 }
2346 return false;
2347}
2348
2349/// Check the body for the given constexpr function declaration only contains
2350/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2351///
2352/// \return true if the body is OK, false if we have found or diagnosed a
2353/// problem.
2354static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2355 Stmt *Body,
2356 Sema::CheckConstexprKind Kind) {
2357 SmallVector<SourceLocation, 4> ReturnStmts;
2358
2359 if (isa<CXXTryStmt>(Val: Body)) {
2360 // C++11 [dcl.constexpr]p3:
2361 // The definition of a constexpr function shall satisfy the following
2362 // constraints: [...]
2363 // - its function-body shall be = delete, = default, or a
2364 // compound-statement
2365 //
2366 // C++11 [dcl.constexpr]p4:
2367 // In the definition of a constexpr constructor, [...]
2368 // - its function-body shall not be a function-try-block;
2369 //
2370 // This restriction is lifted in C++2a, as long as inner statements also
2371 // apply the general constexpr rules.
2372 switch (Kind) {
2373 case Sema::CheckConstexprKind::CheckValid:
2374 if (!SemaRef.getLangOpts().CPlusPlus20)
2375 return false;
2376 break;
2377
2378 case Sema::CheckConstexprKind::Diagnose:
2379 SemaRef.DiagCompat(Loc: Body->getBeginLoc(),
2380 CompatDiagId: diag_compat::constexpr_function_try_block)
2381 << isa<CXXConstructorDecl>(Val: Dcl);
2382 break;
2383 }
2384 }
2385
2386 // - its function-body shall be [...] a compound-statement that contains only
2387 // [... list of cases ...]
2388 //
2389 // Note that walking the children here is enough to properly check for
2390 // CompoundStmt and CXXTryStmt body.
2391 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2392 for (Stmt *SubStmt : Body->children()) {
2393 if (SubStmt &&
2394 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2395 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2396 return false;
2397 }
2398
2399 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2400 // If this is only valid as an extension, report that we don't satisfy the
2401 // constraints of the current language.
2402 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2403 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2404 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2405 return false;
2406 } else if (Cxx2bLoc.isValid()) {
2407 SemaRef.DiagCompat(Loc: Cxx2bLoc, CompatDiagId: diag_compat::cxx23_constexpr_body_invalid_stmt)
2408 << isa<CXXConstructorDecl>(Val: Dcl);
2409 } else if (Cxx2aLoc.isValid()) {
2410 SemaRef.DiagCompat(Loc: Cxx2aLoc, CompatDiagId: diag_compat::cxx20_constexpr_body_invalid_stmt)
2411 << isa<CXXConstructorDecl>(Val: Dcl);
2412 } else if (Cxx1yLoc.isValid()) {
2413 SemaRef.DiagCompat(Loc: Cxx1yLoc, CompatDiagId: diag_compat::cxx14_constexpr_body_invalid_stmt)
2414 << isa<CXXConstructorDecl>(Val: Dcl);
2415 }
2416
2417 if (const CXXConstructorDecl *Constructor
2418 = dyn_cast<CXXConstructorDecl>(Val: Dcl)) {
2419 const CXXRecordDecl *RD = Constructor->getParent();
2420 // DR1359:
2421 // - every non-variant non-static data member and base class sub-object
2422 // shall be initialized;
2423 // DR1460:
2424 // - if the class is a union having variant members, exactly one of them
2425 // shall be initialized;
2426 if (RD->isUnion()) {
2427 if (Constructor->getNumCtorInitializers() == 0 &&
2428 RD->hasVariantMembers()) {
2429 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2430 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2431 CompatDiagId: diag_compat::constexpr_union_ctor_no_init);
2432 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2433 return false;
2434 }
2435 }
2436 } else if (!Constructor->isDependentContext() &&
2437 !Constructor->isDelegatingConstructor()) {
2438 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2439
2440 // Skip detailed checking if we have enough initializers, and we would
2441 // allow at most one initializer per member.
2442 bool AnyAnonStructUnionMembers = false;
2443 unsigned Fields = 0;
2444 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2445 E = RD->field_end(); I != E; ++I, ++Fields) {
2446 if (I->isAnonymousStructOrUnion()) {
2447 AnyAnonStructUnionMembers = true;
2448 break;
2449 }
2450 }
2451 // DR1460:
2452 // - if the class is a union-like class, but is not a union, for each of
2453 // its anonymous union members having variant members, exactly one of
2454 // them shall be initialized;
2455 if (AnyAnonStructUnionMembers ||
2456 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2457 // Check initialization of non-static data members. Base classes are
2458 // always initialized so do not need to be checked. Dependent bases
2459 // might not have initializers in the member initializer list.
2460 llvm::SmallSet<Decl*, 16> Inits;
2461 for (const auto *I: Constructor->inits()) {
2462 if (FieldDecl *FD = I->getMember())
2463 Inits.insert(Ptr: FD);
2464 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2465 Inits.insert(I: ID->chain_begin(), E: ID->chain_end());
2466 }
2467
2468 bool Diagnosed = false;
2469 for (auto *I : RD->fields())
2470 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2471 Kind))
2472 return false;
2473 }
2474 }
2475 } else {
2476 if (ReturnStmts.empty()) {
2477 switch (Kind) {
2478 case Sema::CheckConstexprKind::Diagnose:
2479 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2480 return false;
2481 break;
2482
2483 case Sema::CheckConstexprKind::CheckValid:
2484 // The formal requirements don't include this rule in C++14, even
2485 // though the "must be able to produce a constant expression" rules
2486 // still imply it in some cases.
2487 if (!SemaRef.getLangOpts().CPlusPlus14)
2488 return false;
2489 break;
2490 }
2491 } else if (ReturnStmts.size() > 1) {
2492 switch (Kind) {
2493 case Sema::CheckConstexprKind::Diagnose:
2494 SemaRef.DiagCompat(Loc: ReturnStmts.back(),
2495 CompatDiagId: diag_compat::constexpr_body_multiple_return);
2496 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2497 SemaRef.Diag(Loc: ReturnStmts[I],
2498 DiagID: diag::note_constexpr_body_previous_return);
2499 break;
2500
2501 case Sema::CheckConstexprKind::CheckValid:
2502 if (!SemaRef.getLangOpts().CPlusPlus14)
2503 return false;
2504 break;
2505 }
2506 }
2507 }
2508
2509 // C++11 [dcl.constexpr]p5:
2510 // if no function argument values exist such that the function invocation
2511 // substitution would produce a constant expression, the program is
2512 // ill-formed; no diagnostic required.
2513 // C++11 [dcl.constexpr]p3:
2514 // - every constructor call and implicit conversion used in initializing the
2515 // return value shall be one of those allowed in a constant expression.
2516 // C++11 [dcl.constexpr]p4:
2517 // - every constructor involved in initializing non-static data members and
2518 // base class sub-objects shall be a constexpr constructor.
2519 //
2520 // Note that this rule is distinct from the "requirements for a constexpr
2521 // function", so is not checked in CheckValid mode. Because the check for
2522 // constexpr potential is expensive, skip the check if the diagnostic is
2523 // disabled, the function is declared in a system header, or we're in C++23
2524 // or later mode (see https://wg21.link/P2448).
2525 bool SkipCheck =
2526 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2527 SemaRef.getSourceManager().isInSystemHeader(Loc: Dcl->getLocation()) ||
2528 SemaRef.getDiagnostics().isIgnored(
2529 DiagID: diag::ext_constexpr_function_never_constant_expr, Loc: Dcl->getLocation());
2530 SmallVector<PartialDiagnosticAt, 8> Diags;
2531 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2532 !Expr::isPotentialConstantExpr(FD: Dcl, Diags)) {
2533 SemaRef.Diag(Loc: Dcl->getLocation(),
2534 DiagID: diag::ext_constexpr_function_never_constant_expr)
2535 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval()
2536 << Dcl->getNameInfo().getSourceRange();
2537 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2538 SemaRef.Diag(Loc: Diags[I].first, PD: Diags[I].second);
2539 // Don't return false here: we allow this for compatibility in
2540 // system headers.
2541 }
2542
2543 return true;
2544}
2545
2546static bool CheckConstexprMissingReturn(Sema &SemaRef,
2547 const FunctionDecl *Dcl) {
2548 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2549 Dcl->getReturnType()->isDependentType();
2550 // Skip emitting a missing return error diagnostic for non-void functions
2551 // since C++23 no longer mandates constexpr functions to yield constant
2552 // expressions.
2553 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2554 return true;
2555
2556 // C++14 doesn't require constexpr functions to contain a 'return'
2557 // statement. We still do, unless the return type might be void, because
2558 // otherwise if there's no return statement, the function cannot
2559 // be used in a core constant expression.
2560 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2561 SemaRef.Diag(Loc: Dcl->getLocation(),
2562 DiagID: OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2563 : diag::err_constexpr_body_no_return)
2564 << Dcl->isConsteval();
2565 return OK;
2566}
2567
2568bool Sema::CheckImmediateEscalatingFunctionDefinition(
2569 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2570 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2571 return true;
2572 FD->setBodyContainsImmediateEscalatingExpressions(
2573 FSI->FoundImmediateEscalatingExpression);
2574 if (FSI->FoundImmediateEscalatingExpression) {
2575 auto it = UndefinedButUsed.find(Key: FD->getCanonicalDecl());
2576 if (it != UndefinedButUsed.end()) {
2577 Diag(Loc: it->second, DiagID: diag::err_immediate_function_used_before_definition)
2578 << it->first;
2579 Diag(Loc: FD->getLocation(), DiagID: diag::note_defined_here) << FD;
2580 if (FD->isImmediateFunction() && !FD->isConsteval())
2581 DiagnoseImmediateEscalatingReason(FD);
2582 return false;
2583 }
2584 }
2585 return true;
2586}
2587
2588void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2589 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2590 "expected an immediate function");
2591 assert(FD->hasBody() && "expected the function to have a body");
2592 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2593 Sema &SemaRef;
2594
2595 const FunctionDecl *ImmediateFn;
2596 bool ImmediateFnIsConstructor;
2597 CXXConstructorDecl *CurrentConstructor = nullptr;
2598 CXXCtorInitializer *CurrentInit = nullptr;
2599
2600 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2601 : SemaRef(SemaRef), ImmediateFn(FD),
2602 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(Val: FD)) {
2603 ShouldVisitImplicitCode = true;
2604 ShouldVisitLambdaBody = false;
2605 }
2606
2607 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2608 SourceLocation Loc = E->getBeginLoc();
2609 SourceRange Range = E->getSourceRange();
2610 if (CurrentConstructor && CurrentInit) {
2611 Loc = CurrentConstructor->getLocation();
2612 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2613 : SourceRange();
2614 }
2615
2616 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2617
2618 SemaRef.Diag(Loc, DiagID: diag::note_immediate_function_reason)
2619 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2620 << isa<CXXConstructorDecl>(Val: Fn) << ImmediateFnIsConstructor
2621 << (InitializedField != nullptr)
2622 << (CurrentInit && !CurrentInit->isWritten())
2623 << InitializedField << Range;
2624 }
2625 bool TraverseCallExpr(CallExpr *E) override {
2626 if (const auto *DR =
2627 dyn_cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit());
2628 DR && DR->isImmediateEscalating()) {
2629 Diag(E, Fn: E->getDirectCallee(), /*IsCall=*/true);
2630 return false;
2631 }
2632
2633 for (Expr *A : E->arguments())
2634 if (!TraverseStmt(S: A))
2635 return false;
2636
2637 return true;
2638 }
2639
2640 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2641 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(Val: E->getDecl());
2642 ReferencedFn && E->isImmediateEscalating()) {
2643 Diag(E, Fn: ReferencedFn, /*IsCall=*/false);
2644 return false;
2645 }
2646
2647 return true;
2648 }
2649
2650 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2651 CXXConstructorDecl *D = E->getConstructor();
2652 if (E->isImmediateEscalating()) {
2653 Diag(E, Fn: D, /*IsCall=*/true);
2654 return false;
2655 }
2656 return true;
2657 }
2658
2659 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2660 llvm::SaveAndRestore RAII(CurrentInit, Init);
2661 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init);
2662 }
2663
2664 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2665 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2666 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(D: Ctr);
2667 }
2668
2669 bool TraverseType(QualType T) override { return true; }
2670 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2671
2672 } Visitor(*this, FD);
2673 Visitor.TraverseDecl(D: FD);
2674}
2675
2676CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2677 assert(getLangOpts().CPlusPlus && "No class names in C!");
2678
2679 if (SS && SS->isInvalid())
2680 return nullptr;
2681
2682 if (SS && SS->isNotEmpty()) {
2683 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2684 return dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2685 }
2686
2687 return dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2688}
2689
2690bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2691 const CXXScopeSpec *SS) {
2692 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2693 return CurDecl && &II == CurDecl->getIdentifier();
2694}
2695
2696bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2697 assert(getLangOpts().CPlusPlus && "No class names in C!");
2698
2699 if (!getLangOpts().SpellChecking)
2700 return false;
2701
2702 CXXRecordDecl *CurDecl;
2703 if (SS && SS->isSet() && !SS->isInvalid()) {
2704 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2705 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2706 } else
2707 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2708
2709 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2710 3 * II->getName().edit_distance(Other: CurDecl->getIdentifier()->getName())
2711 < II->getLength()) {
2712 II = CurDecl->getIdentifier();
2713 return true;
2714 }
2715
2716 return false;
2717}
2718
2719CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2720 SourceRange SpecifierRange,
2721 bool Virtual, AccessSpecifier Access,
2722 TypeSourceInfo *TInfo,
2723 SourceLocation EllipsisLoc) {
2724 QualType BaseType = TInfo->getType();
2725 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2726 if (BaseType->containsErrors()) {
2727 // Already emitted a diagnostic when parsing the error type.
2728 return nullptr;
2729 }
2730
2731 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2732 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
2733 << TInfo->getTypeLoc().getSourceRange();
2734 EllipsisLoc = SourceLocation();
2735 }
2736
2737 auto *BaseDecl =
2738 dyn_cast_if_present<CXXRecordDecl>(Val: computeDeclContext(T: BaseType));
2739 // C++ [class.derived.general]p2:
2740 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2741 // that is not an incompletely defined class; any cv-qualifiers are
2742 // ignored.
2743 if (BaseDecl) {
2744 // C++ [class.union.general]p4:
2745 // [...] A union shall not be used as a base class.
2746 if (BaseDecl->isUnion()) {
2747 Diag(Loc: BaseLoc, DiagID: diag::err_union_as_base_class) << SpecifierRange;
2748 return nullptr;
2749 }
2750
2751 if (BaseType.hasQualifiers()) {
2752 std::string Quals =
2753 BaseType.getQualifiers().getAsString(Policy: Context.getPrintingPolicy());
2754 Diag(Loc: BaseLoc, DiagID: diag::warn_qual_base_type)
2755 << Quals << llvm::count(Range&: Quals, Element: ' ') + 1 << BaseType;
2756 Diag(Loc: BaseLoc, DiagID: diag::note_base_class_specified_here) << BaseType;
2757 }
2758
2759 // For the MS ABI, propagate DLL attributes to base class templates.
2760 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2761 Context.getTargetInfo().getTriple().isPS()) {
2762 if (Attr *ClassAttr = getDLLAttr(D: Class)) {
2763 if (auto *BaseSpec =
2764 dyn_cast<ClassTemplateSpecializationDecl>(Val: BaseDecl)) {
2765 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplateSpec: BaseSpec,
2766 BaseLoc);
2767 }
2768 }
2769 }
2770
2771 if (RequireCompleteType(Loc: BaseLoc, T: BaseType, DiagID: diag::err_incomplete_base_class,
2772 Args: SpecifierRange)) {
2773 Class->setInvalidDecl();
2774 return nullptr;
2775 }
2776
2777 BaseDecl = BaseDecl->getDefinition();
2778 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2779
2780 // Microsoft docs say:
2781 // "If a base-class has a code_seg attribute, derived classes must have the
2782 // same attribute."
2783 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2784 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2785 if ((DerivedCSA || BaseCSA) &&
2786 (!BaseCSA || !DerivedCSA ||
2787 BaseCSA->getName() != DerivedCSA->getName())) {
2788 Diag(Loc: Class->getLocation(), DiagID: diag::err_mismatched_code_seg_base);
2789 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_base_class_specified_here)
2790 << BaseDecl;
2791 return nullptr;
2792 }
2793
2794 // A class which contains a flexible array member is not suitable for use as
2795 // a base class:
2796 // - If the layout determines that a base comes before another base,
2797 // the flexible array member would index into the subsequent base.
2798 // - If the layout determines that base comes before the derived class,
2799 // the flexible array member would index into the derived class.
2800 if (BaseDecl->hasFlexibleArrayMember()) {
2801 Diag(Loc: BaseLoc, DiagID: diag::err_base_class_has_flexible_array_member)
2802 << BaseDecl->getDeclName();
2803 return nullptr;
2804 }
2805
2806 // C++ [class]p3:
2807 // If a class is marked final and it appears as a base-type-specifier in
2808 // base-clause, the program is ill-formed.
2809 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2810 Diag(Loc: BaseLoc, DiagID: diag::err_class_marked_final_used_as_base)
2811 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2812 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_entity_declared_at)
2813 << BaseDecl->getDeclName() << FA->getRange();
2814 return nullptr;
2815 }
2816
2817 // If the base class is invalid the derived class is as well.
2818 if (BaseDecl->isInvalidDecl())
2819 Class->setInvalidDecl();
2820 } else if (BaseType->isDependentType()) {
2821 // Make sure that we don't make an ill-formed AST where the type of the
2822 // Class is non-dependent and its attached base class specifier is an
2823 // dependent type, which violates invariants in many clang code paths (e.g.
2824 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2825 // explicitly mark the Class decl invalid. The diagnostic was already
2826 // emitted.
2827 if (!Class->isDependentContext())
2828 Class->setInvalidDecl();
2829 } else {
2830 // The base class is some non-dependent non-class type.
2831 Diag(Loc: BaseLoc, DiagID: diag::err_base_must_be_class) << SpecifierRange;
2832 return nullptr;
2833 }
2834
2835 // In HLSL, unspecified class access is public rather than private.
2836 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2837 Access == AS_none)
2838 Access = AS_public;
2839
2840 // Create the base specifier.
2841 return new (Context) CXXBaseSpecifier(
2842 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2843 Access, TInfo, EllipsisLoc);
2844}
2845
2846BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2847 const ParsedAttributesView &Attributes,
2848 bool Virtual, AccessSpecifier Access,
2849 ParsedType basetype, SourceLocation BaseLoc,
2850 SourceLocation EllipsisLoc) {
2851 if (!classdecl)
2852 return true;
2853
2854 AdjustDeclIfTemplate(Decl&: classdecl);
2855 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: classdecl);
2856 if (!Class)
2857 return true;
2858
2859 // We haven't yet attached the base specifiers.
2860 Class->setIsParsingBaseSpecifiers();
2861
2862 // We do not support any C++11 attributes on base-specifiers yet.
2863 // Diagnose any attributes we see.
2864 for (const ParsedAttr &AL : Attributes) {
2865 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2866 continue;
2867 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2868 DiagnoseUnknownAttribute(AL);
2869 else
2870 Diag(Loc: AL.getLoc(), DiagID: diag::err_base_specifier_attribute)
2871 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2872 }
2873
2874 TypeSourceInfo *TInfo = nullptr;
2875 GetTypeFromParser(Ty: basetype, TInfo: &TInfo);
2876
2877 if (EllipsisLoc.isInvalid() &&
2878 DiagnoseUnexpandedParameterPack(Loc: SpecifierRange.getBegin(), T: TInfo,
2879 UPPC: UPPC_BaseType))
2880 return true;
2881
2882 // C++ [class.union.general]p4:
2883 // [...] A union shall not have base classes.
2884 if (Class->isUnion()) {
2885 Diag(Loc: Class->getLocation(), DiagID: diag::err_base_clause_on_union)
2886 << SpecifierRange;
2887 return true;
2888 }
2889
2890 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2891 Virtual, Access, TInfo,
2892 EllipsisLoc))
2893 return BaseSpec;
2894
2895 Class->setInvalidDecl();
2896 return true;
2897}
2898
2899/// Use small set to collect indirect bases. As this is only used
2900/// locally, there's no need to abstract the small size parameter.
2901typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2902
2903/// Recursively add the bases of Type. Don't add Type itself.
2904static void
2905NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2906 const QualType &Type)
2907{
2908 // Even though the incoming type is a base, it might not be
2909 // a class -- it could be a template parm, for instance.
2910 if (auto Rec = Type->getAs<RecordType>()) {
2911 auto Decl = Rec->getAsCXXRecordDecl();
2912
2913 // Iterate over its bases.
2914 for (const auto &BaseSpec : Decl->bases()) {
2915 QualType Base = Context.getCanonicalType(T: BaseSpec.getType())
2916 .getUnqualifiedType();
2917 if (Set.insert(Ptr: Base).second)
2918 // If we've not already seen it, recurse.
2919 NoteIndirectBases(Context, Set, Type: Base);
2920 }
2921 }
2922}
2923
2924bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2925 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2926 if (Bases.empty())
2927 return false;
2928
2929 // Used to keep track of which base types we have already seen, so
2930 // that we can properly diagnose redundant direct base types. Note
2931 // that the key is always the unqualified canonical type of the base
2932 // class.
2933 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2934
2935 // Used to track indirect bases so we can see if a direct base is
2936 // ambiguous.
2937 IndirectBaseSet IndirectBaseTypes;
2938
2939 // Copy non-redundant base specifiers into permanent storage.
2940 unsigned NumGoodBases = 0;
2941 bool Invalid = false;
2942 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2943 QualType NewBaseType
2944 = Context.getCanonicalType(T: Bases[idx]->getType());
2945 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2946
2947 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2948 if (KnownBase) {
2949 // C++ [class.mi]p3:
2950 // A class shall not be specified as a direct base class of a
2951 // derived class more than once.
2952 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::err_duplicate_base_class)
2953 << KnownBase->getType() << Bases[idx]->getSourceRange();
2954
2955 // Delete the duplicate base class specifier; we're going to
2956 // overwrite its pointer later.
2957 Context.Deallocate(Ptr: Bases[idx]);
2958
2959 Invalid = true;
2960 } else {
2961 // Okay, add this new base class.
2962 KnownBase = Bases[idx];
2963 Bases[NumGoodBases++] = Bases[idx];
2964
2965 if (NewBaseType->isDependentType())
2966 continue;
2967 // Note this base's direct & indirect bases, if there could be ambiguity.
2968 if (Bases.size() > 1)
2969 NoteIndirectBases(Context, Set&: IndirectBaseTypes, Type: NewBaseType);
2970
2971 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2972 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: Record->getDecl());
2973 if (Class->isInterface() &&
2974 (!RD->isInterfaceLike() ||
2975 KnownBase->getAccessSpecifier() != AS_public)) {
2976 // The Microsoft extension __interface does not permit bases that
2977 // are not themselves public interfaces.
2978 Diag(Loc: KnownBase->getBeginLoc(), DiagID: diag::err_invalid_base_in_interface)
2979 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD
2980 << RD->getSourceRange();
2981 Invalid = true;
2982 }
2983 if (RD->hasAttr<WeakAttr>())
2984 Class->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context));
2985 }
2986 }
2987 }
2988
2989 // Attach the remaining base class specifiers to the derived class.
2990 Class->setBases(Bases: Bases.data(), NumBases: NumGoodBases);
2991
2992 // Check that the only base classes that are duplicate are virtual.
2993 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2994 // Check whether this direct base is inaccessible due to ambiguity.
2995 QualType BaseType = Bases[idx]->getType();
2996
2997 // Skip all dependent types in templates being used as base specifiers.
2998 // Checks below assume that the base specifier is a CXXRecord.
2999 if (BaseType->isDependentType())
3000 continue;
3001
3002 CanQualType CanonicalBase = Context.getCanonicalType(T: BaseType)
3003 .getUnqualifiedType();
3004
3005 if (IndirectBaseTypes.count(Ptr: CanonicalBase)) {
3006 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3007 /*DetectVirtual=*/true);
3008 bool found
3009 = Class->isDerivedFrom(Base: CanonicalBase->getAsCXXRecordDecl(), Paths);
3010 assert(found);
3011 (void)found;
3012
3013 if (Paths.isAmbiguous(BaseType: CanonicalBase))
3014 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::warn_inaccessible_base_class)
3015 << BaseType << getAmbiguousPathsDisplayString(Paths)
3016 << Bases[idx]->getSourceRange();
3017 else
3018 assert(Bases[idx]->isVirtual());
3019 }
3020
3021 // Delete the base class specifier, since its data has been copied
3022 // into the CXXRecordDecl.
3023 Context.Deallocate(Ptr: Bases[idx]);
3024 }
3025
3026 return Invalid;
3027}
3028
3029void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3030 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3031 if (!ClassDecl || Bases.empty())
3032 return;
3033
3034 AdjustDeclIfTemplate(Decl&: ClassDecl);
3035 AttachBaseSpecifiers(Class: cast<CXXRecordDecl>(Val: ClassDecl), Bases);
3036}
3037
3038bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3039 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3040 if (!getLangOpts().CPlusPlus)
3041 return false;
3042
3043 if (!Base || !Derived)
3044 return false;
3045
3046 // If either the base or the derived type is invalid, don't try to
3047 // check whether one is derived from the other.
3048 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3049 return false;
3050
3051 // FIXME: In a modules build, do we need the entire path to be visible for us
3052 // to be able to use the inheritance relationship?
3053 if (!isCompleteType(Loc, T: Context.getTypeDeclType(Decl: Derived)) &&
3054 !Derived->isBeingDefined())
3055 return false;
3056
3057 return Derived->isDerivedFrom(Base, Paths);
3058}
3059
3060bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3061 CXXRecordDecl *Base) {
3062 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3063 /*DetectVirtual=*/false);
3064 return IsDerivedFrom(Loc, Derived, Base, Paths);
3065}
3066
3067bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3068 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3069 /*DetectVirtual=*/false);
3070 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3071 Base: Base->getAsCXXRecordDecl(), Paths);
3072}
3073
3074bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3075 CXXBasePaths &Paths) {
3076 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3077 Base: Base->getAsCXXRecordDecl(), Paths);
3078}
3079
3080static void BuildBasePathArray(const CXXBasePath &Path,
3081 CXXCastPath &BasePathArray) {
3082 // We first go backward and check if we have a virtual base.
3083 // FIXME: It would be better if CXXBasePath had the base specifier for
3084 // the nearest virtual base.
3085 unsigned Start = 0;
3086 for (unsigned I = Path.size(); I != 0; --I) {
3087 if (Path[I - 1].Base->isVirtual()) {
3088 Start = I - 1;
3089 break;
3090 }
3091 }
3092
3093 // Now add all bases.
3094 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3095 BasePathArray.push_back(Elt: const_cast<CXXBaseSpecifier*>(Path[I].Base));
3096}
3097
3098
3099void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3100 CXXCastPath &BasePathArray) {
3101 assert(BasePathArray.empty() && "Base path array must be empty!");
3102 assert(Paths.isRecordingPaths() && "Must record paths!");
3103 return ::BuildBasePathArray(Path: Paths.front(), BasePathArray);
3104}
3105
3106bool
3107Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3108 unsigned InaccessibleBaseID,
3109 unsigned AmbiguousBaseConvID,
3110 SourceLocation Loc, SourceRange Range,
3111 DeclarationName Name,
3112 CXXCastPath *BasePath,
3113 bool IgnoreAccess) {
3114 // First, determine whether the path from Derived to Base is
3115 // ambiguous. This is slightly more expensive than checking whether
3116 // the Derived to Base conversion exists, because here we need to
3117 // explore multiple paths to determine if there is an ambiguity.
3118 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3119 /*DetectVirtual=*/false);
3120 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3121 if (!DerivationOkay)
3122 return true;
3123
3124 const CXXBasePath *Path = nullptr;
3125 if (!Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: Base).getUnqualifiedType()))
3126 Path = &Paths.front();
3127
3128 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3129 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3130 // user to access such bases.
3131 if (!Path && getLangOpts().MSVCCompat) {
3132 for (const CXXBasePath &PossiblePath : Paths) {
3133 if (PossiblePath.size() == 1) {
3134 Path = &PossiblePath;
3135 if (AmbiguousBaseConvID)
3136 Diag(Loc, DiagID: diag::ext_ms_ambiguous_direct_base)
3137 << Base << Derived << Range;
3138 break;
3139 }
3140 }
3141 }
3142
3143 if (Path) {
3144 if (!IgnoreAccess) {
3145 // Check that the base class can be accessed.
3146 switch (
3147 CheckBaseClassAccess(AccessLoc: Loc, Base, Derived, Path: *Path, DiagID: InaccessibleBaseID)) {
3148 case AR_inaccessible:
3149 return true;
3150 case AR_accessible:
3151 case AR_dependent:
3152 case AR_delayed:
3153 break;
3154 }
3155 }
3156
3157 // Build a base path if necessary.
3158 if (BasePath)
3159 ::BuildBasePathArray(Path: *Path, BasePathArray&: *BasePath);
3160 return false;
3161 }
3162
3163 if (AmbiguousBaseConvID) {
3164 // We know that the derived-to-base conversion is ambiguous, and
3165 // we're going to produce a diagnostic. Perform the derived-to-base
3166 // search just one more time to compute all of the possible paths so
3167 // that we can print them out. This is more expensive than any of
3168 // the previous derived-to-base checks we've done, but at this point
3169 // performance isn't as much of an issue.
3170 Paths.clear();
3171 Paths.setRecordingPaths(true);
3172 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3173 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3174 (void)StillOkay;
3175
3176 // Build up a textual representation of the ambiguous paths, e.g.,
3177 // D -> B -> A, that will be used to illustrate the ambiguous
3178 // conversions in the diagnostic. We only print one of the paths
3179 // to each base class subobject.
3180 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3181
3182 Diag(Loc, DiagID: AmbiguousBaseConvID)
3183 << Derived << Base << PathDisplayStr << Range << Name;
3184 }
3185 return true;
3186}
3187
3188bool
3189Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3190 SourceLocation Loc, SourceRange Range,
3191 CXXCastPath *BasePath,
3192 bool IgnoreAccess) {
3193 return CheckDerivedToBaseConversion(
3194 Derived, Base, InaccessibleBaseID: diag::err_upcast_to_inaccessible_base,
3195 AmbiguousBaseConvID: diag::err_ambiguous_derived_to_base_conv, Loc, Range, Name: DeclarationName(),
3196 BasePath, IgnoreAccess);
3197}
3198
3199std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3200 std::string PathDisplayStr;
3201 std::set<unsigned> DisplayedPaths;
3202 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3203 Path != Paths.end(); ++Path) {
3204 if (DisplayedPaths.insert(x: Path->back().SubobjectNumber).second) {
3205 // We haven't displayed a path to this particular base
3206 // class subobject yet.
3207 PathDisplayStr += "\n ";
3208 PathDisplayStr += Context.getTypeDeclType(Decl: Paths.getOrigin()).getAsString();
3209 for (CXXBasePath::const_iterator Element = Path->begin();
3210 Element != Path->end(); ++Element)
3211 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3212 }
3213 }
3214
3215 return PathDisplayStr;
3216}
3217
3218//===----------------------------------------------------------------------===//
3219// C++ class member Handling
3220//===----------------------------------------------------------------------===//
3221
3222bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3223 SourceLocation ColonLoc,
3224 const ParsedAttributesView &Attrs) {
3225 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3226 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(C&: Context, AS: Access, DC: CurContext,
3227 ASLoc, ColonLoc);
3228 CurContext->addHiddenDecl(D: ASDecl);
3229 return ProcessAccessDeclAttributeList(ASDecl, AttrList: Attrs);
3230}
3231
3232void Sema::CheckOverrideControl(NamedDecl *D) {
3233 if (D->isInvalidDecl())
3234 return;
3235
3236 // We only care about "override" and "final" declarations.
3237 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3238 return;
3239
3240 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3241
3242 // We can't check dependent instance methods.
3243 if (MD && MD->isInstance() &&
3244 (MD->getParent()->hasAnyDependentBases() ||
3245 MD->getType()->isDependentType()))
3246 return;
3247
3248 if (MD && !MD->isVirtual()) {
3249 // If we have a non-virtual method, check if it hides a virtual method.
3250 // (In that case, it's most likely the method has the wrong type.)
3251 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3252 FindHiddenVirtualMethods(MD, OverloadedMethods);
3253
3254 if (!OverloadedMethods.empty()) {
3255 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3256 Diag(Loc: OA->getLocation(),
3257 DiagID: diag::override_keyword_hides_virtual_member_function)
3258 << "override" << (OverloadedMethods.size() > 1);
3259 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3260 Diag(Loc: FA->getLocation(),
3261 DiagID: diag::override_keyword_hides_virtual_member_function)
3262 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3263 << (OverloadedMethods.size() > 1);
3264 }
3265 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3266 MD->setInvalidDecl();
3267 return;
3268 }
3269 // Fall through into the general case diagnostic.
3270 // FIXME: We might want to attempt typo correction here.
3271 }
3272
3273 if (!MD || !MD->isVirtual()) {
3274 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3275 Diag(Loc: OA->getLocation(),
3276 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3277 << "override" << FixItHint::CreateRemoval(RemoveRange: OA->getLocation());
3278 D->dropAttr<OverrideAttr>();
3279 }
3280 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3281 Diag(Loc: FA->getLocation(),
3282 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3283 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3284 << FixItHint::CreateRemoval(RemoveRange: FA->getLocation());
3285 D->dropAttr<FinalAttr>();
3286 }
3287 return;
3288 }
3289
3290 // C++11 [class.virtual]p5:
3291 // If a function is marked with the virt-specifier override and
3292 // does not override a member function of a base class, the program is
3293 // ill-formed.
3294 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3295 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3296 Diag(Loc: MD->getLocation(), DiagID: diag::err_function_marked_override_not_overriding)
3297 << MD->getDeclName();
3298}
3299
3300void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3301 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3302 return;
3303 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3304 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3305 return;
3306
3307 SourceLocation Loc = MD->getLocation();
3308 SourceLocation SpellingLoc = Loc;
3309 if (getSourceManager().isMacroArgExpansion(Loc))
3310 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3311 SpellingLoc = getSourceManager().getSpellingLoc(Loc: SpellingLoc);
3312 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(Loc: SpellingLoc))
3313 return;
3314
3315 if (MD->size_overridden_methods() > 0) {
3316 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3317 unsigned DiagID =
3318 Inconsistent && !Diags.isIgnored(DiagID: DiagInconsistent, Loc: MD->getLocation())
3319 ? DiagInconsistent
3320 : DiagSuggest;
3321 Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
3322 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3323 Diag(Loc: OMD->getLocation(), DiagID: diag::note_overridden_virtual_function);
3324 };
3325 if (isa<CXXDestructorDecl>(Val: MD))
3326 EmitDiag(
3327 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3328 diag::warn_suggest_destructor_marked_not_override_overriding);
3329 else
3330 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3331 diag::warn_suggest_function_marked_not_override_overriding);
3332 }
3333}
3334
3335bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3336 const CXXMethodDecl *Old) {
3337 FinalAttr *FA = Old->getAttr<FinalAttr>();
3338 if (!FA)
3339 return false;
3340
3341 Diag(Loc: New->getLocation(), DiagID: diag::err_final_function_overridden)
3342 << New->getDeclName()
3343 << FA->isSpelledAsSealed();
3344 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
3345 return true;
3346}
3347
3348static bool InitializationHasSideEffects(const FieldDecl &FD) {
3349 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3350 // FIXME: Destruction of ObjC lifetime types has side-effects.
3351 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3352 return !RD->isCompleteDefinition() ||
3353 !RD->hasTrivialDefaultConstructor() ||
3354 !RD->hasTrivialDestructor();
3355 return false;
3356}
3357
3358void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3359 DeclarationName FieldName,
3360 const CXXRecordDecl *RD,
3361 bool DeclIsField) {
3362 if (Diags.isIgnored(DiagID: diag::warn_shadow_field, Loc))
3363 return;
3364
3365 // To record a shadowed field in a base
3366 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3367 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3368 CXXBasePath &Path) {
3369 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3370 // Record an ambiguous path directly
3371 if (Bases.find(x: Base) != Bases.end())
3372 return true;
3373 for (const auto Field : Base->lookup(Name: FieldName)) {
3374 if ((isa<FieldDecl>(Val: Field) || isa<IndirectFieldDecl>(Val: Field)) &&
3375 Field->getAccess() != AS_private) {
3376 assert(Field->getAccess() != AS_none);
3377 assert(Bases.find(Base) == Bases.end());
3378 Bases[Base] = Field;
3379 return true;
3380 }
3381 }
3382 return false;
3383 };
3384
3385 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3386 /*DetectVirtual=*/true);
3387 if (!RD->lookupInBases(BaseMatches: FieldShadowed, Paths))
3388 return;
3389
3390 for (const auto &P : Paths) {
3391 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3392 auto It = Bases.find(x: Base);
3393 // Skip duplicated bases
3394 if (It == Bases.end())
3395 continue;
3396 auto BaseField = It->second;
3397 assert(BaseField->getAccess() != AS_private);
3398 if (AS_none !=
3399 CXXRecordDecl::MergeAccess(PathAccess: P.Access, DeclAccess: BaseField->getAccess())) {
3400 Diag(Loc, DiagID: diag::warn_shadow_field)
3401 << FieldName << RD << Base << DeclIsField;
3402 Diag(Loc: BaseField->getLocation(), DiagID: diag::note_shadow_field);
3403 Bases.erase(position: It);
3404 }
3405 }
3406}
3407
3408template <typename AttrType>
3409inline static bool HasAttribute(const QualType &T) {
3410 if (const TagDecl *TD = T->getAsTagDecl())
3411 return TD->hasAttr<AttrType>();
3412 if (const TypedefType *TDT = T->getAs<TypedefType>())
3413 return TDT->getDecl()->hasAttr<AttrType>();
3414 return false;
3415}
3416
3417static bool IsUnusedPrivateField(const FieldDecl *FD) {
3418 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3419 QualType FieldType = FD->getType();
3420 if (HasAttribute<WarnUnusedAttr>(T: FieldType))
3421 return true;
3422
3423 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3424 !FD->getParent()->isDependentContext() &&
3425 !HasAttribute<UnusedAttr>(T: FieldType) &&
3426 !InitializationHasSideEffects(FD: *FD);
3427 }
3428 return false;
3429}
3430
3431NamedDecl *
3432Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3433 MultiTemplateParamsArg TemplateParameterLists,
3434 Expr *BitWidth, const VirtSpecifiers &VS,
3435 InClassInitStyle InitStyle) {
3436 const DeclSpec &DS = D.getDeclSpec();
3437 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3438 DeclarationName Name = NameInfo.getName();
3439 SourceLocation Loc = NameInfo.getLoc();
3440
3441 // For anonymous bitfields, the location should point to the type.
3442 if (Loc.isInvalid())
3443 Loc = D.getBeginLoc();
3444
3445 assert(isa<CXXRecordDecl>(CurContext));
3446 assert(!DS.isFriendSpecified());
3447
3448 bool isFunc = D.isDeclarationOfFunction();
3449 const ParsedAttr *MSPropertyAttr =
3450 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3451
3452 if (cast<CXXRecordDecl>(Val: CurContext)->isInterface()) {
3453 // The Microsoft extension __interface only permits public member functions
3454 // and prohibits constructors, destructors, operators, non-public member
3455 // functions, static methods and data members.
3456 unsigned InvalidDecl;
3457 bool ShowDeclName = true;
3458 if (!isFunc &&
3459 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3460 InvalidDecl = 0;
3461 else if (!isFunc)
3462 InvalidDecl = 1;
3463 else if (AS != AS_public)
3464 InvalidDecl = 2;
3465 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3466 InvalidDecl = 3;
3467 else switch (Name.getNameKind()) {
3468 case DeclarationName::CXXConstructorName:
3469 InvalidDecl = 4;
3470 ShowDeclName = false;
3471 break;
3472
3473 case DeclarationName::CXXDestructorName:
3474 InvalidDecl = 5;
3475 ShowDeclName = false;
3476 break;
3477
3478 case DeclarationName::CXXOperatorName:
3479 case DeclarationName::CXXConversionFunctionName:
3480 InvalidDecl = 6;
3481 break;
3482
3483 default:
3484 InvalidDecl = 0;
3485 break;
3486 }
3487
3488 if (InvalidDecl) {
3489 if (ShowDeclName)
3490 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3491 << (InvalidDecl-1) << Name;
3492 else
3493 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3494 << (InvalidDecl-1) << "";
3495 return nullptr;
3496 }
3497 }
3498
3499 // C++ 9.2p6: A member shall not be declared to have automatic storage
3500 // duration (auto, register) or with the extern storage-class-specifier.
3501 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3502 // data members and cannot be applied to names declared const or static,
3503 // and cannot be applied to reference members.
3504 switch (DS.getStorageClassSpec()) {
3505 case DeclSpec::SCS_unspecified:
3506 case DeclSpec::SCS_typedef:
3507 case DeclSpec::SCS_static:
3508 break;
3509 case DeclSpec::SCS_mutable:
3510 if (isFunc) {
3511 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_function);
3512
3513 // FIXME: It would be nicer if the keyword was ignored only for this
3514 // declarator. Otherwise we could get follow-up errors.
3515 D.getMutableDeclSpec().ClearStorageClassSpecs();
3516 }
3517 break;
3518 default:
3519 Diag(Loc: DS.getStorageClassSpecLoc(),
3520 DiagID: diag::err_storageclass_invalid_for_member);
3521 D.getMutableDeclSpec().ClearStorageClassSpecs();
3522 break;
3523 }
3524
3525 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3526 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3527 !isFunc && TemplateParameterLists.empty();
3528
3529 if (DS.hasConstexprSpecifier() && isInstField) {
3530 SemaDiagnosticBuilder B =
3531 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr_member);
3532 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3533 if (InitStyle == ICIS_NoInit) {
3534 B << 0 << 0;
3535 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3536 B << FixItHint::CreateRemoval(RemoveRange: ConstexprLoc);
3537 else {
3538 B << FixItHint::CreateReplacement(RemoveRange: ConstexprLoc, Code: "const");
3539 D.getMutableDeclSpec().ClearConstexprSpec();
3540 const char *PrevSpec;
3541 unsigned DiagID;
3542 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3543 T: DeclSpec::TQ_const, Loc: ConstexprLoc, PrevSpec, DiagID, Lang: getLangOpts());
3544 (void)Failed;
3545 assert(!Failed && "Making a constexpr member const shouldn't fail");
3546 }
3547 } else {
3548 B << 1;
3549 const char *PrevSpec;
3550 unsigned DiagID;
3551 if (D.getMutableDeclSpec().SetStorageClassSpec(
3552 S&: *this, SC: DeclSpec::SCS_static, Loc: ConstexprLoc, PrevSpec, DiagID,
3553 Policy: Context.getPrintingPolicy())) {
3554 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3555 "This is the only DeclSpec that should fail to be applied");
3556 B << 1;
3557 } else {
3558 B << 0 << FixItHint::CreateInsertion(InsertionLoc: ConstexprLoc, Code: "static ");
3559 isInstField = false;
3560 }
3561 }
3562 }
3563
3564 NamedDecl *Member;
3565 if (isInstField) {
3566 CXXScopeSpec &SS = D.getCXXScopeSpec();
3567
3568 // Data members must have identifiers for names.
3569 if (!Name.isIdentifier()) {
3570 Diag(Loc, DiagID: diag::err_bad_variable_name)
3571 << Name;
3572 return nullptr;
3573 }
3574
3575 IdentifierInfo *II = Name.getAsIdentifierInfo();
3576 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3577 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_with_template_arguments)
3578 << II
3579 << SourceRange(D.getName().TemplateId->LAngleLoc,
3580 D.getName().TemplateId->RAngleLoc)
3581 << D.getName().TemplateId->LAngleLoc;
3582 D.SetIdentifier(Id: II, IdLoc: Loc);
3583 }
3584
3585 if (SS.isSet() && !SS.isInvalid()) {
3586 // The user provided a superfluous scope specifier inside a class
3587 // definition:
3588 //
3589 // class X {
3590 // int X::member;
3591 // };
3592 if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) {
3593 TemplateIdAnnotation *TemplateId =
3594 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3595 ? D.getName().TemplateId
3596 : nullptr;
3597 diagnoseQualifiedDeclaration(SS, DC, Name, Loc: D.getIdentifierLoc(),
3598 TemplateId,
3599 /*IsMemberSpecialization=*/false);
3600 } else {
3601 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_qualification)
3602 << Name << SS.getRange();
3603 }
3604 SS.clear();
3605 }
3606
3607 if (MSPropertyAttr) {
3608 Member = HandleMSProperty(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3609 BitfieldWidth: BitWidth, InitStyle, AS, MSPropertyAttr: *MSPropertyAttr);
3610 if (!Member)
3611 return nullptr;
3612 isInstField = false;
3613 } else {
3614 Member = HandleField(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3615 BitfieldWidth: BitWidth, InitStyle, AS);
3616 if (!Member)
3617 return nullptr;
3618 }
3619
3620 CheckShadowInheritedFields(Loc, FieldName: Name, RD: cast<CXXRecordDecl>(Val: CurContext));
3621 } else {
3622 Member = HandleDeclarator(S, D, TemplateParameterLists);
3623 if (!Member)
3624 return nullptr;
3625
3626 // Non-instance-fields can't have a bitfield.
3627 if (BitWidth) {
3628 if (Member->isInvalidDecl()) {
3629 // don't emit another diagnostic.
3630 } else if (isa<VarDecl>(Val: Member) || isa<VarTemplateDecl>(Val: Member)) {
3631 // C++ 9.6p3: A bit-field shall not be a static member.
3632 // "static member 'A' cannot be a bit-field"
3633 Diag(Loc, DiagID: diag::err_static_not_bitfield)
3634 << Name << BitWidth->getSourceRange();
3635 } else if (isa<TypedefDecl>(Val: Member)) {
3636 // "typedef member 'x' cannot be a bit-field"
3637 Diag(Loc, DiagID: diag::err_typedef_not_bitfield)
3638 << Name << BitWidth->getSourceRange();
3639 } else {
3640 // A function typedef ("typedef int f(); f a;").
3641 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3642 Diag(Loc, DiagID: diag::err_not_integral_type_bitfield)
3643 << Name << cast<ValueDecl>(Val: Member)->getType()
3644 << BitWidth->getSourceRange();
3645 }
3646
3647 BitWidth = nullptr;
3648 Member->setInvalidDecl();
3649 }
3650
3651 NamedDecl *NonTemplateMember = Member;
3652 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Member))
3653 NonTemplateMember = FunTmpl->getTemplatedDecl();
3654 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Val: Member))
3655 NonTemplateMember = VarTmpl->getTemplatedDecl();
3656
3657 Member->setAccess(AS);
3658
3659 // If we have declared a member function template or static data member
3660 // template, set the access of the templated declaration as well.
3661 if (NonTemplateMember != Member)
3662 NonTemplateMember->setAccess(AS);
3663
3664 // C++ [temp.deduct.guide]p3:
3665 // A deduction guide [...] for a member class template [shall be
3666 // declared] with the same access [as the template].
3667 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: NonTemplateMember)) {
3668 auto *TD = DG->getDeducedTemplate();
3669 // Access specifiers are only meaningful if both the template and the
3670 // deduction guide are from the same scope.
3671 if (AS != TD->getAccess() &&
3672 TD->getDeclContext()->getRedeclContext()->Equals(
3673 DC: DG->getDeclContext()->getRedeclContext())) {
3674 Diag(Loc: DG->getBeginLoc(), DiagID: diag::err_deduction_guide_wrong_access);
3675 Diag(Loc: TD->getBeginLoc(), DiagID: diag::note_deduction_guide_template_access)
3676 << TD->getAccess();
3677 const AccessSpecDecl *LastAccessSpec = nullptr;
3678 for (const auto *D : cast<CXXRecordDecl>(Val: CurContext)->decls()) {
3679 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(Val: D))
3680 LastAccessSpec = AccessSpec;
3681 }
3682 assert(LastAccessSpec && "differing access with no access specifier");
3683 Diag(Loc: LastAccessSpec->getBeginLoc(), DiagID: diag::note_deduction_guide_access)
3684 << AS;
3685 }
3686 }
3687 }
3688
3689 if (VS.isOverrideSpecified())
3690 Member->addAttr(A: OverrideAttr::Create(Ctx&: Context, Range: VS.getOverrideLoc()));
3691 if (VS.isFinalSpecified())
3692 Member->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: VS.getFinalLoc(),
3693 S: VS.isFinalSpelledSealed()
3694 ? FinalAttr::Keyword_sealed
3695 : FinalAttr::Keyword_final));
3696
3697 if (VS.getLastLocation().isValid()) {
3698 // Update the end location of a method that has a virt-specifiers.
3699 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Member))
3700 MD->setRangeEnd(VS.getLastLocation());
3701 }
3702
3703 CheckOverrideControl(D: Member);
3704
3705 assert((Name || isInstField) && "No identifier for non-field ?");
3706
3707 if (isInstField) {
3708 FieldDecl *FD = cast<FieldDecl>(Val: Member);
3709 FieldCollector->Add(D: FD);
3710
3711 if (!Diags.isIgnored(DiagID: diag::warn_unused_private_field, Loc: FD->getLocation()) &&
3712 IsUnusedPrivateField(FD)) {
3713 // Remember all explicit private FieldDecls that have a name, no side
3714 // effects and are not part of a dependent type declaration.
3715 UnusedPrivateFields.insert(X: FD);
3716 }
3717 }
3718
3719 return Member;
3720}
3721
3722namespace {
3723 class UninitializedFieldVisitor
3724 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3725 Sema &S;
3726 // List of Decls to generate a warning on. Also remove Decls that become
3727 // initialized.
3728 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3729 // List of base classes of the record. Classes are removed after their
3730 // initializers.
3731 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3732 // Vector of decls to be removed from the Decl set prior to visiting the
3733 // nodes. These Decls may have been initialized in the prior initializer.
3734 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3735 // If non-null, add a note to the warning pointing back to the constructor.
3736 const CXXConstructorDecl *Constructor;
3737 // Variables to hold state when processing an initializer list. When
3738 // InitList is true, special case initialization of FieldDecls matching
3739 // InitListFieldDecl.
3740 bool InitList;
3741 FieldDecl *InitListFieldDecl;
3742 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3743
3744 public:
3745 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3746 UninitializedFieldVisitor(Sema &S,
3747 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3748 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3749 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3750 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3751
3752 // Returns true if the use of ME is not an uninitialized use.
3753 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3754 bool CheckReferenceOnly) {
3755 llvm::SmallVector<FieldDecl*, 4> Fields;
3756 bool ReferenceField = false;
3757 while (ME) {
3758 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
3759 if (!FD)
3760 return false;
3761 Fields.push_back(Elt: FD);
3762 if (FD->getType()->isReferenceType())
3763 ReferenceField = true;
3764 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParenImpCasts());
3765 }
3766
3767 // Binding a reference to an uninitialized field is not an
3768 // uninitialized use.
3769 if (CheckReferenceOnly && !ReferenceField)
3770 return true;
3771
3772 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3773 // Discard the first field since it is the field decl that is being
3774 // initialized.
3775 for (const FieldDecl *FD : llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Fields)))
3776 UsedFieldIndex.push_back(Elt: FD->getFieldIndex());
3777
3778 for (auto UsedIter = UsedFieldIndex.begin(),
3779 UsedEnd = UsedFieldIndex.end(),
3780 OrigIter = InitFieldIndex.begin(),
3781 OrigEnd = InitFieldIndex.end();
3782 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3783 if (*UsedIter < *OrigIter)
3784 return true;
3785 if (*UsedIter > *OrigIter)
3786 break;
3787 }
3788
3789 return false;
3790 }
3791
3792 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3793 bool AddressOf) {
3794 if (isa<EnumConstantDecl>(Val: ME->getMemberDecl()))
3795 return;
3796
3797 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3798 // or union.
3799 MemberExpr *FieldME = ME;
3800
3801 bool AllPODFields = FieldME->getType().isPODType(Context: S.Context);
3802
3803 Expr *Base = ME;
3804 while (MemberExpr *SubME =
3805 dyn_cast<MemberExpr>(Val: Base->IgnoreParenImpCasts())) {
3806
3807 if (isa<VarDecl>(Val: SubME->getMemberDecl()))
3808 return;
3809
3810 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: SubME->getMemberDecl()))
3811 if (!FD->isAnonymousStructOrUnion())
3812 FieldME = SubME;
3813
3814 if (!FieldME->getType().isPODType(Context: S.Context))
3815 AllPODFields = false;
3816
3817 Base = SubME->getBase();
3818 }
3819
3820 if (!isa<CXXThisExpr>(Val: Base->IgnoreParenImpCasts())) {
3821 Visit(S: Base);
3822 return;
3823 }
3824
3825 if (AddressOf && AllPODFields)
3826 return;
3827
3828 ValueDecl* FoundVD = FieldME->getMemberDecl();
3829
3830 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Val: Base)) {
3831 while (isa<ImplicitCastExpr>(Val: BaseCast->getSubExpr())) {
3832 BaseCast = cast<ImplicitCastExpr>(Val: BaseCast->getSubExpr());
3833 }
3834
3835 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3836 QualType T = BaseCast->getType();
3837 if (T->isPointerType() &&
3838 BaseClasses.count(Ptr: T->getPointeeType())) {
3839 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag::warn_base_class_is_uninit)
3840 << T->getPointeeType() << FoundVD;
3841 }
3842 }
3843 }
3844
3845 if (!Decls.count(Ptr: FoundVD))
3846 return;
3847
3848 const bool IsReference = FoundVD->getType()->isReferenceType();
3849
3850 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3851 // Special checking for initializer lists.
3852 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3853 return;
3854 }
3855 } else {
3856 // Prevent double warnings on use of unbounded references.
3857 if (CheckReferenceOnly && !IsReference)
3858 return;
3859 }
3860
3861 unsigned diag = IsReference
3862 ? diag::warn_reference_field_is_uninit
3863 : diag::warn_field_is_uninit;
3864 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag) << FoundVD;
3865 if (Constructor)
3866 S.Diag(Loc: Constructor->getLocation(),
3867 DiagID: diag::note_uninit_in_this_constructor)
3868 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3869
3870 }
3871
3872 void HandleValue(Expr *E, bool AddressOf) {
3873 E = E->IgnoreParens();
3874
3875 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
3876 HandleMemberExpr(ME, CheckReferenceOnly: false /*CheckReferenceOnly*/,
3877 AddressOf /*AddressOf*/);
3878 return;
3879 }
3880
3881 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
3882 Visit(S: CO->getCond());
3883 HandleValue(E: CO->getTrueExpr(), AddressOf);
3884 HandleValue(E: CO->getFalseExpr(), AddressOf);
3885 return;
3886 }
3887
3888 if (BinaryConditionalOperator *BCO =
3889 dyn_cast<BinaryConditionalOperator>(Val: E)) {
3890 Visit(S: BCO->getCond());
3891 HandleValue(E: BCO->getFalseExpr(), AddressOf);
3892 return;
3893 }
3894
3895 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
3896 HandleValue(E: OVE->getSourceExpr(), AddressOf);
3897 return;
3898 }
3899
3900 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
3901 switch (BO->getOpcode()) {
3902 default:
3903 break;
3904 case(BO_PtrMemD):
3905 case(BO_PtrMemI):
3906 HandleValue(E: BO->getLHS(), AddressOf);
3907 Visit(S: BO->getRHS());
3908 return;
3909 case(BO_Comma):
3910 Visit(S: BO->getLHS());
3911 HandleValue(E: BO->getRHS(), AddressOf);
3912 return;
3913 }
3914 }
3915
3916 Visit(S: E);
3917 }
3918
3919 void CheckInitListExpr(InitListExpr *ILE) {
3920 InitFieldIndex.push_back(Elt: 0);
3921 for (auto *Child : ILE->children()) {
3922 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Val: Child)) {
3923 CheckInitListExpr(ILE: SubList);
3924 } else {
3925 Visit(S: Child);
3926 }
3927 ++InitFieldIndex.back();
3928 }
3929 InitFieldIndex.pop_back();
3930 }
3931
3932 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3933 FieldDecl *Field, const Type *BaseClass) {
3934 // Remove Decls that may have been initialized in the previous
3935 // initializer.
3936 for (ValueDecl* VD : DeclsToRemove)
3937 Decls.erase(Ptr: VD);
3938 DeclsToRemove.clear();
3939
3940 Constructor = FieldConstructor;
3941 InitListExpr *ILE = dyn_cast<InitListExpr>(Val: E);
3942
3943 if (ILE && Field) {
3944 InitList = true;
3945 InitListFieldDecl = Field;
3946 InitFieldIndex.clear();
3947 CheckInitListExpr(ILE);
3948 } else {
3949 InitList = false;
3950 Visit(S: E);
3951 }
3952
3953 if (Field)
3954 Decls.erase(Ptr: Field);
3955 if (BaseClass)
3956 BaseClasses.erase(Ptr: BaseClass->getCanonicalTypeInternal());
3957 }
3958
3959 void VisitMemberExpr(MemberExpr *ME) {
3960 // All uses of unbounded reference fields will warn.
3961 HandleMemberExpr(ME, CheckReferenceOnly: true /*CheckReferenceOnly*/, AddressOf: false /*AddressOf*/);
3962 }
3963
3964 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3965 if (E->getCastKind() == CK_LValueToRValue) {
3966 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
3967 return;
3968 }
3969
3970 Inherited::VisitImplicitCastExpr(S: E);
3971 }
3972
3973 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3974 if (E->getConstructor()->isCopyConstructor()) {
3975 Expr *ArgExpr = E->getArg(Arg: 0);
3976 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
3977 if (ILE->getNumInits() == 1)
3978 ArgExpr = ILE->getInit(Init: 0);
3979 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
3980 if (ICE->getCastKind() == CK_NoOp)
3981 ArgExpr = ICE->getSubExpr();
3982 HandleValue(E: ArgExpr, AddressOf: false /*AddressOf*/);
3983 return;
3984 }
3985 Inherited::VisitCXXConstructExpr(S: E);
3986 }
3987
3988 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3989 Expr *Callee = E->getCallee();
3990 if (isa<MemberExpr>(Val: Callee)) {
3991 HandleValue(E: Callee, AddressOf: false /*AddressOf*/);
3992 for (auto *Arg : E->arguments())
3993 Visit(S: Arg);
3994 return;
3995 }
3996
3997 Inherited::VisitCXXMemberCallExpr(S: E);
3998 }
3999
4000 void VisitCallExpr(CallExpr *E) {
4001 // Treat std::move as a use.
4002 if (E->isCallToStdMove()) {
4003 HandleValue(E: E->getArg(Arg: 0), /*AddressOf=*/false);
4004 return;
4005 }
4006
4007 Inherited::VisitCallExpr(CE: E);
4008 }
4009
4010 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4011 Expr *Callee = E->getCallee();
4012
4013 if (isa<UnresolvedLookupExpr>(Val: Callee))
4014 return Inherited::VisitCXXOperatorCallExpr(S: E);
4015
4016 Visit(S: Callee);
4017 for (auto *Arg : E->arguments())
4018 HandleValue(E: Arg->IgnoreParenImpCasts(), AddressOf: false /*AddressOf*/);
4019 }
4020
4021 void VisitBinaryOperator(BinaryOperator *E) {
4022 // If a field assignment is detected, remove the field from the
4023 // uninitiailized field set.
4024 if (E->getOpcode() == BO_Assign)
4025 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getLHS()))
4026 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()))
4027 if (!FD->getType()->isReferenceType())
4028 DeclsToRemove.push_back(Elt: FD);
4029
4030 if (E->isCompoundAssignmentOp()) {
4031 HandleValue(E: E->getLHS(), AddressOf: false /*AddressOf*/);
4032 Visit(S: E->getRHS());
4033 return;
4034 }
4035
4036 Inherited::VisitBinaryOperator(S: E);
4037 }
4038
4039 void VisitUnaryOperator(UnaryOperator *E) {
4040 if (E->isIncrementDecrementOp()) {
4041 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4042 return;
4043 }
4044 if (E->getOpcode() == UO_AddrOf) {
4045 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getSubExpr())) {
4046 HandleValue(E: ME->getBase(), AddressOf: true /*AddressOf*/);
4047 return;
4048 }
4049 }
4050
4051 Inherited::VisitUnaryOperator(S: E);
4052 }
4053 };
4054
4055 // Diagnose value-uses of fields to initialize themselves, e.g.
4056 // foo(foo)
4057 // where foo is not also a parameter to the constructor.
4058 // Also diagnose across field uninitialized use such as
4059 // x(y), y(x)
4060 // TODO: implement -Wuninitialized and fold this into that framework.
4061 static void DiagnoseUninitializedFields(
4062 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4063
4064 if (SemaRef.getDiagnostics().isIgnored(DiagID: diag::warn_field_is_uninit,
4065 Loc: Constructor->getLocation())) {
4066 return;
4067 }
4068
4069 if (Constructor->isInvalidDecl())
4070 return;
4071
4072 const CXXRecordDecl *RD = Constructor->getParent();
4073
4074 if (RD->isDependentContext())
4075 return;
4076
4077 // Holds fields that are uninitialized.
4078 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4079
4080 // At the beginning, all fields are uninitialized.
4081 for (auto *I : RD->decls()) {
4082 if (auto *FD = dyn_cast<FieldDecl>(Val: I)) {
4083 UninitializedFields.insert(Ptr: FD);
4084 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I)) {
4085 UninitializedFields.insert(Ptr: IFD->getAnonField());
4086 }
4087 }
4088
4089 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4090 for (const auto &I : RD->bases())
4091 UninitializedBaseClasses.insert(Ptr: I.getType().getCanonicalType());
4092
4093 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4094 return;
4095
4096 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4097 UninitializedFields,
4098 UninitializedBaseClasses);
4099
4100 for (const auto *FieldInit : Constructor->inits()) {
4101 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4102 break;
4103
4104 Expr *InitExpr = FieldInit->getInit();
4105 if (!InitExpr)
4106 continue;
4107
4108 if (CXXDefaultInitExpr *Default =
4109 dyn_cast<CXXDefaultInitExpr>(Val: InitExpr)) {
4110 InitExpr = Default->getExpr();
4111 if (!InitExpr)
4112 continue;
4113 // In class initializers will point to the constructor.
4114 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: Constructor,
4115 Field: FieldInit->getAnyMember(),
4116 BaseClass: FieldInit->getBaseClass());
4117 } else {
4118 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: nullptr,
4119 Field: FieldInit->getAnyMember(),
4120 BaseClass: FieldInit->getBaseClass());
4121 }
4122 }
4123 }
4124} // namespace
4125
4126void Sema::ActOnStartCXXInClassMemberInitializer() {
4127 // Create a synthetic function scope to represent the call to the constructor
4128 // that notionally surrounds a use of this initializer.
4129 PushFunctionScope();
4130}
4131
4132void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4133 if (!D.isFunctionDeclarator())
4134 return;
4135 auto &FTI = D.getFunctionTypeInfo();
4136 if (!FTI.Params)
4137 return;
4138 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4139 FTI.NumParams)) {
4140 auto *ParamDecl = cast<NamedDecl>(Val: Param.Param);
4141 if (ParamDecl->getDeclName())
4142 PushOnScopeChains(D: ParamDecl, S, /*AddToContext=*/false);
4143 }
4144}
4145
4146ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4147 return ActOnRequiresClause(ConstraintExpr);
4148}
4149
4150ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4151 if (ConstraintExpr.isInvalid())
4152 return ExprError();
4153
4154 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr.get(),
4155 UPPC: UPPC_RequiresClause))
4156 return ExprError();
4157
4158 return ConstraintExpr;
4159}
4160
4161ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4162 Expr *InitExpr,
4163 SourceLocation InitLoc) {
4164 InitializedEntity Entity =
4165 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: FD);
4166 InitializationKind Kind =
4167 FD->getInClassInitStyle() == ICIS_ListInit
4168 ? InitializationKind::CreateDirectList(InitLoc: InitExpr->getBeginLoc(),
4169 LBraceLoc: InitExpr->getBeginLoc(),
4170 RBraceLoc: InitExpr->getEndLoc())
4171 : InitializationKind::CreateCopy(InitLoc: InitExpr->getBeginLoc(), EqualLoc: InitLoc);
4172 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4173 return Seq.Perform(S&: *this, Entity, Kind, Args: InitExpr);
4174}
4175
4176void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4177 SourceLocation InitLoc,
4178 ExprResult InitExpr) {
4179 // Pop the notional constructor scope we created earlier.
4180 PopFunctionScopeInfo(WP: nullptr, D);
4181
4182 // Microsoft C++'s property declaration cannot have a default member
4183 // initializer.
4184 if (isa<MSPropertyDecl>(Val: D)) {
4185 D->setInvalidDecl();
4186 return;
4187 }
4188
4189 FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
4190 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4191 "must set init style when field is created");
4192
4193 if (!InitExpr.isUsable() ||
4194 DiagnoseUnexpandedParameterPack(E: InitExpr.get(), UPPC: UPPC_Initializer)) {
4195 FD->setInvalidDecl();
4196 ExprResult RecoveryInit =
4197 CreateRecoveryExpr(Begin: InitLoc, End: InitLoc, SubExprs: {}, T: FD->getType());
4198 if (RecoveryInit.isUsable())
4199 FD->setInClassInitializer(RecoveryInit.get());
4200 return;
4201 }
4202
4203 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4204 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr: InitExpr.get(), InitLoc);
4205 // C++11 [class.base.init]p7:
4206 // The initialization of each base and member constitutes a
4207 // full-expression.
4208 if (!InitExpr.isInvalid())
4209 InitExpr = ActOnFinishFullExpr(Expr: InitExpr.get(), /*DiscarededValue=*/DiscardedValue: false);
4210 if (InitExpr.isInvalid()) {
4211 FD->setInvalidDecl();
4212 return;
4213 }
4214 }
4215
4216 FD->setInClassInitializer(InitExpr.get());
4217}
4218
4219/// Find the direct and/or virtual base specifiers that
4220/// correspond to the given base type, for use in base initialization
4221/// within a constructor.
4222static bool FindBaseInitializer(Sema &SemaRef,
4223 CXXRecordDecl *ClassDecl,
4224 QualType BaseType,
4225 const CXXBaseSpecifier *&DirectBaseSpec,
4226 const CXXBaseSpecifier *&VirtualBaseSpec) {
4227 // First, check for a direct base class.
4228 DirectBaseSpec = nullptr;
4229 for (const auto &Base : ClassDecl->bases()) {
4230 if (SemaRef.Context.hasSameUnqualifiedType(T1: BaseType, T2: Base.getType())) {
4231 // We found a direct base of this type. That's what we're
4232 // initializing.
4233 DirectBaseSpec = &Base;
4234 break;
4235 }
4236 }
4237
4238 // Check for a virtual base class.
4239 // FIXME: We might be able to short-circuit this if we know in advance that
4240 // there are no virtual bases.
4241 VirtualBaseSpec = nullptr;
4242 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4243 // We haven't found a base yet; search the class hierarchy for a
4244 // virtual base class.
4245 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4246 /*DetectVirtual=*/false);
4247 if (SemaRef.IsDerivedFrom(Loc: ClassDecl->getLocation(),
4248 Derived: SemaRef.Context.getTypeDeclType(Decl: ClassDecl),
4249 Base: BaseType, Paths)) {
4250 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4251 Path != Paths.end(); ++Path) {
4252 if (Path->back().Base->isVirtual()) {
4253 VirtualBaseSpec = Path->back().Base;
4254 break;
4255 }
4256 }
4257 }
4258 }
4259
4260 return DirectBaseSpec || VirtualBaseSpec;
4261}
4262
4263MemInitResult
4264Sema::ActOnMemInitializer(Decl *ConstructorD,
4265 Scope *S,
4266 CXXScopeSpec &SS,
4267 IdentifierInfo *MemberOrBase,
4268 ParsedType TemplateTypeTy,
4269 const DeclSpec &DS,
4270 SourceLocation IdLoc,
4271 Expr *InitList,
4272 SourceLocation EllipsisLoc) {
4273 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4274 DS, IdLoc, Init: InitList,
4275 EllipsisLoc);
4276}
4277
4278MemInitResult
4279Sema::ActOnMemInitializer(Decl *ConstructorD,
4280 Scope *S,
4281 CXXScopeSpec &SS,
4282 IdentifierInfo *MemberOrBase,
4283 ParsedType TemplateTypeTy,
4284 const DeclSpec &DS,
4285 SourceLocation IdLoc,
4286 SourceLocation LParenLoc,
4287 ArrayRef<Expr *> Args,
4288 SourceLocation RParenLoc,
4289 SourceLocation EllipsisLoc) {
4290 Expr *List = ParenListExpr::Create(Ctx: Context, LParenLoc, Exprs: Args, RParenLoc);
4291 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4292 DS, IdLoc, Init: List, EllipsisLoc);
4293}
4294
4295namespace {
4296
4297// Callback to only accept typo corrections that can be a valid C++ member
4298// initializer: either a non-static field member or a base class.
4299class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4300public:
4301 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4302 : ClassDecl(ClassDecl) {}
4303
4304 bool ValidateCandidate(const TypoCorrection &candidate) override {
4305 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4306 if (FieldDecl *Member = dyn_cast<FieldDecl>(Val: ND))
4307 return Member->getDeclContext()->getRedeclContext()->Equals(DC: ClassDecl);
4308 return isa<TypeDecl>(Val: ND);
4309 }
4310 return false;
4311 }
4312
4313 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4314 return std::make_unique<MemInitializerValidatorCCC>(args&: *this);
4315 }
4316
4317private:
4318 CXXRecordDecl *ClassDecl;
4319};
4320
4321}
4322
4323bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4324 RecordDecl *ClassDecl,
4325 const IdentifierInfo *Name) {
4326 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4327 DeclContextLookupResult::iterator Found =
4328 llvm::find_if(Range&: Result, P: [this](const NamedDecl *Elem) {
4329 return isa<FieldDecl, IndirectFieldDecl>(Val: Elem) &&
4330 Elem->isPlaceholderVar(LangOpts: getLangOpts());
4331 });
4332 // We did not find a placeholder variable
4333 if (Found == Result.end())
4334 return false;
4335 Diag(Loc, DiagID: diag::err_using_placeholder_variable) << Name;
4336 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4337 const NamedDecl *ND = *It;
4338 if (ND->getDeclContext() != ND->getDeclContext())
4339 break;
4340 if (isa<FieldDecl, IndirectFieldDecl>(Val: ND) &&
4341 ND->isPlaceholderVar(LangOpts: getLangOpts()))
4342 Diag(Loc: ND->getLocation(), DiagID: diag::note_reference_placeholder) << ND;
4343 }
4344 return true;
4345}
4346
4347ValueDecl *
4348Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4349 const IdentifierInfo *MemberOrBase) {
4350 ValueDecl *ND = nullptr;
4351 for (auto *D : ClassDecl->lookup(Name: MemberOrBase)) {
4352 if (isa<FieldDecl, IndirectFieldDecl>(Val: D)) {
4353 bool IsPlaceholder = D->isPlaceholderVar(LangOpts: getLangOpts());
4354 if (ND) {
4355 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4356 return nullptr;
4357 break;
4358 }
4359 if (!IsPlaceholder)
4360 return cast<ValueDecl>(Val: D);
4361 ND = cast<ValueDecl>(Val: D);
4362 }
4363 }
4364 return ND;
4365}
4366
4367ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4368 CXXScopeSpec &SS,
4369 ParsedType TemplateTypeTy,
4370 IdentifierInfo *MemberOrBase) {
4371 if (SS.getScopeRep() || TemplateTypeTy)
4372 return nullptr;
4373 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4374}
4375
4376MemInitResult
4377Sema::BuildMemInitializer(Decl *ConstructorD,
4378 Scope *S,
4379 CXXScopeSpec &SS,
4380 IdentifierInfo *MemberOrBase,
4381 ParsedType TemplateTypeTy,
4382 const DeclSpec &DS,
4383 SourceLocation IdLoc,
4384 Expr *Init,
4385 SourceLocation EllipsisLoc) {
4386 if (!ConstructorD || !Init)
4387 return true;
4388
4389 AdjustDeclIfTemplate(Decl&: ConstructorD);
4390
4391 CXXConstructorDecl *Constructor
4392 = dyn_cast<CXXConstructorDecl>(Val: ConstructorD);
4393 if (!Constructor) {
4394 // The user wrote a constructor initializer on a function that is
4395 // not a C++ constructor. Ignore the error for now, because we may
4396 // have more member initializers coming; we'll diagnose it just
4397 // once in ActOnMemInitializers.
4398 return true;
4399 }
4400
4401 CXXRecordDecl *ClassDecl = Constructor->getParent();
4402
4403 // C++ [class.base.init]p2:
4404 // Names in a mem-initializer-id are looked up in the scope of the
4405 // constructor's class and, if not found in that scope, are looked
4406 // up in the scope containing the constructor's definition.
4407 // [Note: if the constructor's class contains a member with the
4408 // same name as a direct or virtual base class of the class, a
4409 // mem-initializer-id naming the member or base class and composed
4410 // of a single identifier refers to the class member. A
4411 // mem-initializer-id for the hidden base class may be specified
4412 // using a qualified name. ]
4413
4414 // Look for a member, first.
4415 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4416 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4417 if (EllipsisLoc.isValid())
4418 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_member_init)
4419 << MemberOrBase
4420 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4421
4422 return BuildMemberInitializer(Member, Init, IdLoc);
4423 }
4424 // It didn't name a member, so see if it names a class.
4425 QualType BaseType;
4426 TypeSourceInfo *TInfo = nullptr;
4427
4428 if (TemplateTypeTy) {
4429 BaseType = GetTypeFromParser(Ty: TemplateTypeTy, TInfo: &TInfo);
4430 if (BaseType.isNull())
4431 return true;
4432 } else if (DS.getTypeSpecType() == TST_decltype) {
4433 BaseType = BuildDecltypeType(E: DS.getRepAsExpr());
4434 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4435 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decltype_auto_invalid);
4436 return true;
4437 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4438 BaseType =
4439 BuildPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(),
4440 Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc());
4441 } else {
4442 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4443 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
4444
4445 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4446 if (!TyD) {
4447 if (R.isAmbiguous()) return true;
4448
4449 // We don't want access-control diagnostics here.
4450 R.suppressDiagnostics();
4451
4452 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4453 bool NotUnknownSpecialization = false;
4454 DeclContext *DC = computeDeclContext(SS, EnteringContext: false);
4455 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Val: DC))
4456 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4457
4458 if (!NotUnknownSpecialization) {
4459 // When the scope specifier can refer to a member of an unknown
4460 // specialization, we take it as a type name.
4461 BaseType = CheckTypenameType(
4462 Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(),
4463 QualifierLoc: SS.getWithLocInContext(Context), II: *MemberOrBase, IILoc: IdLoc);
4464 if (BaseType.isNull())
4465 return true;
4466
4467 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4468 DependentNameTypeLoc TL =
4469 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4470 if (!TL.isNull()) {
4471 TL.setNameLoc(IdLoc);
4472 TL.setElaboratedKeywordLoc(SourceLocation());
4473 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4474 }
4475
4476 R.clear();
4477 R.setLookupName(MemberOrBase);
4478 }
4479 }
4480
4481 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4482 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4483 auto *TempSpec = cast<TemplateSpecializationType>(
4484 Val: UnqualifiedBase->getInjectedClassNameSpecialization());
4485 TemplateName TN = TempSpec->getTemplateName();
4486 for (auto const &Base : ClassDecl->bases()) {
4487 auto BaseTemplate =
4488 Base.getType()->getAs<TemplateSpecializationType>();
4489 if (BaseTemplate &&
4490 Context.hasSameTemplateName(X: BaseTemplate->getTemplateName(), Y: TN,
4491 /*IgnoreDeduced=*/true)) {
4492 Diag(Loc: IdLoc, DiagID: diag::ext_unqualified_base_class)
4493 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4494 BaseType = Base.getType();
4495 break;
4496 }
4497 }
4498 }
4499 }
4500
4501 // If no results were found, try to correct typos.
4502 TypoCorrection Corr;
4503 MemInitializerValidatorCCC CCC(ClassDecl);
4504 if (R.empty() && BaseType.isNull() &&
4505 (Corr =
4506 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
4507 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: ClassDecl))) {
4508 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4509 // We have found a non-static data member with a similar
4510 // name to what was typed; complain and initialize that
4511 // member.
4512 diagnoseTypo(Correction: Corr,
4513 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4514 << MemberOrBase << true);
4515 return BuildMemberInitializer(Member, Init, IdLoc);
4516 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4517 const CXXBaseSpecifier *DirectBaseSpec;
4518 const CXXBaseSpecifier *VirtualBaseSpec;
4519 if (FindBaseInitializer(SemaRef&: *this, ClassDecl,
4520 BaseType: Context.getTypeDeclType(Decl: Type),
4521 DirectBaseSpec, VirtualBaseSpec)) {
4522 // We have found a direct or virtual base class with a
4523 // similar name to what was typed; complain and initialize
4524 // that base class.
4525 diagnoseTypo(Correction: Corr,
4526 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4527 << MemberOrBase << false,
4528 PrevNote: PDiag() /*Suppress note, we provide our own.*/);
4529
4530 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4531 : VirtualBaseSpec;
4532 Diag(Loc: BaseSpec->getBeginLoc(), DiagID: diag::note_base_class_specified_here)
4533 << BaseSpec->getType() << BaseSpec->getSourceRange();
4534
4535 TyD = Type;
4536 }
4537 }
4538 }
4539
4540 if (!TyD && BaseType.isNull()) {
4541 Diag(Loc: IdLoc, DiagID: diag::err_mem_init_not_member_or_class)
4542 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4543 return true;
4544 }
4545 }
4546
4547 if (BaseType.isNull()) {
4548 BaseType = getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS,
4549 T: Context.getTypeDeclType(Decl: TyD));
4550 MarkAnyDeclReferenced(Loc: TyD->getLocation(), D: TyD, /*OdrUse=*/MightBeOdrUse: false);
4551 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4552 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4553 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4554 TL.setElaboratedKeywordLoc(SourceLocation());
4555 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4556 }
4557 }
4558
4559 if (!TInfo)
4560 TInfo = Context.getTrivialTypeSourceInfo(T: BaseType, Loc: IdLoc);
4561
4562 return BuildBaseInitializer(BaseType, BaseTInfo: TInfo, Init, ClassDecl, EllipsisLoc);
4563}
4564
4565MemInitResult
4566Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4567 SourceLocation IdLoc) {
4568 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Val: Member);
4569 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Val: Member);
4570 assert((DirectMember || IndirectMember) &&
4571 "Member must be a FieldDecl or IndirectFieldDecl");
4572
4573 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4574 return true;
4575
4576 if (Member->isInvalidDecl())
4577 return true;
4578
4579 MultiExprArg Args;
4580 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4581 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4582 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
4583 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4584 } else {
4585 // Template instantiation doesn't reconstruct ParenListExprs for us.
4586 Args = Init;
4587 }
4588
4589 SourceRange InitRange = Init->getSourceRange();
4590
4591 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4592 // Can't check initialization for a member of dependent type or when
4593 // any of the arguments are type-dependent expressions.
4594 DiscardCleanupsInEvaluationContext();
4595 } else {
4596 bool InitList = false;
4597 if (isa<InitListExpr>(Val: Init)) {
4598 InitList = true;
4599 Args = Init;
4600 }
4601
4602 // Initialize the member.
4603 InitializedEntity MemberEntity =
4604 DirectMember ? InitializedEntity::InitializeMember(Member: DirectMember, Parent: nullptr)
4605 : InitializedEntity::InitializeMember(Member: IndirectMember,
4606 Parent: nullptr);
4607 InitializationKind Kind =
4608 InitList ? InitializationKind::CreateDirectList(
4609 InitLoc: IdLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4610 : InitializationKind::CreateDirect(InitLoc: IdLoc, LParenLoc: InitRange.getBegin(),
4611 RParenLoc: InitRange.getEnd());
4612
4613 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4614 ExprResult MemberInit = InitSeq.Perform(S&: *this, Entity: MemberEntity, Kind, Args,
4615 ResultType: nullptr);
4616 if (!MemberInit.isInvalid()) {
4617 // C++11 [class.base.init]p7:
4618 // The initialization of each base and member constitutes a
4619 // full-expression.
4620 MemberInit = ActOnFinishFullExpr(Expr: MemberInit.get(), CC: InitRange.getBegin(),
4621 /*DiscardedValue*/ false);
4622 }
4623
4624 if (MemberInit.isInvalid()) {
4625 // Args were sensible expressions but we couldn't initialize the member
4626 // from them. Preserve them in a RecoveryExpr instead.
4627 Init = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4628 T: Member->getType())
4629 .get();
4630 if (!Init)
4631 return true;
4632 } else {
4633 Init = MemberInit.get();
4634 }
4635 }
4636
4637 if (DirectMember) {
4638 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4639 InitRange.getBegin(), Init,
4640 InitRange.getEnd());
4641 } else {
4642 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4643 InitRange.getBegin(), Init,
4644 InitRange.getEnd());
4645 }
4646}
4647
4648MemInitResult
4649Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4650 CXXRecordDecl *ClassDecl) {
4651 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4652 if (!LangOpts.CPlusPlus11)
4653 return Diag(Loc: NameLoc, DiagID: diag::err_delegating_ctor)
4654 << TInfo->getTypeLoc().getSourceRange();
4655 Diag(Loc: NameLoc, DiagID: diag::warn_cxx98_compat_delegating_ctor);
4656
4657 bool InitList = true;
4658 MultiExprArg Args = Init;
4659 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4660 InitList = false;
4661 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4662 }
4663
4664 SourceRange InitRange = Init->getSourceRange();
4665 // Initialize the object.
4666 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4667 Type: QualType(ClassDecl->getTypeForDecl(), 0));
4668 InitializationKind Kind =
4669 InitList ? InitializationKind::CreateDirectList(
4670 InitLoc: NameLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4671 : InitializationKind::CreateDirect(InitLoc: NameLoc, LParenLoc: InitRange.getBegin(),
4672 RParenLoc: InitRange.getEnd());
4673 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4674 ExprResult DelegationInit = InitSeq.Perform(S&: *this, Entity: DelegationEntity, Kind,
4675 Args, ResultType: nullptr);
4676 if (!DelegationInit.isInvalid()) {
4677 assert((DelegationInit.get()->containsErrors() ||
4678 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4679 "Delegating constructor with no target?");
4680
4681 // C++11 [class.base.init]p7:
4682 // The initialization of each base and member constitutes a
4683 // full-expression.
4684 DelegationInit = ActOnFinishFullExpr(
4685 Expr: DelegationInit.get(), CC: InitRange.getBegin(), /*DiscardedValue*/ false);
4686 }
4687
4688 if (DelegationInit.isInvalid()) {
4689 DelegationInit =
4690 CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4691 T: QualType(ClassDecl->getTypeForDecl(), 0));
4692 if (DelegationInit.isInvalid())
4693 return true;
4694 } else {
4695 // If we are in a dependent context, template instantiation will
4696 // perform this type-checking again. Just save the arguments that we
4697 // received in a ParenListExpr.
4698 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4699 // of the information that we have about the base
4700 // initializer. However, deconstructing the ASTs is a dicey process,
4701 // and this approach is far more likely to get the corner cases right.
4702 if (CurContext->isDependentContext())
4703 DelegationInit = Init;
4704 }
4705
4706 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4707 DelegationInit.getAs<Expr>(),
4708 InitRange.getEnd());
4709}
4710
4711MemInitResult
4712Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4713 Expr *Init, CXXRecordDecl *ClassDecl,
4714 SourceLocation EllipsisLoc) {
4715 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4716
4717 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4718 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_does_not_name_class)
4719 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4720
4721 // C++ [class.base.init]p2:
4722 // [...] Unless the mem-initializer-id names a nonstatic data
4723 // member of the constructor's class or a direct or virtual base
4724 // of that class, the mem-initializer is ill-formed. A
4725 // mem-initializer-list can initialize a base class using any
4726 // name that denotes that base class type.
4727
4728 // We can store the initializers in "as-written" form and delay analysis until
4729 // instantiation if the constructor is dependent. But not for dependent
4730 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4731 bool Dependent = CurContext->isDependentContext() &&
4732 (BaseType->isDependentType() || Init->isTypeDependent());
4733
4734 SourceRange InitRange = Init->getSourceRange();
4735 if (EllipsisLoc.isValid()) {
4736 // This is a pack expansion.
4737 if (!BaseType->containsUnexpandedParameterPack()) {
4738 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
4739 << SourceRange(BaseLoc, InitRange.getEnd());
4740
4741 EllipsisLoc = SourceLocation();
4742 }
4743 } else {
4744 // Check for any unexpanded parameter packs.
4745 if (DiagnoseUnexpandedParameterPack(Loc: BaseLoc, T: BaseTInfo, UPPC: UPPC_Initializer))
4746 return true;
4747
4748 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4749 return true;
4750 }
4751
4752 // Check for direct and virtual base classes.
4753 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4754 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4755 if (!Dependent) {
4756 if (Context.hasSameUnqualifiedType(T1: QualType(ClassDecl->getTypeForDecl(),0),
4757 T2: BaseType))
4758 return BuildDelegatingInitializer(TInfo: BaseTInfo, Init, ClassDecl);
4759
4760 FindBaseInitializer(SemaRef&: *this, ClassDecl, BaseType, DirectBaseSpec,
4761 VirtualBaseSpec);
4762
4763 // C++ [base.class.init]p2:
4764 // Unless the mem-initializer-id names a nonstatic data member of the
4765 // constructor's class or a direct or virtual base of that class, the
4766 // mem-initializer is ill-formed.
4767 if (!DirectBaseSpec && !VirtualBaseSpec) {
4768 // If the class has any dependent bases, then it's possible that
4769 // one of those types will resolve to the same type as
4770 // BaseType. Therefore, just treat this as a dependent base
4771 // class initialization. FIXME: Should we try to check the
4772 // initialization anyway? It seems odd.
4773 if (ClassDecl->hasAnyDependentBases())
4774 Dependent = true;
4775 else
4776 return Diag(Loc: BaseLoc, DiagID: diag::err_not_direct_base_or_virtual)
4777 << BaseType << Context.getTypeDeclType(Decl: ClassDecl)
4778 << BaseTInfo->getTypeLoc().getSourceRange();
4779 }
4780 }
4781
4782 if (Dependent) {
4783 DiscardCleanupsInEvaluationContext();
4784
4785 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4786 /*IsVirtual=*/false,
4787 InitRange.getBegin(), Init,
4788 InitRange.getEnd(), EllipsisLoc);
4789 }
4790
4791 // C++ [base.class.init]p2:
4792 // If a mem-initializer-id is ambiguous because it designates both
4793 // a direct non-virtual base class and an inherited virtual base
4794 // class, the mem-initializer is ill-formed.
4795 if (DirectBaseSpec && VirtualBaseSpec)
4796 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_direct_and_virtual)
4797 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4798
4799 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4800 if (!BaseSpec)
4801 BaseSpec = VirtualBaseSpec;
4802
4803 // Initialize the base.
4804 bool InitList = true;
4805 MultiExprArg Args = Init;
4806 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4807 InitList = false;
4808 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4809 }
4810
4811 InitializedEntity BaseEntity =
4812 InitializedEntity::InitializeBase(Context, Base: BaseSpec, IsInheritedVirtualBase: VirtualBaseSpec);
4813 InitializationKind Kind =
4814 InitList ? InitializationKind::CreateDirectList(InitLoc: BaseLoc)
4815 : InitializationKind::CreateDirect(InitLoc: BaseLoc, LParenLoc: InitRange.getBegin(),
4816 RParenLoc: InitRange.getEnd());
4817 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4818 ExprResult BaseInit = InitSeq.Perform(S&: *this, Entity: BaseEntity, Kind, Args, ResultType: nullptr);
4819 if (!BaseInit.isInvalid()) {
4820 // C++11 [class.base.init]p7:
4821 // The initialization of each base and member constitutes a
4822 // full-expression.
4823 BaseInit = ActOnFinishFullExpr(Expr: BaseInit.get(), CC: InitRange.getBegin(),
4824 /*DiscardedValue*/ false);
4825 }
4826
4827 if (BaseInit.isInvalid()) {
4828 BaseInit = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(),
4829 SubExprs: Args, T: BaseType);
4830 if (BaseInit.isInvalid())
4831 return true;
4832 } else {
4833 // If we are in a dependent context, template instantiation will
4834 // perform this type-checking again. Just save the arguments that we
4835 // received in a ParenListExpr.
4836 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4837 // of the information that we have about the base
4838 // initializer. However, deconstructing the ASTs is a dicey process,
4839 // and this approach is far more likely to get the corner cases right.
4840 if (CurContext->isDependentContext())
4841 BaseInit = Init;
4842 }
4843
4844 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4845 BaseSpec->isVirtual(),
4846 InitRange.getBegin(),
4847 BaseInit.getAs<Expr>(),
4848 InitRange.getEnd(), EllipsisLoc);
4849}
4850
4851// Create a static_cast\<T&&>(expr).
4852static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4853 QualType TargetType =
4854 SemaRef.BuildReferenceType(T: E->getType(), /*SpelledAsLValue*/ LValueRef: false,
4855 Loc: SourceLocation(), Entity: DeclarationName());
4856 SourceLocation ExprLoc = E->getBeginLoc();
4857 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4858 T: TargetType, Loc: ExprLoc);
4859
4860 return SemaRef.BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
4861 AngleBrackets: SourceRange(ExprLoc, ExprLoc),
4862 Parens: E->getSourceRange()).get();
4863}
4864
4865/// ImplicitInitializerKind - How an implicit base or member initializer should
4866/// initialize its base or member.
4867enum ImplicitInitializerKind {
4868 IIK_Default,
4869 IIK_Copy,
4870 IIK_Move,
4871 IIK_Inherit
4872};
4873
4874static bool
4875BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4876 ImplicitInitializerKind ImplicitInitKind,
4877 CXXBaseSpecifier *BaseSpec,
4878 bool IsInheritedVirtualBase,
4879 CXXCtorInitializer *&CXXBaseInit) {
4880 InitializedEntity InitEntity
4881 = InitializedEntity::InitializeBase(Context&: SemaRef.Context, Base: BaseSpec,
4882 IsInheritedVirtualBase);
4883
4884 ExprResult BaseInit;
4885
4886 switch (ImplicitInitKind) {
4887 case IIK_Inherit:
4888 case IIK_Default: {
4889 InitializationKind InitKind
4890 = InitializationKind::CreateDefault(InitLoc: Constructor->getLocation());
4891 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4892 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
4893 break;
4894 }
4895
4896 case IIK_Move:
4897 case IIK_Copy: {
4898 bool Moving = ImplicitInitKind == IIK_Move;
4899 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
4900 QualType ParamType = Param->getType().getNonReferenceType();
4901
4902 Expr *CopyCtorArg =
4903 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
4904 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
4905 NameLoc: Constructor->getLocation(), T: ParamType,
4906 VK: VK_LValue, FoundD: nullptr);
4907
4908 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: CopyCtorArg));
4909
4910 // Cast to the base class to avoid ambiguities.
4911 QualType ArgTy =
4912 SemaRef.Context.getQualifiedType(T: BaseSpec->getType().getUnqualifiedType(),
4913 Qs: ParamType.getQualifiers());
4914
4915 if (Moving) {
4916 CopyCtorArg = CastForMoving(SemaRef, E: CopyCtorArg);
4917 }
4918
4919 CXXCastPath BasePath;
4920 BasePath.push_back(Elt: BaseSpec);
4921 CopyCtorArg = SemaRef.ImpCastExprToType(E: CopyCtorArg, Type: ArgTy,
4922 CK: CK_UncheckedDerivedToBase,
4923 VK: Moving ? VK_XValue : VK_LValue,
4924 BasePath: &BasePath).get();
4925
4926 InitializationKind InitKind
4927 = InitializationKind::CreateDirect(InitLoc: Constructor->getLocation(),
4928 LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
4929 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4930 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: CopyCtorArg);
4931 break;
4932 }
4933 }
4934
4935 BaseInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: BaseInit);
4936 if (BaseInit.isInvalid())
4937 return true;
4938
4939 CXXBaseInit =
4940 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4941 SemaRef.Context.getTrivialTypeSourceInfo(T: BaseSpec->getType(),
4942 Loc: SourceLocation()),
4943 BaseSpec->isVirtual(),
4944 SourceLocation(),
4945 BaseInit.getAs<Expr>(),
4946 SourceLocation(),
4947 SourceLocation());
4948
4949 return false;
4950}
4951
4952static bool RefersToRValueRef(Expr *MemRef) {
4953 ValueDecl *Referenced = cast<MemberExpr>(Val: MemRef)->getMemberDecl();
4954 return Referenced->getType()->isRValueReferenceType();
4955}
4956
4957static bool
4958BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4959 ImplicitInitializerKind ImplicitInitKind,
4960 FieldDecl *Field, IndirectFieldDecl *Indirect,
4961 CXXCtorInitializer *&CXXMemberInit) {
4962 if (Field->isInvalidDecl())
4963 return true;
4964
4965 SourceLocation Loc = Constructor->getLocation();
4966
4967 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4968 bool Moving = ImplicitInitKind == IIK_Move;
4969 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
4970 QualType ParamType = Param->getType().getNonReferenceType();
4971
4972 // Suppress copying zero-width bitfields.
4973 if (Field->isZeroLengthBitField())
4974 return false;
4975
4976 Expr *MemberExprBase =
4977 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
4978 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
4979 NameLoc: Loc, T: ParamType, VK: VK_LValue, FoundD: nullptr);
4980
4981 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: MemberExprBase));
4982
4983 if (Moving) {
4984 MemberExprBase = CastForMoving(SemaRef, E: MemberExprBase);
4985 }
4986
4987 // Build a reference to this field within the parameter.
4988 CXXScopeSpec SS;
4989 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4990 Sema::LookupMemberName);
4991 MemberLookup.addDecl(D: Indirect ? cast<ValueDecl>(Val: Indirect)
4992 : cast<ValueDecl>(Val: Field), AS: AS_public);
4993 MemberLookup.resolveKind();
4994 ExprResult CtorArg
4995 = SemaRef.BuildMemberReferenceExpr(Base: MemberExprBase,
4996 BaseType: ParamType, OpLoc: Loc,
4997 /*IsArrow=*/false,
4998 SS,
4999 /*TemplateKWLoc=*/SourceLocation(),
5000 /*FirstQualifierInScope=*/nullptr,
5001 R&: MemberLookup,
5002 /*TemplateArgs=*/nullptr,
5003 /*S*/nullptr);
5004 if (CtorArg.isInvalid())
5005 return true;
5006
5007 // C++11 [class.copy]p15:
5008 // - if a member m has rvalue reference type T&&, it is direct-initialized
5009 // with static_cast<T&&>(x.m);
5010 if (RefersToRValueRef(MemRef: CtorArg.get())) {
5011 CtorArg = CastForMoving(SemaRef, E: CtorArg.get());
5012 }
5013
5014 InitializedEntity Entity =
5015 Indirect ? InitializedEntity::InitializeMember(Member: Indirect, Parent: nullptr,
5016 /*Implicit*/ true)
5017 : InitializedEntity::InitializeMember(Member: Field, Parent: nullptr,
5018 /*Implicit*/ true);
5019
5020 // Direct-initialize to use the copy constructor.
5021 InitializationKind InitKind =
5022 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5023
5024 Expr *CtorArgE = CtorArg.getAs<Expr>();
5025 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5026 ExprResult MemberInit =
5027 InitSeq.Perform(S&: SemaRef, Entity, Kind: InitKind, Args: MultiExprArg(&CtorArgE, 1));
5028 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5029 if (MemberInit.isInvalid())
5030 return true;
5031
5032 if (Indirect)
5033 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5034 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5035 else
5036 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5037 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5038 return false;
5039 }
5040
5041 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5042 "Unhandled implicit init kind!");
5043
5044 QualType FieldBaseElementType =
5045 SemaRef.Context.getBaseElementType(QT: Field->getType());
5046
5047 if (FieldBaseElementType->isRecordType()) {
5048 InitializedEntity InitEntity =
5049 Indirect ? InitializedEntity::InitializeMember(Member: Indirect, Parent: nullptr,
5050 /*Implicit*/ true)
5051 : InitializedEntity::InitializeMember(Member: Field, Parent: nullptr,
5052 /*Implicit*/ true);
5053 InitializationKind InitKind =
5054 InitializationKind::CreateDefault(InitLoc: Loc);
5055
5056 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5057 ExprResult MemberInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5058
5059 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5060 if (MemberInit.isInvalid())
5061 return true;
5062
5063 if (Indirect)
5064 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5065 Indirect, Loc,
5066 Loc,
5067 MemberInit.get(),
5068 Loc);
5069 else
5070 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5071 Field, Loc, Loc,
5072 MemberInit.get(),
5073 Loc);
5074 return false;
5075 }
5076
5077 if (!Field->getParent()->isUnion()) {
5078 if (FieldBaseElementType->isReferenceType()) {
5079 SemaRef.Diag(Loc: Constructor->getLocation(),
5080 DiagID: diag::err_uninitialized_member_in_ctor)
5081 << (int)Constructor->isImplicit()
5082 << SemaRef.Context.getTagDeclType(Decl: Constructor->getParent())
5083 << 0 << Field->getDeclName();
5084 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5085 return true;
5086 }
5087
5088 if (FieldBaseElementType.isConstQualified()) {
5089 SemaRef.Diag(Loc: Constructor->getLocation(),
5090 DiagID: diag::err_uninitialized_member_in_ctor)
5091 << (int)Constructor->isImplicit()
5092 << SemaRef.Context.getTagDeclType(Decl: Constructor->getParent())
5093 << 1 << Field->getDeclName();
5094 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5095 return true;
5096 }
5097 }
5098
5099 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5100 // ARC and Weak:
5101 // Default-initialize Objective-C pointers to NULL.
5102 CXXMemberInit
5103 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5104 Loc, Loc,
5105 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5106 Loc);
5107 return false;
5108 }
5109
5110 // Nothing to initialize.
5111 CXXMemberInit = nullptr;
5112 return false;
5113}
5114
5115namespace {
5116struct BaseAndFieldInfo {
5117 Sema &S;
5118 CXXConstructorDecl *Ctor;
5119 bool AnyErrorsInInits;
5120 ImplicitInitializerKind IIK;
5121 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5122 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5123 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5124
5125 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5126 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5127 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5128 if (Ctor->getInheritedConstructor())
5129 IIK = IIK_Inherit;
5130 else if (Generated && Ctor->isCopyConstructor())
5131 IIK = IIK_Copy;
5132 else if (Generated && Ctor->isMoveConstructor())
5133 IIK = IIK_Move;
5134 else
5135 IIK = IIK_Default;
5136 }
5137
5138 bool isImplicitCopyOrMove() const {
5139 switch (IIK) {
5140 case IIK_Copy:
5141 case IIK_Move:
5142 return true;
5143
5144 case IIK_Default:
5145 case IIK_Inherit:
5146 return false;
5147 }
5148
5149 llvm_unreachable("Invalid ImplicitInitializerKind!");
5150 }
5151
5152 bool addFieldInitializer(CXXCtorInitializer *Init) {
5153 AllToInit.push_back(Elt: Init);
5154
5155 // Check whether this initializer makes the field "used".
5156 if (Init->getInit()->HasSideEffects(Ctx: S.Context))
5157 S.UnusedPrivateFields.remove(X: Init->getAnyMember());
5158
5159 return false;
5160 }
5161
5162 bool isInactiveUnionMember(FieldDecl *Field) {
5163 RecordDecl *Record = Field->getParent();
5164 if (!Record->isUnion())
5165 return false;
5166
5167 if (FieldDecl *Active =
5168 ActiveUnionMember.lookup(Val: Record->getCanonicalDecl()))
5169 return Active != Field->getCanonicalDecl();
5170
5171 // In an implicit copy or move constructor, ignore any in-class initializer.
5172 if (isImplicitCopyOrMove())
5173 return true;
5174
5175 // If there's no explicit initialization, the field is active only if it
5176 // has an in-class initializer...
5177 if (Field->hasInClassInitializer())
5178 return false;
5179 // ... or it's an anonymous struct or union whose class has an in-class
5180 // initializer.
5181 if (!Field->isAnonymousStructOrUnion())
5182 return true;
5183 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5184 return !FieldRD->hasInClassInitializer();
5185 }
5186
5187 /// Determine whether the given field is, or is within, a union member
5188 /// that is inactive (because there was an initializer given for a different
5189 /// member of the union, or because the union was not initialized at all).
5190 bool isWithinInactiveUnionMember(FieldDecl *Field,
5191 IndirectFieldDecl *Indirect) {
5192 if (!Indirect)
5193 return isInactiveUnionMember(Field);
5194
5195 for (auto *C : Indirect->chain()) {
5196 FieldDecl *Field = dyn_cast<FieldDecl>(Val: C);
5197 if (Field && isInactiveUnionMember(Field))
5198 return true;
5199 }
5200 return false;
5201 }
5202};
5203}
5204
5205/// Determine whether the given type is an incomplete or zero-lenfgth
5206/// array type.
5207static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5208 if (T->isIncompleteArrayType())
5209 return true;
5210
5211 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5212 if (ArrayT->isZeroSize())
5213 return true;
5214
5215 T = ArrayT->getElementType();
5216 }
5217
5218 return false;
5219}
5220
5221static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5222 FieldDecl *Field,
5223 IndirectFieldDecl *Indirect = nullptr) {
5224 if (Field->isInvalidDecl())
5225 return false;
5226
5227 // Overwhelmingly common case: we have a direct initializer for this field.
5228 if (CXXCtorInitializer *Init =
5229 Info.AllBaseFields.lookup(Val: Field->getCanonicalDecl()))
5230 return Info.addFieldInitializer(Init);
5231
5232 // C++11 [class.base.init]p8:
5233 // if the entity is a non-static data member that has a
5234 // brace-or-equal-initializer and either
5235 // -- the constructor's class is a union and no other variant member of that
5236 // union is designated by a mem-initializer-id or
5237 // -- the constructor's class is not a union, and, if the entity is a member
5238 // of an anonymous union, no other member of that union is designated by
5239 // a mem-initializer-id,
5240 // the entity is initialized as specified in [dcl.init].
5241 //
5242 // We also apply the same rules to handle anonymous structs within anonymous
5243 // unions.
5244 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5245 return false;
5246
5247 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5248 ExprResult DIE =
5249 SemaRef.BuildCXXDefaultInitExpr(Loc: Info.Ctor->getLocation(), Field);
5250 if (DIE.isInvalid())
5251 return true;
5252
5253 auto Entity = InitializedEntity::InitializeMember(Member: Field, Parent: nullptr, Implicit: true);
5254 SemaRef.checkInitializerLifetime(Entity, Init: DIE.get());
5255
5256 CXXCtorInitializer *Init;
5257 if (Indirect)
5258 Init = new (SemaRef.Context)
5259 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5260 SourceLocation(), DIE.get(), SourceLocation());
5261 else
5262 Init = new (SemaRef.Context)
5263 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5264 SourceLocation(), DIE.get(), SourceLocation());
5265 return Info.addFieldInitializer(Init);
5266 }
5267
5268 // Don't initialize incomplete or zero-length arrays.
5269 if (isIncompleteOrZeroLengthArrayType(Context&: SemaRef.Context, T: Field->getType()))
5270 return false;
5271
5272 // Don't try to build an implicit initializer if there were semantic
5273 // errors in any of the initializers (and therefore we might be
5274 // missing some that the user actually wrote).
5275 if (Info.AnyErrorsInInits)
5276 return false;
5277
5278 CXXCtorInitializer *Init = nullptr;
5279 if (BuildImplicitMemberInitializer(SemaRef&: Info.S, Constructor: Info.Ctor, ImplicitInitKind: Info.IIK, Field,
5280 Indirect, CXXMemberInit&: Init))
5281 return true;
5282
5283 if (!Init)
5284 return false;
5285
5286 return Info.addFieldInitializer(Init);
5287}
5288
5289bool
5290Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5291 CXXCtorInitializer *Initializer) {
5292 assert(Initializer->isDelegatingInitializer());
5293 Constructor->setNumCtorInitializers(1);
5294 CXXCtorInitializer **initializer =
5295 new (Context) CXXCtorInitializer*[1];
5296 memcpy(dest: initializer, src: &Initializer, n: sizeof (CXXCtorInitializer*));
5297 Constructor->setCtorInitializers(initializer);
5298
5299 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: Constructor->getParent())) {
5300 MarkFunctionReferenced(Loc: Initializer->getSourceLocation(), Func: Dtor);
5301 DiagnoseUseOfDecl(D: Dtor, Locs: Initializer->getSourceLocation());
5302 }
5303
5304 DelegatingCtorDecls.push_back(LocalValue: Constructor);
5305
5306 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5307
5308 return false;
5309}
5310
5311static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,
5312 CXXRecordDecl *Class) {
5313 if (Class->isInvalidDecl())
5314 return nullptr;
5315 if (Class->hasIrrelevantDestructor())
5316 return nullptr;
5317
5318 // Dtor might still be missing, e.g because it's invalid.
5319 return S.LookupDestructor(Class);
5320}
5321
5322static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,
5323 FieldDecl *Field) {
5324 if (Field->isInvalidDecl())
5325 return;
5326
5327 // Don't destroy incomplete or zero-length arrays.
5328 if (isIncompleteOrZeroLengthArrayType(Context&: S.Context, T: Field->getType()))
5329 return;
5330
5331 QualType FieldType = S.Context.getBaseElementType(QT: Field->getType());
5332
5333 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5334 if (!FieldClassDecl)
5335 return;
5336
5337 // The destructor for an implicit anonymous union member is never invoked.
5338 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5339 return;
5340
5341 auto *Dtor = LookupDestructorIfRelevant(S, Class: FieldClassDecl);
5342 if (!Dtor)
5343 return;
5344
5345 S.CheckDestructorAccess(Loc: Field->getLocation(), Dtor,
5346 PDiag: S.PDiag(DiagID: diag::err_access_dtor_field)
5347 << Field->getDeclName() << FieldType);
5348
5349 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5350 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5351}
5352
5353static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,
5354 CXXRecordDecl *ClassDecl) {
5355 if (ClassDecl->isDependentContext())
5356 return;
5357
5358 // We only potentially invoke the destructors of potentially constructed
5359 // subobjects.
5360 bool VisitVirtualBases = !ClassDecl->isAbstract();
5361
5362 // If the destructor exists and has already been marked used in the MS ABI,
5363 // then virtual base destructors have already been checked and marked used.
5364 // Skip checking them again to avoid duplicate diagnostics.
5365 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5366 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5367 if (Dtor && Dtor->isUsed())
5368 VisitVirtualBases = false;
5369 }
5370
5371 llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;
5372
5373 // Bases.
5374 for (const auto &Base : ClassDecl->bases()) {
5375 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5376 if (!BaseClassDecl)
5377 continue;
5378
5379 // Remember direct virtual bases.
5380 if (Base.isVirtual()) {
5381 if (!VisitVirtualBases)
5382 continue;
5383 DirectVirtualBases.insert(Ptr: BaseClassDecl);
5384 }
5385
5386 auto *Dtor = LookupDestructorIfRelevant(S, Class: BaseClassDecl);
5387 if (!Dtor)
5388 continue;
5389
5390 // FIXME: caret should be on the start of the class name
5391 S.CheckDestructorAccess(Loc: Base.getBeginLoc(), Dtor,
5392 PDiag: S.PDiag(DiagID: diag::err_access_dtor_base)
5393 << Base.getType() << Base.getSourceRange(),
5394 objectType: S.Context.getTypeDeclType(Decl: ClassDecl));
5395
5396 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5397 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5398 }
5399
5400 if (VisitVirtualBases)
5401 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5402 DirectVirtualBases: &DirectVirtualBases);
5403}
5404
5405bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5406 ArrayRef<CXXCtorInitializer *> Initializers) {
5407 if (Constructor->isDependentContext()) {
5408 // Just store the initializers as written, they will be checked during
5409 // instantiation.
5410 if (!Initializers.empty()) {
5411 Constructor->setNumCtorInitializers(Initializers.size());
5412 CXXCtorInitializer **baseOrMemberInitializers =
5413 new (Context) CXXCtorInitializer*[Initializers.size()];
5414 memcpy(dest: baseOrMemberInitializers, src: Initializers.data(),
5415 n: Initializers.size() * sizeof(CXXCtorInitializer*));
5416 Constructor->setCtorInitializers(baseOrMemberInitializers);
5417 }
5418
5419 // Let template instantiation know whether we had errors.
5420 if (AnyErrors)
5421 Constructor->setInvalidDecl();
5422
5423 return false;
5424 }
5425
5426 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5427
5428 // We need to build the initializer AST according to order of construction
5429 // and not what user specified in the Initializers list.
5430 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5431 if (!ClassDecl)
5432 return true;
5433
5434 bool HadError = false;
5435
5436 for (unsigned i = 0; i < Initializers.size(); i++) {
5437 CXXCtorInitializer *Member = Initializers[i];
5438
5439 if (Member->isBaseInitializer())
5440 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5441 else {
5442 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5443
5444 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5445 for (auto *C : F->chain()) {
5446 FieldDecl *FD = dyn_cast<FieldDecl>(Val: C);
5447 if (FD && FD->getParent()->isUnion())
5448 Info.ActiveUnionMember.insert(KV: std::make_pair(
5449 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5450 }
5451 } else if (FieldDecl *FD = Member->getMember()) {
5452 if (FD->getParent()->isUnion())
5453 Info.ActiveUnionMember.insert(KV: std::make_pair(
5454 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5455 }
5456 }
5457 }
5458
5459 // Keep track of the direct virtual bases.
5460 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5461 for (auto &I : ClassDecl->bases()) {
5462 if (I.isVirtual())
5463 DirectVBases.insert(Ptr: &I);
5464 }
5465
5466 // Push virtual bases before others.
5467 for (auto &VBase : ClassDecl->vbases()) {
5468 if (CXXCtorInitializer *Value
5469 = Info.AllBaseFields.lookup(Val: VBase.getType()->getAs<RecordType>())) {
5470 // [class.base.init]p7, per DR257:
5471 // A mem-initializer where the mem-initializer-id names a virtual base
5472 // class is ignored during execution of a constructor of any class that
5473 // is not the most derived class.
5474 if (ClassDecl->isAbstract()) {
5475 // FIXME: Provide a fixit to remove the base specifier. This requires
5476 // tracking the location of the associated comma for a base specifier.
5477 Diag(Loc: Value->getSourceLocation(), DiagID: diag::warn_abstract_vbase_init_ignored)
5478 << VBase.getType() << ClassDecl;
5479 DiagnoseAbstractType(RD: ClassDecl);
5480 }
5481
5482 Info.AllToInit.push_back(Elt: Value);
5483 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5484 // [class.base.init]p8, per DR257:
5485 // If a given [...] base class is not named by a mem-initializer-id
5486 // [...] and the entity is not a virtual base class of an abstract
5487 // class, then [...] the entity is default-initialized.
5488 bool IsInheritedVirtualBase = !DirectVBases.count(Ptr: &VBase);
5489 CXXCtorInitializer *CXXBaseInit;
5490 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5491 BaseSpec: &VBase, IsInheritedVirtualBase,
5492 CXXBaseInit)) {
5493 HadError = true;
5494 continue;
5495 }
5496
5497 Info.AllToInit.push_back(Elt: CXXBaseInit);
5498 }
5499 }
5500
5501 // Non-virtual bases.
5502 for (auto &Base : ClassDecl->bases()) {
5503 // Virtuals are in the virtual base list and already constructed.
5504 if (Base.isVirtual())
5505 continue;
5506
5507 if (CXXCtorInitializer *Value
5508 = Info.AllBaseFields.lookup(Val: Base.getType()->getAs<RecordType>())) {
5509 Info.AllToInit.push_back(Elt: Value);
5510 } else if (!AnyErrors) {
5511 CXXCtorInitializer *CXXBaseInit;
5512 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5513 BaseSpec: &Base, /*IsInheritedVirtualBase=*/false,
5514 CXXBaseInit)) {
5515 HadError = true;
5516 continue;
5517 }
5518
5519 Info.AllToInit.push_back(Elt: CXXBaseInit);
5520 }
5521 }
5522
5523 // Fields.
5524 for (auto *Mem : ClassDecl->decls()) {
5525 if (auto *F = dyn_cast<FieldDecl>(Val: Mem)) {
5526 // C++ [class.bit]p2:
5527 // A declaration for a bit-field that omits the identifier declares an
5528 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5529 // initialized.
5530 if (F->isUnnamedBitField())
5531 continue;
5532
5533 // If we're not generating the implicit copy/move constructor, then we'll
5534 // handle anonymous struct/union fields based on their individual
5535 // indirect fields.
5536 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5537 continue;
5538
5539 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F))
5540 HadError = true;
5541 continue;
5542 }
5543
5544 // Beyond this point, we only consider default initialization.
5545 if (Info.isImplicitCopyOrMove())
5546 continue;
5547
5548 if (auto *F = dyn_cast<IndirectFieldDecl>(Val: Mem)) {
5549 if (F->getType()->isIncompleteArrayType()) {
5550 assert(ClassDecl->hasFlexibleArrayMember() &&
5551 "Incomplete array type is not valid");
5552 continue;
5553 }
5554
5555 // Initialize each field of an anonymous struct individually.
5556 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F->getAnonField(), Indirect: F))
5557 HadError = true;
5558
5559 continue;
5560 }
5561 }
5562
5563 unsigned NumInitializers = Info.AllToInit.size();
5564 if (NumInitializers > 0) {
5565 Constructor->setNumCtorInitializers(NumInitializers);
5566 CXXCtorInitializer **baseOrMemberInitializers =
5567 new (Context) CXXCtorInitializer*[NumInitializers];
5568 memcpy(dest: baseOrMemberInitializers, src: Info.AllToInit.data(),
5569 n: NumInitializers * sizeof(CXXCtorInitializer*));
5570 Constructor->setCtorInitializers(baseOrMemberInitializers);
5571
5572 SourceLocation Location = Constructor->getLocation();
5573
5574 // Constructors implicitly reference the base and member
5575 // destructors.
5576
5577 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5578 FieldDecl *Field = Initializer->getAnyMember();
5579 if (!Field)
5580 continue;
5581
5582 // C++ [class.base.init]p12:
5583 // In a non-delegating constructor, the destructor for each
5584 // potentially constructed subobject of class type is potentially
5585 // invoked.
5586 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5587 }
5588
5589 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl: Constructor->getParent());
5590 }
5591
5592 return HadError;
5593}
5594
5595static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5596 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5597 const RecordDecl *RD = RT->getDecl();
5598 if (RD->isAnonymousStructOrUnion()) {
5599 for (auto *Field : RD->fields())
5600 PopulateKeysForFields(Field, IdealInits);
5601 return;
5602 }
5603 }
5604 IdealInits.push_back(Elt: Field->getCanonicalDecl());
5605}
5606
5607static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5608 return Context.getCanonicalType(T: BaseType).getTypePtr();
5609}
5610
5611static const void *GetKeyForMember(ASTContext &Context,
5612 CXXCtorInitializer *Member) {
5613 if (!Member->isAnyMemberInitializer())
5614 return GetKeyForBase(Context, BaseType: QualType(Member->getBaseClass(), 0));
5615
5616 return Member->getAnyMember()->getCanonicalDecl();
5617}
5618
5619static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5620 const CXXCtorInitializer *Previous,
5621 const CXXCtorInitializer *Current) {
5622 if (Previous->isAnyMemberInitializer())
5623 Diag << 0 << Previous->getAnyMember();
5624 else
5625 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5626
5627 if (Current->isAnyMemberInitializer())
5628 Diag << 0 << Current->getAnyMember();
5629 else
5630 Diag << 1 << Current->getTypeSourceInfo()->getType();
5631}
5632
5633static void DiagnoseBaseOrMemInitializerOrder(
5634 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5635 ArrayRef<CXXCtorInitializer *> Inits) {
5636 if (Constructor->getDeclContext()->isDependentContext())
5637 return;
5638
5639 // Don't check initializers order unless the warning is enabled at the
5640 // location of at least one initializer.
5641 bool ShouldCheckOrder = false;
5642 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5643 CXXCtorInitializer *Init = Inits[InitIndex];
5644 if (!SemaRef.Diags.isIgnored(DiagID: diag::warn_initializer_out_of_order,
5645 Loc: Init->getSourceLocation())) {
5646 ShouldCheckOrder = true;
5647 break;
5648 }
5649 }
5650 if (!ShouldCheckOrder)
5651 return;
5652
5653 // Build the list of bases and members in the order that they'll
5654 // actually be initialized. The explicit initializers should be in
5655 // this same order but may be missing things.
5656 SmallVector<const void*, 32> IdealInitKeys;
5657
5658 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5659
5660 // 1. Virtual bases.
5661 for (const auto &VBase : ClassDecl->vbases())
5662 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: VBase.getType()));
5663
5664 // 2. Non-virtual bases.
5665 for (const auto &Base : ClassDecl->bases()) {
5666 if (Base.isVirtual())
5667 continue;
5668 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: Base.getType()));
5669 }
5670
5671 // 3. Direct fields.
5672 for (auto *Field : ClassDecl->fields()) {
5673 if (Field->isUnnamedBitField())
5674 continue;
5675
5676 PopulateKeysForFields(Field, IdealInits&: IdealInitKeys);
5677 }
5678
5679 unsigned NumIdealInits = IdealInitKeys.size();
5680 unsigned IdealIndex = 0;
5681
5682 // Track initializers that are in an incorrect order for either a warning or
5683 // note if multiple ones occur.
5684 SmallVector<unsigned> WarnIndexes;
5685 // Correlates the index of an initializer in the init-list to the index of
5686 // the field/base in the class.
5687 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5688
5689 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5690 const void *InitKey = GetKeyForMember(Context&: SemaRef.Context, Member: Inits[InitIndex]);
5691
5692 // Scan forward to try to find this initializer in the idealized
5693 // initializers list.
5694 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5695 if (InitKey == IdealInitKeys[IdealIndex])
5696 break;
5697
5698 // If we didn't find this initializer, it must be because we
5699 // scanned past it on a previous iteration. That can only
5700 // happen if we're out of order; emit a warning.
5701 if (IdealIndex == NumIdealInits && InitIndex) {
5702 WarnIndexes.push_back(Elt: InitIndex);
5703
5704 // Move back to the initializer's location in the ideal list.
5705 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5706 if (InitKey == IdealInitKeys[IdealIndex])
5707 break;
5708
5709 assert(IdealIndex < NumIdealInits &&
5710 "initializer not found in initializer list");
5711 }
5712 CorrelatedInitOrder.emplace_back(Args&: IdealIndex, Args&: InitIndex);
5713 }
5714
5715 if (WarnIndexes.empty())
5716 return;
5717
5718 // Sort based on the ideal order, first in the pair.
5719 llvm::sort(C&: CorrelatedInitOrder, Comp: llvm::less_first());
5720
5721 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5722 // emit the diagnostic before we can try adding notes.
5723 {
5724 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5725 Loc: Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5726 DiagID: WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5727 : diag::warn_some_initializers_out_of_order);
5728
5729 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5730 if (CorrelatedInitOrder[I].second == I)
5731 continue;
5732 // Ideally we would be using InsertFromRange here, but clang doesn't
5733 // appear to handle InsertFromRange correctly when the source range is
5734 // modified by another fix-it.
5735 D << FixItHint::CreateReplacement(
5736 RemoveRange: Inits[I]->getSourceRange(),
5737 Code: Lexer::getSourceText(
5738 Range: CharSourceRange::getTokenRange(
5739 R: Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5740 SM: SemaRef.getSourceManager(), LangOpts: SemaRef.getLangOpts()));
5741 }
5742
5743 // If there is only 1 item out of order, the warning expects the name and
5744 // type of each being added to it.
5745 if (WarnIndexes.size() == 1) {
5746 AddInitializerToDiag(Diag: D, Previous: Inits[WarnIndexes.front() - 1],
5747 Current: Inits[WarnIndexes.front()]);
5748 return;
5749 }
5750 }
5751 // More than 1 item to warn, create notes letting the user know which ones
5752 // are bad.
5753 for (unsigned WarnIndex : WarnIndexes) {
5754 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5755 auto D = SemaRef.Diag(Loc: PrevInit->getSourceLocation(),
5756 DiagID: diag::note_initializer_out_of_order);
5757 AddInitializerToDiag(Diag: D, Previous: PrevInit, Current: Inits[WarnIndex]);
5758 D << PrevInit->getSourceRange();
5759 }
5760}
5761
5762namespace {
5763bool CheckRedundantInit(Sema &S,
5764 CXXCtorInitializer *Init,
5765 CXXCtorInitializer *&PrevInit) {
5766 if (!PrevInit) {
5767 PrevInit = Init;
5768 return false;
5769 }
5770
5771 if (FieldDecl *Field = Init->getAnyMember())
5772 S.Diag(Loc: Init->getSourceLocation(),
5773 DiagID: diag::err_multiple_mem_initialization)
5774 << Field->getDeclName()
5775 << Init->getSourceRange();
5776 else {
5777 const Type *BaseClass = Init->getBaseClass();
5778 assert(BaseClass && "neither field nor base");
5779 S.Diag(Loc: Init->getSourceLocation(),
5780 DiagID: diag::err_multiple_base_initialization)
5781 << QualType(BaseClass, 0)
5782 << Init->getSourceRange();
5783 }
5784 S.Diag(Loc: PrevInit->getSourceLocation(), DiagID: diag::note_previous_initializer)
5785 << 0 << PrevInit->getSourceRange();
5786
5787 return true;
5788}
5789
5790typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5791typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5792
5793bool CheckRedundantUnionInit(Sema &S,
5794 CXXCtorInitializer *Init,
5795 RedundantUnionMap &Unions) {
5796 FieldDecl *Field = Init->getAnyMember();
5797 RecordDecl *Parent = Field->getParent();
5798 NamedDecl *Child = Field;
5799
5800 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5801 if (Parent->isUnion()) {
5802 UnionEntry &En = Unions[Parent];
5803 if (En.first && En.first != Child) {
5804 S.Diag(Loc: Init->getSourceLocation(),
5805 DiagID: diag::err_multiple_mem_union_initialization)
5806 << Field->getDeclName()
5807 << Init->getSourceRange();
5808 S.Diag(Loc: En.second->getSourceLocation(), DiagID: diag::note_previous_initializer)
5809 << 0 << En.second->getSourceRange();
5810 return true;
5811 }
5812 if (!En.first) {
5813 En.first = Child;
5814 En.second = Init;
5815 }
5816 if (!Parent->isAnonymousStructOrUnion())
5817 return false;
5818 }
5819
5820 Child = Parent;
5821 Parent = cast<RecordDecl>(Val: Parent->getDeclContext());
5822 }
5823
5824 return false;
5825}
5826} // namespace
5827
5828void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5829 SourceLocation ColonLoc,
5830 ArrayRef<CXXCtorInitializer*> MemInits,
5831 bool AnyErrors) {
5832 if (!ConstructorDecl)
5833 return;
5834
5835 AdjustDeclIfTemplate(Decl&: ConstructorDecl);
5836
5837 CXXConstructorDecl *Constructor
5838 = dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl);
5839
5840 if (!Constructor) {
5841 Diag(Loc: ColonLoc, DiagID: diag::err_only_constructors_take_base_inits);
5842 return;
5843 }
5844
5845 // Mapping for the duplicate initializers check.
5846 // For member initializers, this is keyed with a FieldDecl*.
5847 // For base initializers, this is keyed with a Type*.
5848 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5849
5850 // Mapping for the inconsistent anonymous-union initializers check.
5851 RedundantUnionMap MemberUnions;
5852
5853 bool HadError = false;
5854 for (unsigned i = 0; i < MemInits.size(); i++) {
5855 CXXCtorInitializer *Init = MemInits[i];
5856
5857 // Set the source order index.
5858 Init->setSourceOrder(i);
5859
5860 if (Init->isAnyMemberInitializer()) {
5861 const void *Key = GetKeyForMember(Context, Member: Init);
5862 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]) ||
5863 CheckRedundantUnionInit(S&: *this, Init, Unions&: MemberUnions))
5864 HadError = true;
5865 } else if (Init->isBaseInitializer()) {
5866 const void *Key = GetKeyForMember(Context, Member: Init);
5867 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]))
5868 HadError = true;
5869 } else {
5870 assert(Init->isDelegatingInitializer());
5871 // This must be the only initializer
5872 if (MemInits.size() != 1) {
5873 Diag(Loc: Init->getSourceLocation(),
5874 DiagID: diag::err_delegating_initializer_alone)
5875 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5876 // We will treat this as being the only initializer.
5877 }
5878 SetDelegatingInitializer(Constructor, Initializer: MemInits[i]);
5879 // Return immediately as the initializer is set.
5880 return;
5881 }
5882 }
5883
5884 if (HadError)
5885 return;
5886
5887 DiagnoseBaseOrMemInitializerOrder(SemaRef&: *this, Constructor, Inits: MemInits);
5888
5889 SetCtorInitializers(Constructor, AnyErrors, Initializers: MemInits);
5890
5891 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5892}
5893
5894void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5895 CXXRecordDecl *ClassDecl) {
5896 // Ignore dependent contexts. Also ignore unions, since their members never
5897 // have destructors implicitly called.
5898 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5899 return;
5900
5901 // FIXME: all the access-control diagnostics are positioned on the
5902 // field/base declaration. That's probably good; that said, the
5903 // user might reasonably want to know why the destructor is being
5904 // emitted, and we currently don't say.
5905
5906 // Non-static data members.
5907 for (auto *Field : ClassDecl->fields()) {
5908 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5909 }
5910
5911 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl);
5912}
5913
5914void Sema::MarkVirtualBaseDestructorsReferenced(
5915 SourceLocation Location, CXXRecordDecl *ClassDecl,
5916 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5917 // Virtual bases.
5918 for (const auto &VBase : ClassDecl->vbases()) {
5919 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5920 if (!BaseClassDecl)
5921 continue;
5922
5923 // Ignore already visited direct virtual bases.
5924 if (DirectVirtualBases && DirectVirtualBases->count(Ptr: BaseClassDecl))
5925 continue;
5926
5927 auto *Dtor = LookupDestructorIfRelevant(S&: *this, Class: BaseClassDecl);
5928 if (!Dtor)
5929 continue;
5930
5931 if (CheckDestructorAccess(
5932 Loc: ClassDecl->getLocation(), Dtor,
5933 PDiag: PDiag(DiagID: diag::err_access_dtor_vbase)
5934 << Context.getTypeDeclType(Decl: ClassDecl) << VBase.getType(),
5935 objectType: Context.getTypeDeclType(Decl: ClassDecl)) ==
5936 AR_accessible) {
5937 CheckDerivedToBaseConversion(
5938 Derived: Context.getTypeDeclType(Decl: ClassDecl), Base: VBase.getType(),
5939 InaccessibleBaseID: diag::err_access_dtor_vbase, AmbiguousBaseConvID: 0, Loc: ClassDecl->getLocation(),
5940 Range: SourceRange(), Name: DeclarationName(), BasePath: nullptr);
5941 }
5942
5943 MarkFunctionReferenced(Loc: Location, Func: Dtor);
5944 DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5945 }
5946}
5947
5948void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5949 if (!CDtorDecl)
5950 return;
5951
5952 if (CXXConstructorDecl *Constructor
5953 = dyn_cast<CXXConstructorDecl>(Val: CDtorDecl)) {
5954 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5955 !ClassDecl || ClassDecl->isInvalidDecl()) {
5956 return;
5957 }
5958 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5959 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5960 }
5961}
5962
5963bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5964 if (!getLangOpts().CPlusPlus)
5965 return false;
5966
5967 const auto *RD = Context.getBaseElementType(QT: T)->getAsCXXRecordDecl();
5968 if (!RD)
5969 return false;
5970
5971 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5972 // class template specialization here, but doing so breaks a lot of code.
5973
5974 // We can't answer whether something is abstract until it has a
5975 // definition. If it's currently being defined, we'll walk back
5976 // over all the declarations when we have a full definition.
5977 const CXXRecordDecl *Def = RD->getDefinition();
5978 if (!Def || Def->isBeingDefined())
5979 return false;
5980
5981 return RD->isAbstract();
5982}
5983
5984bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5985 TypeDiagnoser &Diagnoser) {
5986 if (!isAbstractType(Loc, T))
5987 return false;
5988
5989 T = Context.getBaseElementType(QT: T);
5990 Diagnoser.diagnose(S&: *this, Loc, T);
5991 DiagnoseAbstractType(RD: T->getAsCXXRecordDecl());
5992 return true;
5993}
5994
5995void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5996 // Check if we've already emitted the list of pure virtual functions
5997 // for this class.
5998 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(Ptr: RD))
5999 return;
6000
6001 // If the diagnostic is suppressed, don't emit the notes. We're only
6002 // going to emit them once, so try to attach them to a diagnostic we're
6003 // actually going to show.
6004 if (Diags.isLastDiagnosticIgnored())
6005 return;
6006
6007 CXXFinalOverriderMap FinalOverriders;
6008 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
6009
6010 // Keep a set of seen pure methods so we won't diagnose the same method
6011 // more than once.
6012 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6013
6014 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
6015 MEnd = FinalOverriders.end();
6016 M != MEnd;
6017 ++M) {
6018 for (OverridingMethods::iterator SO = M->second.begin(),
6019 SOEnd = M->second.end();
6020 SO != SOEnd; ++SO) {
6021 // C++ [class.abstract]p4:
6022 // A class is abstract if it contains or inherits at least one
6023 // pure virtual function for which the final overrider is pure
6024 // virtual.
6025
6026 //
6027 if (SO->second.size() != 1)
6028 continue;
6029
6030 if (!SO->second.front().Method->isPureVirtual())
6031 continue;
6032
6033 if (!SeenPureMethods.insert(Ptr: SO->second.front().Method).second)
6034 continue;
6035
6036 Diag(Loc: SO->second.front().Method->getLocation(),
6037 DiagID: diag::note_pure_virtual_function)
6038 << SO->second.front().Method->getDeclName() << RD->getDeclName();
6039 }
6040 }
6041
6042 if (!PureVirtualClassDiagSet)
6043 PureVirtualClassDiagSet.reset(p: new RecordDeclSetTy);
6044 PureVirtualClassDiagSet->insert(Ptr: RD);
6045}
6046
6047namespace {
6048struct AbstractUsageInfo {
6049 Sema &S;
6050 CXXRecordDecl *Record;
6051 CanQualType AbstractType;
6052 bool Invalid;
6053
6054 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6055 : S(S), Record(Record),
6056 AbstractType(S.Context.getCanonicalType(
6057 T: S.Context.getTypeDeclType(Decl: Record))),
6058 Invalid(false) {}
6059
6060 void DiagnoseAbstractType() {
6061 if (Invalid) return;
6062 S.DiagnoseAbstractType(RD: Record);
6063 Invalid = true;
6064 }
6065
6066 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6067};
6068
6069struct CheckAbstractUsage {
6070 AbstractUsageInfo &Info;
6071 const NamedDecl *Ctx;
6072
6073 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6074 : Info(Info), Ctx(Ctx) {}
6075
6076 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6077 switch (TL.getTypeLocClass()) {
6078#define ABSTRACT_TYPELOC(CLASS, PARENT)
6079#define TYPELOC(CLASS, PARENT) \
6080 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6081#include "clang/AST/TypeLocNodes.def"
6082 }
6083 }
6084
6085 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6086 Visit(TL: TL.getReturnLoc(), Sel: Sema::AbstractReturnType);
6087 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6088 if (!TL.getParam(i: I))
6089 continue;
6090
6091 TypeSourceInfo *TSI = TL.getParam(i: I)->getTypeSourceInfo();
6092 if (TSI) Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractParamType);
6093 }
6094 }
6095
6096 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6097 Visit(TL: TL.getElementLoc(), Sel: Sema::AbstractArrayType);
6098 }
6099
6100 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6101 // Visit the type parameters from a permissive context.
6102 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6103 TemplateArgumentLoc TAL = TL.getArgLoc(i: I);
6104 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6105 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6106 Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6107 // TODO: other template argument types?
6108 }
6109 }
6110
6111 // Visit pointee types from a permissive context.
6112#define CheckPolymorphic(Type) \
6113 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6114 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6115 }
6116 CheckPolymorphic(PointerTypeLoc)
6117 CheckPolymorphic(ReferenceTypeLoc)
6118 CheckPolymorphic(MemberPointerTypeLoc)
6119 CheckPolymorphic(BlockPointerTypeLoc)
6120 CheckPolymorphic(AtomicTypeLoc)
6121
6122 /// Handle all the types we haven't given a more specific
6123 /// implementation for above.
6124 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6125 // Every other kind of type that we haven't called out already
6126 // that has an inner type is either (1) sugar or (2) contains that
6127 // inner type in some way as a subobject.
6128 if (TypeLoc Next = TL.getNextTypeLoc())
6129 return Visit(TL: Next, Sel);
6130
6131 // If there's no inner type and we're in a permissive context,
6132 // don't diagnose.
6133 if (Sel == Sema::AbstractNone) return;
6134
6135 // Check whether the type matches the abstract type.
6136 QualType T = TL.getType();
6137 if (T->isArrayType()) {
6138 Sel = Sema::AbstractArrayType;
6139 T = Info.S.Context.getBaseElementType(QT: T);
6140 }
6141 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
6142 if (CT != Info.AbstractType) return;
6143
6144 // It matched; do some magic.
6145 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6146 if (Sel == Sema::AbstractArrayType) {
6147 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_array_of_abstract_type)
6148 << T << TL.getSourceRange();
6149 } else {
6150 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_abstract_type_in_decl)
6151 << Sel << T << TL.getSourceRange();
6152 }
6153 Info.DiagnoseAbstractType();
6154 }
6155};
6156
6157void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6158 Sema::AbstractDiagSelID Sel) {
6159 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6160}
6161
6162}
6163
6164/// Check for invalid uses of an abstract type in a function declaration.
6165static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6166 FunctionDecl *FD) {
6167 // Only definitions are required to refer to complete and
6168 // non-abstract types.
6169 if (!FD->doesThisDeclarationHaveABody())
6170 return;
6171
6172 // For safety's sake, just ignore it if we don't have type source
6173 // information. This should never happen for non-implicit methods,
6174 // but...
6175 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6176 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6177}
6178
6179/// Check for invalid uses of an abstract type in a variable0 declaration.
6180static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6181 VarDecl *VD) {
6182 // No need to do the check on definitions, which require that
6183 // the type is complete.
6184 if (VD->isThisDeclarationADefinition())
6185 return;
6186
6187 Info.CheckType(D: VD, TL: VD->getTypeSourceInfo()->getTypeLoc(),
6188 Sel: Sema::AbstractVariableType);
6189}
6190
6191/// Check for invalid uses of an abstract type within a class definition.
6192static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6193 CXXRecordDecl *RD) {
6194 for (auto *D : RD->decls()) {
6195 if (D->isImplicit()) continue;
6196
6197 // Step through friends to the befriended declaration.
6198 if (auto *FD = dyn_cast<FriendDecl>(Val: D)) {
6199 D = FD->getFriendDecl();
6200 if (!D) continue;
6201 }
6202
6203 // Functions and function templates.
6204 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
6205 CheckAbstractClassUsage(Info, FD);
6206 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6207 CheckAbstractClassUsage(Info, FD: FTD->getTemplatedDecl());
6208
6209 // Fields and static variables.
6210 } else if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
6211 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6212 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractFieldType);
6213 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
6214 CheckAbstractClassUsage(Info, VD);
6215 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D)) {
6216 CheckAbstractClassUsage(Info, VD: VTD->getTemplatedDecl());
6217
6218 // Nested classes and class templates.
6219 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
6220 CheckAbstractClassUsage(Info, RD);
6221 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) {
6222 CheckAbstractClassUsage(Info, RD: CTD->getTemplatedDecl());
6223 }
6224 }
6225}
6226
6227static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6228 Attr *ClassAttr = getDLLAttr(D: Class);
6229 if (!ClassAttr)
6230 return;
6231
6232 assert(ClassAttr->getKind() == attr::DLLExport);
6233
6234 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6235
6236 if (TSK == TSK_ExplicitInstantiationDeclaration)
6237 // Don't go any further if this is just an explicit instantiation
6238 // declaration.
6239 return;
6240
6241 // Add a context note to explain how we got to any diagnostics produced below.
6242 struct MarkingClassDllexported {
6243 Sema &S;
6244 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6245 SourceLocation AttrLoc)
6246 : S(S) {
6247 Sema::CodeSynthesisContext Ctx;
6248 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6249 Ctx.PointOfInstantiation = AttrLoc;
6250 Ctx.Entity = Class;
6251 S.pushCodeSynthesisContext(Ctx);
6252 }
6253 ~MarkingClassDllexported() {
6254 S.popCodeSynthesisContext();
6255 }
6256 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6257
6258 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6259 S.MarkVTableUsed(Loc: Class->getLocation(), Class, DefinitionRequired: true);
6260
6261 for (Decl *Member : Class->decls()) {
6262 // Skip members that were not marked exported.
6263 if (!Member->hasAttr<DLLExportAttr>())
6264 continue;
6265
6266 // Defined static variables that are members of an exported base
6267 // class must be marked export too.
6268 auto *VD = dyn_cast<VarDecl>(Val: Member);
6269 if (VD && VD->getStorageClass() == SC_Static &&
6270 TSK == TSK_ImplicitInstantiation)
6271 S.MarkVariableReferenced(Loc: VD->getLocation(), Var: VD);
6272
6273 auto *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6274 if (!MD)
6275 continue;
6276
6277 if (MD->isUserProvided()) {
6278 // Instantiate non-default class member functions ...
6279
6280 // .. except for certain kinds of template specializations.
6281 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6282 continue;
6283
6284 // If this is an MS ABI dllexport default constructor, instantiate any
6285 // default arguments.
6286 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6287 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6288 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6289 S.InstantiateDefaultCtorDefaultArgs(Ctor: CD);
6290 }
6291 }
6292
6293 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6294
6295 // The function will be passed to the consumer when its definition is
6296 // encountered.
6297 } else if (MD->isExplicitlyDefaulted()) {
6298 // Synthesize and instantiate explicitly defaulted methods.
6299 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6300
6301 if (TSK != TSK_ExplicitInstantiationDefinition) {
6302 // Except for explicit instantiation defs, we will not see the
6303 // definition again later, so pass it to the consumer now.
6304 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6305 }
6306 } else if (!MD->isTrivial() ||
6307 MD->isCopyAssignmentOperator() ||
6308 MD->isMoveAssignmentOperator()) {
6309 // Synthesize and instantiate non-trivial implicit methods, and the copy
6310 // and move assignment operators. The latter are exported even if they
6311 // are trivial, because the address of an operator can be taken and
6312 // should compare equal across libraries.
6313 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6314
6315 // There is no later point when we will see the definition of this
6316 // function, so pass it to the consumer now.
6317 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6318 }
6319 }
6320}
6321
6322static void checkForMultipleExportedDefaultConstructors(Sema &S,
6323 CXXRecordDecl *Class) {
6324 // Only the MS ABI has default constructor closures, so we don't need to do
6325 // this semantic checking anywhere else.
6326 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6327 return;
6328
6329 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6330 for (Decl *Member : Class->decls()) {
6331 // Look for exported default constructors.
6332 auto *CD = dyn_cast<CXXConstructorDecl>(Val: Member);
6333 if (!CD || !CD->isDefaultConstructor())
6334 continue;
6335 auto *Attr = CD->getAttr<DLLExportAttr>();
6336 if (!Attr)
6337 continue;
6338
6339 // If the class is non-dependent, mark the default arguments as ODR-used so
6340 // that we can properly codegen the constructor closure.
6341 if (!Class->isDependentContext()) {
6342 for (ParmVarDecl *PD : CD->parameters()) {
6343 (void)S.CheckCXXDefaultArgExpr(CallLoc: Attr->getLocation(), FD: CD, Param: PD);
6344 S.DiscardCleanupsInEvaluationContext();
6345 }
6346 }
6347
6348 if (LastExportedDefaultCtor) {
6349 S.Diag(Loc: LastExportedDefaultCtor->getLocation(),
6350 DiagID: diag::err_attribute_dll_ambiguous_default_ctor)
6351 << Class;
6352 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_entity_declared_at)
6353 << CD->getDeclName();
6354 return;
6355 }
6356 LastExportedDefaultCtor = CD;
6357 }
6358}
6359
6360static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6361 CXXRecordDecl *Class) {
6362 bool ErrorReported = false;
6363 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6364 ClassTemplateDecl *TD) {
6365 if (ErrorReported)
6366 return;
6367 S.Diag(Loc: TD->getLocation(),
6368 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6369 << /*surface*/ 0 << TD;
6370 ErrorReported = true;
6371 };
6372
6373 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6374 if (!TD) {
6375 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6376 if (!SD) {
6377 S.Diag(Loc: Class->getLocation(),
6378 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6379 << /*surface*/ 0 << Class;
6380 S.Diag(Loc: Class->getLocation(),
6381 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6382 << Class;
6383 return;
6384 }
6385 TD = SD->getSpecializedTemplate();
6386 }
6387
6388 TemplateParameterList *Params = TD->getTemplateParameters();
6389 unsigned N = Params->size();
6390
6391 if (N != 2) {
6392 reportIllegalClassTemplate(S, TD);
6393 S.Diag(Loc: TD->getLocation(),
6394 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6395 << TD << 2;
6396 }
6397 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6398 reportIllegalClassTemplate(S, TD);
6399 S.Diag(Loc: TD->getLocation(),
6400 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6401 << TD << /*1st*/ 0 << /*type*/ 0;
6402 }
6403 if (N > 1) {
6404 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6405 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6406 reportIllegalClassTemplate(S, TD);
6407 S.Diag(Loc: TD->getLocation(),
6408 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6409 << TD << /*2nd*/ 1 << /*integer*/ 1;
6410 }
6411 }
6412}
6413
6414static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6415 CXXRecordDecl *Class) {
6416 bool ErrorReported = false;
6417 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6418 ClassTemplateDecl *TD) {
6419 if (ErrorReported)
6420 return;
6421 S.Diag(Loc: TD->getLocation(),
6422 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6423 << /*texture*/ 1 << TD;
6424 ErrorReported = true;
6425 };
6426
6427 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6428 if (!TD) {
6429 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6430 if (!SD) {
6431 S.Diag(Loc: Class->getLocation(),
6432 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6433 << /*texture*/ 1 << Class;
6434 S.Diag(Loc: Class->getLocation(),
6435 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6436 << Class;
6437 return;
6438 }
6439 TD = SD->getSpecializedTemplate();
6440 }
6441
6442 TemplateParameterList *Params = TD->getTemplateParameters();
6443 unsigned N = Params->size();
6444
6445 if (N != 3) {
6446 reportIllegalClassTemplate(S, TD);
6447 S.Diag(Loc: TD->getLocation(),
6448 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6449 << TD << 3;
6450 }
6451 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6452 reportIllegalClassTemplate(S, TD);
6453 S.Diag(Loc: TD->getLocation(),
6454 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6455 << TD << /*1st*/ 0 << /*type*/ 0;
6456 }
6457 if (N > 1) {
6458 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6459 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6460 reportIllegalClassTemplate(S, TD);
6461 S.Diag(Loc: TD->getLocation(),
6462 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6463 << TD << /*2nd*/ 1 << /*integer*/ 1;
6464 }
6465 }
6466 if (N > 2) {
6467 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 2));
6468 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6469 reportIllegalClassTemplate(S, TD);
6470 S.Diag(Loc: TD->getLocation(),
6471 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6472 << TD << /*3rd*/ 2 << /*integer*/ 1;
6473 }
6474 }
6475}
6476
6477void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6478 // Mark any compiler-generated routines with the implicit code_seg attribute.
6479 for (auto *Method : Class->methods()) {
6480 if (Method->isUserProvided())
6481 continue;
6482 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(FD: Method, /*IsDefinition=*/true))
6483 Method->addAttr(A);
6484 }
6485}
6486
6487void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6488 Attr *ClassAttr = getDLLAttr(D: Class);
6489
6490 // MSVC inherits DLL attributes to partial class template specializations.
6491 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6492 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Class)) {
6493 if (Attr *TemplateAttr =
6494 getDLLAttr(D: Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6495 auto *A = cast<InheritableAttr>(Val: TemplateAttr->clone(C&: getASTContext()));
6496 A->setInherited(true);
6497 ClassAttr = A;
6498 }
6499 }
6500 }
6501
6502 if (!ClassAttr)
6503 return;
6504
6505 // MSVC allows imported or exported template classes that have UniqueExternal
6506 // linkage. This occurs when the template class has been instantiated with
6507 // a template parameter which itself has internal linkage.
6508 // We drop the attribute to avoid exporting or importing any members.
6509 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6510 Context.getTargetInfo().getTriple().isPS()) &&
6511 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6512 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6513 return;
6514 }
6515
6516 if (!Class->isExternallyVisible()) {
6517 Diag(Loc: Class->getLocation(), DiagID: diag::err_attribute_dll_not_extern)
6518 << Class << ClassAttr;
6519 return;
6520 }
6521
6522 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6523 !ClassAttr->isInherited()) {
6524 // Diagnose dll attributes on members of class with dll attribute.
6525 for (Decl *Member : Class->decls()) {
6526 if (!isa<VarDecl>(Val: Member) && !isa<CXXMethodDecl>(Val: Member))
6527 continue;
6528 InheritableAttr *MemberAttr = getDLLAttr(D: Member);
6529 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6530 continue;
6531
6532 Diag(Loc: MemberAttr->getLocation(),
6533 DiagID: diag::err_attribute_dll_member_of_dll_class)
6534 << MemberAttr << ClassAttr;
6535 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_previous_attribute);
6536 Member->setInvalidDecl();
6537 }
6538 }
6539
6540 if (Class->getDescribedClassTemplate())
6541 // Don't inherit dll attribute until the template is instantiated.
6542 return;
6543
6544 // The class is either imported or exported.
6545 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6546
6547 // Check if this was a dllimport attribute propagated from a derived class to
6548 // a base class template specialization. We don't apply these attributes to
6549 // static data members.
6550 const bool PropagatedImport =
6551 !ClassExported &&
6552 cast<DLLImportAttr>(Val: ClassAttr)->wasPropagatedToBaseTemplate();
6553
6554 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6555
6556 // Ignore explicit dllexport on explicit class template instantiation
6557 // declarations, except in MinGW mode.
6558 if (ClassExported && !ClassAttr->isInherited() &&
6559 TSK == TSK_ExplicitInstantiationDeclaration &&
6560 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6561 Class->dropAttr<DLLExportAttr>();
6562 return;
6563 }
6564
6565 // Force declaration of implicit members so they can inherit the attribute.
6566 ForceDeclarationOfImplicitMembers(Class);
6567
6568 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6569 // seem to be true in practice?
6570
6571 for (Decl *Member : Class->decls()) {
6572 VarDecl *VD = dyn_cast<VarDecl>(Val: Member);
6573 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6574
6575 // Only methods and static fields inherit the attributes.
6576 if (!VD && !MD)
6577 continue;
6578
6579 if (MD) {
6580 // Don't process deleted methods.
6581 if (MD->isDeleted())
6582 continue;
6583
6584 if (MD->isInlined()) {
6585 // MinGW does not import or export inline methods. But do it for
6586 // template instantiations.
6587 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6588 TSK != TSK_ExplicitInstantiationDeclaration &&
6589 TSK != TSK_ExplicitInstantiationDefinition)
6590 continue;
6591
6592 // MSVC versions before 2015 don't export the move assignment operators
6593 // and move constructor, so don't attempt to import/export them if
6594 // we have a definition.
6595 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: MD);
6596 if ((MD->isMoveAssignmentOperator() ||
6597 (Ctor && Ctor->isMoveConstructor())) &&
6598 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015))
6599 continue;
6600
6601 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6602 // operator is exported anyway.
6603 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
6604 (Ctor || isa<CXXDestructorDecl>(Val: MD)) && MD->isTrivial())
6605 continue;
6606 }
6607 }
6608
6609 // Don't apply dllimport attributes to static data members of class template
6610 // instantiations when the attribute is propagated from a derived class.
6611 if (VD && PropagatedImport)
6612 continue;
6613
6614 if (!cast<NamedDecl>(Val: Member)->isExternallyVisible())
6615 continue;
6616
6617 if (!getDLLAttr(D: Member)) {
6618 InheritableAttr *NewAttr = nullptr;
6619
6620 // Do not export/import inline function when -fno-dllexport-inlines is
6621 // passed. But add attribute for later local static var check.
6622 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6623 TSK != TSK_ExplicitInstantiationDeclaration &&
6624 TSK != TSK_ExplicitInstantiationDefinition) {
6625 if (ClassExported) {
6626 NewAttr = ::new (getASTContext())
6627 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6628 } else {
6629 NewAttr = ::new (getASTContext())
6630 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6631 }
6632 } else {
6633 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6634 }
6635
6636 NewAttr->setInherited(true);
6637 Member->addAttr(A: NewAttr);
6638
6639 if (MD) {
6640 // Propagate DLLAttr to friend re-declarations of MD that have already
6641 // been constructed.
6642 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6643 FD = FD->getPreviousDecl()) {
6644 if (FD->getFriendObjectKind() == Decl::FOK_None)
6645 continue;
6646 assert(!getDLLAttr(FD) &&
6647 "friend re-decl should not already have a DLLAttr");
6648 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6649 NewAttr->setInherited(true);
6650 FD->addAttr(A: NewAttr);
6651 }
6652 }
6653 }
6654 }
6655
6656 if (ClassExported)
6657 DelayedDllExportClasses.push_back(Elt: Class);
6658}
6659
6660void Sema::propagateDLLAttrToBaseClassTemplate(
6661 CXXRecordDecl *Class, Attr *ClassAttr,
6662 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6663 if (getDLLAttr(
6664 D: BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6665 // If the base class template has a DLL attribute, don't try to change it.
6666 return;
6667 }
6668
6669 auto TSK = BaseTemplateSpec->getSpecializationKind();
6670 if (!getDLLAttr(D: BaseTemplateSpec) &&
6671 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6672 TSK == TSK_ImplicitInstantiation)) {
6673 // The template hasn't been instantiated yet (or it has, but only as an
6674 // explicit instantiation declaration or implicit instantiation, which means
6675 // we haven't codegenned any members yet), so propagate the attribute.
6676 auto *NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6677 NewAttr->setInherited(true);
6678 BaseTemplateSpec->addAttr(A: NewAttr);
6679
6680 // If this was an import, mark that we propagated it from a derived class to
6681 // a base class template specialization.
6682 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(Val: NewAttr))
6683 ImportAttr->setPropagatedToBaseTemplate();
6684
6685 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6686 // needs to be run again to work see the new attribute. Otherwise this will
6687 // get run whenever the template is instantiated.
6688 if (TSK != TSK_Undeclared)
6689 checkClassLevelDLLAttribute(Class: BaseTemplateSpec);
6690
6691 return;
6692 }
6693
6694 if (getDLLAttr(D: BaseTemplateSpec)) {
6695 // The template has already been specialized or instantiated with an
6696 // attribute, explicitly or through propagation. We should not try to change
6697 // it.
6698 return;
6699 }
6700
6701 // The template was previously instantiated or explicitly specialized without
6702 // a dll attribute, It's too late for us to add an attribute, so warn that
6703 // this is unsupported.
6704 Diag(Loc: BaseLoc, DiagID: diag::warn_attribute_dll_instantiated_base_class)
6705 << BaseTemplateSpec->isExplicitSpecialization();
6706 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_attribute);
6707 if (BaseTemplateSpec->isExplicitSpecialization()) {
6708 Diag(Loc: BaseTemplateSpec->getLocation(),
6709 DiagID: diag::note_template_class_explicit_specialization_was_here)
6710 << BaseTemplateSpec;
6711 } else {
6712 Diag(Loc: BaseTemplateSpec->getPointOfInstantiation(),
6713 DiagID: diag::note_template_class_instantiation_was_here)
6714 << BaseTemplateSpec;
6715 }
6716}
6717
6718Sema::DefaultedFunctionKind
6719Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6720 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
6721 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
6722 if (Ctor->isDefaultConstructor())
6723 return CXXSpecialMemberKind::DefaultConstructor;
6724
6725 if (Ctor->isCopyConstructor())
6726 return CXXSpecialMemberKind::CopyConstructor;
6727
6728 if (Ctor->isMoveConstructor())
6729 return CXXSpecialMemberKind::MoveConstructor;
6730 }
6731
6732 if (MD->isCopyAssignmentOperator())
6733 return CXXSpecialMemberKind::CopyAssignment;
6734
6735 if (MD->isMoveAssignmentOperator())
6736 return CXXSpecialMemberKind::MoveAssignment;
6737
6738 if (isa<CXXDestructorDecl>(Val: FD))
6739 return CXXSpecialMemberKind::Destructor;
6740 }
6741
6742 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6743 case OO_EqualEqual:
6744 return DefaultedComparisonKind::Equal;
6745
6746 case OO_ExclaimEqual:
6747 return DefaultedComparisonKind::NotEqual;
6748
6749 case OO_Spaceship:
6750 // No point allowing this if <=> doesn't exist in the current language mode.
6751 if (!getLangOpts().CPlusPlus20)
6752 break;
6753 return DefaultedComparisonKind::ThreeWay;
6754
6755 case OO_Less:
6756 case OO_LessEqual:
6757 case OO_Greater:
6758 case OO_GreaterEqual:
6759 // No point allowing this if <=> doesn't exist in the current language mode.
6760 if (!getLangOpts().CPlusPlus20)
6761 break;
6762 return DefaultedComparisonKind::Relational;
6763
6764 default:
6765 break;
6766 }
6767
6768 // Not defaultable.
6769 return DefaultedFunctionKind();
6770}
6771
6772static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6773 SourceLocation DefaultLoc) {
6774 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6775 if (DFK.isComparison())
6776 return S.DefineDefaultedComparison(Loc: DefaultLoc, FD, DCK: DFK.asComparison());
6777
6778 switch (DFK.asSpecialMember()) {
6779 case CXXSpecialMemberKind::DefaultConstructor:
6780 S.DefineImplicitDefaultConstructor(CurrentLocation: DefaultLoc,
6781 Constructor: cast<CXXConstructorDecl>(Val: FD));
6782 break;
6783 case CXXSpecialMemberKind::CopyConstructor:
6784 S.DefineImplicitCopyConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6785 break;
6786 case CXXSpecialMemberKind::CopyAssignment:
6787 S.DefineImplicitCopyAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6788 break;
6789 case CXXSpecialMemberKind::Destructor:
6790 S.DefineImplicitDestructor(CurrentLocation: DefaultLoc, Destructor: cast<CXXDestructorDecl>(Val: FD));
6791 break;
6792 case CXXSpecialMemberKind::MoveConstructor:
6793 S.DefineImplicitMoveConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6794 break;
6795 case CXXSpecialMemberKind::MoveAssignment:
6796 S.DefineImplicitMoveAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6797 break;
6798 case CXXSpecialMemberKind::Invalid:
6799 llvm_unreachable("Invalid special member.");
6800 }
6801}
6802
6803/// Determine whether a type is permitted to be passed or returned in
6804/// registers, per C++ [class.temporary]p3.
6805static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6806 TargetInfo::CallingConvKind CCK) {
6807 if (D->isDependentType() || D->isInvalidDecl())
6808 return false;
6809
6810 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6811 // The PS4 platform ABI follows the behavior of Clang 3.2.
6812 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6813 return !D->hasNonTrivialDestructorForCall() &&
6814 !D->hasNonTrivialCopyConstructorForCall();
6815
6816 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6817 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6818 bool DtorIsTrivialForCall = false;
6819
6820 // If a class has at least one eligible, trivial copy constructor, it
6821 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6822 //
6823 // Note: This permits classes with non-trivial copy or move ctors to be
6824 // passed in registers, so long as they *also* have a trivial copy ctor,
6825 // which is non-conforming.
6826 if (D->needsImplicitCopyConstructor()) {
6827 if (!D->defaultedCopyConstructorIsDeleted()) {
6828 if (D->hasTrivialCopyConstructor())
6829 CopyCtorIsTrivial = true;
6830 if (D->hasTrivialCopyConstructorForCall())
6831 CopyCtorIsTrivialForCall = true;
6832 }
6833 } else {
6834 for (const CXXConstructorDecl *CD : D->ctors()) {
6835 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6836 !CD->isIneligibleOrNotSelected()) {
6837 if (CD->isTrivial())
6838 CopyCtorIsTrivial = true;
6839 if (CD->isTrivialForCall())
6840 CopyCtorIsTrivialForCall = true;
6841 }
6842 }
6843 }
6844
6845 if (D->needsImplicitDestructor()) {
6846 if (!D->defaultedDestructorIsDeleted() &&
6847 D->hasTrivialDestructorForCall())
6848 DtorIsTrivialForCall = true;
6849 } else if (const auto *DD = D->getDestructor()) {
6850 if (!DD->isDeleted() && DD->isTrivialForCall())
6851 DtorIsTrivialForCall = true;
6852 }
6853
6854 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6855 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6856 return true;
6857
6858 // If a class has a destructor, we'd really like to pass it indirectly
6859 // because it allows us to elide copies. Unfortunately, MSVC makes that
6860 // impossible for small types, which it will pass in a single register or
6861 // stack slot. Most objects with dtors are large-ish, so handle that early.
6862 // We can't call out all large objects as being indirect because there are
6863 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6864 // how we pass large POD types.
6865
6866 // Note: This permits small classes with nontrivial destructors to be
6867 // passed in registers, which is non-conforming.
6868 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6869 uint64_t TypeSize = isAArch64 ? 128 : 64;
6870
6871 if (CopyCtorIsTrivial &&
6872 S.getASTContext().getTypeSize(T: D->getTypeForDecl()) <= TypeSize)
6873 return true;
6874 return false;
6875 }
6876
6877 // Per C++ [class.temporary]p3, the relevant condition is:
6878 // each copy constructor, move constructor, and destructor of X is
6879 // either trivial or deleted, and X has at least one non-deleted copy
6880 // or move constructor
6881 bool HasNonDeletedCopyOrMove = false;
6882
6883 if (D->needsImplicitCopyConstructor() &&
6884 !D->defaultedCopyConstructorIsDeleted()) {
6885 if (!D->hasTrivialCopyConstructorForCall())
6886 return false;
6887 HasNonDeletedCopyOrMove = true;
6888 }
6889
6890 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6891 !D->defaultedMoveConstructorIsDeleted()) {
6892 if (!D->hasTrivialMoveConstructorForCall())
6893 return false;
6894 HasNonDeletedCopyOrMove = true;
6895 }
6896
6897 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6898 !D->hasTrivialDestructorForCall())
6899 return false;
6900
6901 for (const CXXMethodDecl *MD : D->methods()) {
6902 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6903 continue;
6904
6905 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6906 if (CD && CD->isCopyOrMoveConstructor())
6907 HasNonDeletedCopyOrMove = true;
6908 else if (!isa<CXXDestructorDecl>(Val: MD))
6909 continue;
6910
6911 if (!MD->isTrivialForCall())
6912 return false;
6913 }
6914
6915 return HasNonDeletedCopyOrMove;
6916}
6917
6918/// Report an error regarding overriding, along with any relevant
6919/// overridden methods.
6920///
6921/// \param DiagID the primary error to report.
6922/// \param MD the overriding method.
6923static bool
6924ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6925 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6926 bool IssuedDiagnostic = false;
6927 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6928 if (Report(O)) {
6929 if (!IssuedDiagnostic) {
6930 S.Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
6931 IssuedDiagnostic = true;
6932 }
6933 S.Diag(Loc: O->getLocation(), DiagID: diag::note_overridden_virtual_function);
6934 }
6935 }
6936 return IssuedDiagnostic;
6937}
6938
6939void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6940 if (!Record)
6941 return;
6942
6943 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6944 AbstractUsageInfo Info(*this, Record);
6945 CheckAbstractClassUsage(Info, RD: Record);
6946 }
6947
6948 // If this is not an aggregate type and has no user-declared constructor,
6949 // complain about any non-static data members of reference or const scalar
6950 // type, since they will never get initializers.
6951 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6952 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6953 !Record->isLambda()) {
6954 bool Complained = false;
6955 for (const auto *F : Record->fields()) {
6956 if (F->hasInClassInitializer() || F->isUnnamedBitField())
6957 continue;
6958
6959 if (F->getType()->isReferenceType() ||
6960 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6961 if (!Complained) {
6962 Diag(Loc: Record->getLocation(), DiagID: diag::warn_no_constructor_for_refconst)
6963 << Record->getTagKind() << Record;
6964 Complained = true;
6965 }
6966
6967 Diag(Loc: F->getLocation(), DiagID: diag::note_refconst_member_not_initialized)
6968 << F->getType()->isReferenceType()
6969 << F->getDeclName();
6970 }
6971 }
6972 }
6973
6974 if (Record->getIdentifier()) {
6975 // C++ [class.mem]p13:
6976 // If T is the name of a class, then each of the following shall have a
6977 // name different from T:
6978 // - every member of every anonymous union that is a member of class T.
6979 //
6980 // C++ [class.mem]p14:
6981 // In addition, if class T has a user-declared constructor (12.1), every
6982 // non-static data member of class T shall have a name different from T.
6983 DeclContext::lookup_result R = Record->lookup(Name: Record->getDeclName());
6984 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6985 ++I) {
6986 NamedDecl *D = (*I)->getUnderlyingDecl();
6987 if (((isa<FieldDecl>(Val: D) || isa<UnresolvedUsingValueDecl>(Val: D)) &&
6988 Record->hasUserDeclaredConstructor()) ||
6989 isa<IndirectFieldDecl>(Val: D)) {
6990 Diag(Loc: (*I)->getLocation(), DiagID: diag::err_member_name_of_class)
6991 << D->getDeclName();
6992 break;
6993 }
6994 }
6995 }
6996
6997 // Warn if the class has virtual methods but non-virtual public destructor.
6998 if (Record->isPolymorphic() && !Record->isDependentType()) {
6999 CXXDestructorDecl *dtor = Record->getDestructor();
7000 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7001 !Record->hasAttr<FinalAttr>())
7002 Diag(Loc: dtor ? dtor->getLocation() : Record->getLocation(),
7003 DiagID: diag::warn_non_virtual_dtor) << Context.getRecordType(Decl: Record);
7004 }
7005
7006 if (Record->isAbstract()) {
7007 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7008 Diag(Loc: Record->getLocation(), DiagID: diag::warn_abstract_final_class)
7009 << FA->isSpelledAsSealed();
7010 DiagnoseAbstractType(RD: Record);
7011 }
7012 }
7013
7014 // Warn if the class has a final destructor but is not itself marked final.
7015 if (!Record->hasAttr<FinalAttr>()) {
7016 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7017 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7018 Diag(Loc: FA->getLocation(), DiagID: diag::warn_final_dtor_non_final_class)
7019 << FA->isSpelledAsSealed()
7020 << FixItHint::CreateInsertion(
7021 InsertionLoc: getLocForEndOfToken(Loc: Record->getLocation()),
7022 Code: (FA->isSpelledAsSealed() ? " sealed" : " final"));
7023 Diag(Loc: Record->getLocation(),
7024 DiagID: diag::note_final_dtor_non_final_class_silence)
7025 << Context.getRecordType(Decl: Record) << FA->isSpelledAsSealed();
7026 }
7027 }
7028 }
7029
7030 // See if trivial_abi has to be dropped.
7031 if (Record->hasAttr<TrivialABIAttr>())
7032 checkIllFormedTrivialABIStruct(RD&: *Record);
7033
7034 // Set HasTrivialSpecialMemberForCall if the record has attribute
7035 // "trivial_abi".
7036 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7037
7038 if (HasTrivialABI)
7039 Record->setHasTrivialSpecialMemberForCall();
7040
7041 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7042 // We check these last because they can depend on the properties of the
7043 // primary comparison functions (==, <=>).
7044 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7045
7046 // Perform checks that can't be done until we know all the properties of a
7047 // member function (whether it's defaulted, deleted, virtual, overriding,
7048 // ...).
7049 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7050 // A static function cannot override anything.
7051 if (MD->getStorageClass() == SC_Static) {
7052 if (ReportOverrides(S&: *this, DiagID: diag::err_static_overrides_virtual, MD,
7053 Report: [](const CXXMethodDecl *) { return true; }))
7054 return;
7055 }
7056
7057 // A deleted function cannot override a non-deleted function and vice
7058 // versa.
7059 if (ReportOverrides(S&: *this,
7060 DiagID: MD->isDeleted() ? diag::err_deleted_override
7061 : diag::err_non_deleted_override,
7062 MD, Report: [&](const CXXMethodDecl *V) {
7063 return MD->isDeleted() != V->isDeleted();
7064 })) {
7065 if (MD->isDefaulted() && MD->isDeleted())
7066 // Explain why this defaulted function was deleted.
7067 DiagnoseDeletedDefaultedFunction(FD: MD);
7068 return;
7069 }
7070
7071 // A consteval function cannot override a non-consteval function and vice
7072 // versa.
7073 if (ReportOverrides(S&: *this,
7074 DiagID: MD->isConsteval() ? diag::err_consteval_override
7075 : diag::err_non_consteval_override,
7076 MD, Report: [&](const CXXMethodDecl *V) {
7077 return MD->isConsteval() != V->isConsteval();
7078 })) {
7079 if (MD->isDefaulted() && MD->isDeleted())
7080 // Explain why this defaulted function was deleted.
7081 DiagnoseDeletedDefaultedFunction(FD: MD);
7082 return;
7083 }
7084 };
7085
7086 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7087 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7088 return false;
7089
7090 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7091 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7092 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7093 DefaultedSecondaryComparisons.push_back(Elt: FD);
7094 return true;
7095 }
7096
7097 CheckExplicitlyDefaultedFunction(S, MD: FD);
7098 return false;
7099 };
7100
7101 if (!Record->isInvalidDecl() &&
7102 Record->hasAttr<VTablePointerAuthenticationAttr>())
7103 checkIncorrectVTablePointerAuthenticationAttribute(RD&: *Record);
7104
7105 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7106 // Check whether the explicitly-defaulted members are valid.
7107 bool Incomplete = CheckForDefaultedFunction(M);
7108
7109 // Skip the rest of the checks for a member of a dependent class.
7110 if (Record->isDependentType())
7111 return;
7112
7113 // For an explicitly defaulted or deleted special member, we defer
7114 // determining triviality until the class is complete. That time is now!
7115 CXXSpecialMemberKind CSM = getSpecialMember(MD: M);
7116 if (!M->isImplicit() && !M->isUserProvided()) {
7117 if (CSM != CXXSpecialMemberKind::Invalid) {
7118 M->setTrivial(SpecialMemberIsTrivial(MD: M, CSM));
7119 // Inform the class that we've finished declaring this member.
7120 Record->finishedDefaultedOrDeletedMember(MD: M);
7121 M->setTrivialForCall(
7122 HasTrivialABI ||
7123 SpecialMemberIsTrivial(MD: M, CSM,
7124 TAH: TrivialABIHandling::ConsiderTrivialABI));
7125 Record->setTrivialForCallFlags(M);
7126 }
7127 }
7128
7129 // Set triviality for the purpose of calls if this is a user-provided
7130 // copy/move constructor or destructor.
7131 if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7132 CSM == CXXSpecialMemberKind::MoveConstructor ||
7133 CSM == CXXSpecialMemberKind::Destructor) &&
7134 M->isUserProvided()) {
7135 M->setTrivialForCall(HasTrivialABI);
7136 Record->setTrivialForCallFlags(M);
7137 }
7138
7139 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7140 M->hasAttr<DLLExportAttr>()) {
7141 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
7142 M->isTrivial() &&
7143 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7144 CSM == CXXSpecialMemberKind::CopyConstructor ||
7145 CSM == CXXSpecialMemberKind::Destructor))
7146 M->dropAttr<DLLExportAttr>();
7147
7148 if (M->hasAttr<DLLExportAttr>()) {
7149 // Define after any fields with in-class initializers have been parsed.
7150 DelayedDllExportMemberFunctions.push_back(Elt: M);
7151 }
7152 }
7153
7154 bool EffectivelyConstexprDestructor = true;
7155 // Avoid triggering vtable instantiation due to a dtor that is not
7156 // "effectively constexpr" for better compatibility.
7157 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7158 if (isa<CXXDestructorDecl>(Val: M)) {
7159 llvm::SmallDenseSet<QualType> Visited;
7160 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7161 if (!Visited.insert(V: T->getCanonicalTypeUnqualified()).second)
7162 return false;
7163 const CXXRecordDecl *RD =
7164 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7165 if (!RD || !RD->isCompleteDefinition())
7166 return true;
7167
7168 if (!RD->hasConstexprDestructor())
7169 return false;
7170
7171 for (const CXXBaseSpecifier &B : RD->bases())
7172 if (!Check(B.getType(), Check))
7173 return false;
7174 for (const FieldDecl *FD : RD->fields())
7175 if (!Check(FD->getType(), Check))
7176 return false;
7177 return true;
7178 };
7179 EffectivelyConstexprDestructor =
7180 Check(QualType(Record->getTypeForDecl(), 0), Check);
7181 }
7182
7183 // Define defaulted constexpr virtual functions that override a base class
7184 // function right away.
7185 // FIXME: We can defer doing this until the vtable is marked as used.
7186 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7187 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7188 EffectivelyConstexprDestructor)
7189 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
7190
7191 if (!Incomplete)
7192 CheckCompletedMemberFunction(M);
7193 };
7194
7195 // Check the destructor before any other member function. We need to
7196 // determine whether it's trivial in order to determine whether the claas
7197 // type is a literal type, which is a prerequisite for determining whether
7198 // other special member functions are valid and whether they're implicitly
7199 // 'constexpr'.
7200 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7201 CompleteMemberFunction(Dtor);
7202
7203 bool HasMethodWithOverrideControl = false,
7204 HasOverridingMethodWithoutOverrideControl = false;
7205 for (auto *D : Record->decls()) {
7206 if (auto *M = dyn_cast<CXXMethodDecl>(Val: D)) {
7207 // FIXME: We could do this check for dependent types with non-dependent
7208 // bases.
7209 if (!Record->isDependentType()) {
7210 // See if a method overloads virtual methods in a base
7211 // class without overriding any.
7212 if (!M->isStatic())
7213 DiagnoseHiddenVirtualMethods(MD: M);
7214
7215 if (M->hasAttr<OverrideAttr>()) {
7216 HasMethodWithOverrideControl = true;
7217 } else if (M->size_overridden_methods() > 0) {
7218 HasOverridingMethodWithoutOverrideControl = true;
7219 } else {
7220 // Warn on newly-declared virtual methods in `final` classes
7221 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7222 Diag(Loc: M->getLocation(), DiagID: diag::warn_unnecessary_virtual_specifier)
7223 << M;
7224 }
7225 }
7226 }
7227
7228 if (!isa<CXXDestructorDecl>(Val: M))
7229 CompleteMemberFunction(M);
7230 } else if (auto *F = dyn_cast<FriendDecl>(Val: D)) {
7231 CheckForDefaultedFunction(
7232 dyn_cast_or_null<FunctionDecl>(Val: F->getFriendDecl()));
7233 }
7234 }
7235
7236 if (HasOverridingMethodWithoutOverrideControl) {
7237 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7238 for (auto *M : Record->methods())
7239 DiagnoseAbsenceOfOverrideControl(D: M, Inconsistent: HasInconsistentOverrideControl);
7240 }
7241
7242 // Check the defaulted secondary comparisons after any other member functions.
7243 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7244 CheckExplicitlyDefaultedFunction(S, MD: FD);
7245
7246 // If this is a member function, we deferred checking it until now.
7247 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
7248 CheckCompletedMemberFunction(MD);
7249 }
7250
7251 // ms_struct is a request to use the same ABI rules as MSVC. Check
7252 // whether this class uses any C++ features that are implemented
7253 // completely differently in MSVC, and if so, emit a diagnostic.
7254 // That diagnostic defaults to an error, but we allow projects to
7255 // map it down to a warning (or ignore it). It's a fairly common
7256 // practice among users of the ms_struct pragma to mass-annotate
7257 // headers, sweeping up a bunch of types that the project doesn't
7258 // really rely on MSVC-compatible layout for. We must therefore
7259 // support "ms_struct except for C++ stuff" as a secondary ABI.
7260 // Don't emit this diagnostic if the feature was enabled as a
7261 // language option (as opposed to via a pragma or attribute), as
7262 // the option -mms-bitfields otherwise essentially makes it impossible
7263 // to build C++ code, unless this diagnostic is turned off.
7264 if (Record->isMsStruct(C: Context) && !Context.getLangOpts().MSBitfields &&
7265 (Record->isPolymorphic() || Record->getNumBases())) {
7266 Diag(Loc: Record->getLocation(), DiagID: diag::warn_cxx_ms_struct);
7267 }
7268
7269 checkClassLevelDLLAttribute(Class: Record);
7270 checkClassLevelCodeSegAttribute(Class: Record);
7271
7272 bool ClangABICompat4 =
7273 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7274 TargetInfo::CallingConvKind CCK =
7275 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7276 bool CanPass = canPassInRegisters(S&: *this, D: Record, CCK);
7277
7278 // Do not change ArgPassingRestrictions if it has already been set to
7279 // RecordArgPassingKind::CanNeverPassInRegs.
7280 if (Record->getArgPassingRestrictions() !=
7281 RecordArgPassingKind::CanNeverPassInRegs)
7282 Record->setArgPassingRestrictions(
7283 CanPass ? RecordArgPassingKind::CanPassInRegs
7284 : RecordArgPassingKind::CannotPassInRegs);
7285
7286 // If canPassInRegisters returns true despite the record having a non-trivial
7287 // destructor, the record is destructed in the callee. This happens only when
7288 // the record or one of its subobjects has a field annotated with trivial_abi
7289 // or a field qualified with ObjC __strong/__weak.
7290 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7291 Record->setParamDestroyedInCallee(true);
7292 else if (Record->hasNonTrivialDestructor())
7293 Record->setParamDestroyedInCallee(CanPass);
7294
7295 if (getLangOpts().ForceEmitVTables) {
7296 // If we want to emit all the vtables, we need to mark it as used. This
7297 // is especially required for cases like vtable assumption loads.
7298 MarkVTableUsed(Loc: Record->getInnerLocStart(), Class: Record);
7299 }
7300
7301 if (getLangOpts().CUDA) {
7302 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7303 checkCUDADeviceBuiltinSurfaceClassTemplate(S&: *this, Class: Record);
7304 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7305 checkCUDADeviceBuiltinTextureClassTemplate(S&: *this, Class: Record);
7306 }
7307
7308 llvm::SmallDenseMap<OverloadedOperatorKind,
7309 llvm::SmallVector<const FunctionDecl *, 2>, 4>
7310 TypeAwareDecls{{OO_New, {}},
7311 {OO_Array_New, {}},
7312 {OO_Delete, {}},
7313 {OO_Array_New, {}}};
7314 for (auto *D : Record->decls()) {
7315 const FunctionDecl *FnDecl = D->getAsFunction();
7316 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7317 continue;
7318 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7319 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(Elt: FnDecl);
7320 }
7321 auto CheckMismatchedTypeAwareAllocators =
7322 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7323 OverloadedOperatorKind DeleteKind) {
7324 auto &NewDecls = TypeAwareDecls[NewKind];
7325 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7326 if (NewDecls.empty() == DeleteDecls.empty())
7327 return;
7328 DeclarationName FoundOperator =
7329 Context.DeclarationNames.getCXXOperatorName(
7330 Op: NewDecls.empty() ? DeleteKind : NewKind);
7331 DeclarationName MissingOperator =
7332 Context.DeclarationNames.getCXXOperatorName(
7333 Op: NewDecls.empty() ? NewKind : DeleteKind);
7334 Diag(Loc: Record->getLocation(),
7335 DiagID: diag::err_type_aware_allocator_missing_matching_operator)
7336 << FoundOperator << Context.getRecordType(Decl: Record)
7337 << MissingOperator;
7338 for (auto MD : NewDecls)
7339 Diag(Loc: MD->getLocation(),
7340 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7341 << MD;
7342 for (auto MD : DeleteDecls)
7343 Diag(Loc: MD->getLocation(),
7344 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7345 << MD;
7346 };
7347 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7348 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7349}
7350
7351/// Look up the special member function that would be called by a special
7352/// member function for a subobject of class type.
7353///
7354/// \param Class The class type of the subobject.
7355/// \param CSM The kind of special member function.
7356/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7357/// \param ConstRHS True if this is a copy operation with a const object
7358/// on its RHS, that is, if the argument to the outer special member
7359/// function is 'const' and this is not a field marked 'mutable'.
7360static Sema::SpecialMemberOverloadResult
7361lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7362 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7363 bool ConstRHS) {
7364 unsigned LHSQuals = 0;
7365 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7366 CSM == CXXSpecialMemberKind::MoveAssignment)
7367 LHSQuals = FieldQuals;
7368
7369 unsigned RHSQuals = FieldQuals;
7370 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7371 CSM == CXXSpecialMemberKind::Destructor)
7372 RHSQuals = 0;
7373 else if (ConstRHS)
7374 RHSQuals |= Qualifiers::Const;
7375
7376 return S.LookupSpecialMember(D: Class, SM: CSM,
7377 ConstArg: RHSQuals & Qualifiers::Const,
7378 VolatileArg: RHSQuals & Qualifiers::Volatile,
7379 RValueThis: false,
7380 ConstThis: LHSQuals & Qualifiers::Const,
7381 VolatileThis: LHSQuals & Qualifiers::Volatile);
7382}
7383
7384class Sema::InheritedConstructorInfo {
7385 Sema &S;
7386 SourceLocation UseLoc;
7387
7388 /// A mapping from the base classes through which the constructor was
7389 /// inherited to the using shadow declaration in that base class (or a null
7390 /// pointer if the constructor was declared in that base class).
7391 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7392 InheritedFromBases;
7393
7394public:
7395 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7396 ConstructorUsingShadowDecl *Shadow)
7397 : S(S), UseLoc(UseLoc) {
7398 bool DiagnosedMultipleConstructedBases = false;
7399 CXXRecordDecl *ConstructedBase = nullptr;
7400 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7401
7402 // Find the set of such base class subobjects and check that there's a
7403 // unique constructed subobject.
7404 for (auto *D : Shadow->redecls()) {
7405 auto *DShadow = cast<ConstructorUsingShadowDecl>(Val: D);
7406 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7407 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7408
7409 InheritedFromBases.insert(
7410 KV: std::make_pair(x: DNominatedBase->getCanonicalDecl(),
7411 y: DShadow->getNominatedBaseClassShadowDecl()));
7412 if (DShadow->constructsVirtualBase())
7413 InheritedFromBases.insert(
7414 KV: std::make_pair(x: DConstructedBase->getCanonicalDecl(),
7415 y: DShadow->getConstructedBaseClassShadowDecl()));
7416 else
7417 assert(DNominatedBase == DConstructedBase);
7418
7419 // [class.inhctor.init]p2:
7420 // If the constructor was inherited from multiple base class subobjects
7421 // of type B, the program is ill-formed.
7422 if (!ConstructedBase) {
7423 ConstructedBase = DConstructedBase;
7424 ConstructedBaseIntroducer = D->getIntroducer();
7425 } else if (ConstructedBase != DConstructedBase &&
7426 !Shadow->isInvalidDecl()) {
7427 if (!DiagnosedMultipleConstructedBases) {
7428 S.Diag(Loc: UseLoc, DiagID: diag::err_ambiguous_inherited_constructor)
7429 << Shadow->getTargetDecl();
7430 S.Diag(Loc: ConstructedBaseIntroducer->getLocation(),
7431 DiagID: diag::note_ambiguous_inherited_constructor_using)
7432 << ConstructedBase;
7433 DiagnosedMultipleConstructedBases = true;
7434 }
7435 S.Diag(Loc: D->getIntroducer()->getLocation(),
7436 DiagID: diag::note_ambiguous_inherited_constructor_using)
7437 << DConstructedBase;
7438 }
7439 }
7440
7441 if (DiagnosedMultipleConstructedBases)
7442 Shadow->setInvalidDecl();
7443 }
7444
7445 /// Find the constructor to use for inherited construction of a base class,
7446 /// and whether that base class constructor inherits the constructor from a
7447 /// virtual base class (in which case it won't actually invoke it).
7448 std::pair<CXXConstructorDecl *, bool>
7449 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7450 auto It = InheritedFromBases.find(Val: Base->getCanonicalDecl());
7451 if (It == InheritedFromBases.end())
7452 return std::make_pair(x: nullptr, y: false);
7453
7454 // This is an intermediary class.
7455 if (It->second)
7456 return std::make_pair(
7457 x: S.findInheritingConstructor(Loc: UseLoc, BaseCtor: Ctor, DerivedShadow: It->second),
7458 y: It->second->constructsVirtualBase());
7459
7460 // This is the base class from which the constructor was inherited.
7461 return std::make_pair(x&: Ctor, y: false);
7462 }
7463};
7464
7465/// Is the special member function which would be selected to perform the
7466/// specified operation on the specified class type a constexpr constructor?
7467static bool specialMemberIsConstexpr(
7468 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7469 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7470 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7471 // Suppress duplicate constraint checking here, in case a constraint check
7472 // caused us to decide to do this. Any truely recursive checks will get
7473 // caught during these checks anyway.
7474 Sema::SatisfactionStackResetRAII SSRAII{S};
7475
7476 // If we're inheriting a constructor, see if we need to call it for this base
7477 // class.
7478 if (InheritedCtor) {
7479 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7480 auto BaseCtor =
7481 Inherited->findConstructorForBase(Base: ClassDecl, Ctor: InheritedCtor).first;
7482 if (BaseCtor)
7483 return BaseCtor->isConstexpr();
7484 }
7485
7486 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7487 return ClassDecl->hasConstexprDefaultConstructor();
7488 if (CSM == CXXSpecialMemberKind::Destructor)
7489 return ClassDecl->hasConstexprDestructor();
7490
7491 Sema::SpecialMemberOverloadResult SMOR =
7492 lookupCallFromSpecialMember(S, Class: ClassDecl, CSM, FieldQuals: Quals, ConstRHS);
7493 if (!SMOR.getMethod())
7494 // A constructor we wouldn't select can't be "involved in initializing"
7495 // anything.
7496 return true;
7497 return SMOR.getMethod()->isConstexpr();
7498}
7499
7500/// Determine whether the specified special member function would be constexpr
7501/// if it were implicitly defined.
7502static bool defaultedSpecialMemberIsConstexpr(
7503 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7504 CXXConstructorDecl *InheritedCtor = nullptr,
7505 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7506 if (!S.getLangOpts().CPlusPlus11)
7507 return false;
7508
7509 // C++11 [dcl.constexpr]p4:
7510 // In the definition of a constexpr constructor [...]
7511 bool Ctor = true;
7512 switch (CSM) {
7513 case CXXSpecialMemberKind::DefaultConstructor:
7514 if (Inherited)
7515 break;
7516 // Since default constructor lookup is essentially trivial (and cannot
7517 // involve, for instance, template instantiation), we compute whether a
7518 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7519 //
7520 // This is important for performance; we need to know whether the default
7521 // constructor is constexpr to determine whether the type is a literal type.
7522 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7523
7524 case CXXSpecialMemberKind::CopyConstructor:
7525 case CXXSpecialMemberKind::MoveConstructor:
7526 // For copy or move constructors, we need to perform overload resolution.
7527 break;
7528
7529 case CXXSpecialMemberKind::CopyAssignment:
7530 case CXXSpecialMemberKind::MoveAssignment:
7531 if (!S.getLangOpts().CPlusPlus14)
7532 return false;
7533 // In C++1y, we need to perform overload resolution.
7534 Ctor = false;
7535 break;
7536
7537 case CXXSpecialMemberKind::Destructor:
7538 return ClassDecl->defaultedDestructorIsConstexpr();
7539
7540 case CXXSpecialMemberKind::Invalid:
7541 return false;
7542 }
7543
7544 // -- if the class is a non-empty union, or for each non-empty anonymous
7545 // union member of a non-union class, exactly one non-static data member
7546 // shall be initialized; [DR1359]
7547 //
7548 // If we squint, this is guaranteed, since exactly one non-static data member
7549 // will be initialized (if the constructor isn't deleted), we just don't know
7550 // which one.
7551 if (Ctor && ClassDecl->isUnion())
7552 return CSM == CXXSpecialMemberKind::DefaultConstructor
7553 ? ClassDecl->hasInClassInitializer() ||
7554 !ClassDecl->hasVariantMembers()
7555 : true;
7556
7557 // -- the class shall not have any virtual base classes;
7558 if (Ctor && ClassDecl->getNumVBases())
7559 return false;
7560
7561 // C++1y [class.copy]p26:
7562 // -- [the class] is a literal type, and
7563 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7564 return false;
7565
7566 // -- every constructor involved in initializing [...] base class
7567 // sub-objects shall be a constexpr constructor;
7568 // -- the assignment operator selected to copy/move each direct base
7569 // class is a constexpr function, and
7570 if (!S.getLangOpts().CPlusPlus23) {
7571 for (const auto &B : ClassDecl->bases()) {
7572 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7573 if (!BaseType)
7574 continue;
7575 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(Val: BaseType->getDecl());
7576 if (!specialMemberIsConstexpr(S, ClassDecl: BaseClassDecl, CSM, Quals: 0, ConstRHS: ConstArg,
7577 InheritedCtor, Inherited))
7578 return false;
7579 }
7580 }
7581
7582 // -- every constructor involved in initializing non-static data members
7583 // [...] shall be a constexpr constructor;
7584 // -- every non-static data member and base class sub-object shall be
7585 // initialized
7586 // -- for each non-static data member of X that is of class type (or array
7587 // thereof), the assignment operator selected to copy/move that member is
7588 // a constexpr function
7589 if (!S.getLangOpts().CPlusPlus23) {
7590 for (const auto *F : ClassDecl->fields()) {
7591 if (F->isInvalidDecl())
7592 continue;
7593 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7594 F->hasInClassInitializer())
7595 continue;
7596 QualType BaseType = S.Context.getBaseElementType(QT: F->getType());
7597 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7598 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(Val: RecordTy->getDecl());
7599 if (!specialMemberIsConstexpr(S, ClassDecl: FieldRecDecl, CSM,
7600 Quals: BaseType.getCVRQualifiers(),
7601 ConstRHS: ConstArg && !F->isMutable()))
7602 return false;
7603 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7604 return false;
7605 }
7606 }
7607 }
7608
7609 // All OK, it's constexpr!
7610 return true;
7611}
7612
7613namespace {
7614/// RAII object to register a defaulted function as having its exception
7615/// specification computed.
7616struct ComputingExceptionSpec {
7617 Sema &S;
7618
7619 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7620 : S(S) {
7621 Sema::CodeSynthesisContext Ctx;
7622 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7623 Ctx.PointOfInstantiation = Loc;
7624 Ctx.Entity = FD;
7625 S.pushCodeSynthesisContext(Ctx);
7626 }
7627 ~ComputingExceptionSpec() {
7628 S.popCodeSynthesisContext();
7629 }
7630};
7631}
7632
7633static Sema::ImplicitExceptionSpecification
7634ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7635 CXXMethodDecl *MD,
7636 CXXSpecialMemberKind CSM,
7637 Sema::InheritedConstructorInfo *ICI);
7638
7639static Sema::ImplicitExceptionSpecification
7640ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7641 FunctionDecl *FD,
7642 Sema::DefaultedComparisonKind DCK);
7643
7644static Sema::ImplicitExceptionSpecification
7645computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7646 auto DFK = S.getDefaultedFunctionKind(FD);
7647 if (DFK.isSpecialMember())
7648 return ComputeDefaultedSpecialMemberExceptionSpec(
7649 S, Loc, MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), ICI: nullptr);
7650 if (DFK.isComparison())
7651 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7652 DCK: DFK.asComparison());
7653
7654 auto *CD = cast<CXXConstructorDecl>(Val: FD);
7655 assert(CD->getInheritedConstructor() &&
7656 "only defaulted functions and inherited constructors have implicit "
7657 "exception specs");
7658 Sema::InheritedConstructorInfo ICI(
7659 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7660 return ComputeDefaultedSpecialMemberExceptionSpec(
7661 S, Loc, MD: CD, CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI);
7662}
7663
7664static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7665 CXXMethodDecl *MD) {
7666 FunctionProtoType::ExtProtoInfo EPI;
7667
7668 // Build an exception specification pointing back at this member.
7669 EPI.ExceptionSpec.Type = EST_Unevaluated;
7670 EPI.ExceptionSpec.SourceDecl = MD;
7671
7672 // Set the calling convention to the default for C++ instance methods.
7673 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7674 cc: S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7675 /*IsCXXMethod=*/true));
7676 return EPI;
7677}
7678
7679void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7680 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7681 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7682 return;
7683
7684 // Evaluate the exception specification.
7685 auto IES = computeImplicitExceptionSpec(S&: *this, Loc, FD);
7686 auto ESI = IES.getExceptionSpec();
7687
7688 // Update the type of the special member to use it.
7689 UpdateExceptionSpec(FD, ESI);
7690}
7691
7692void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7693 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7694
7695 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7696 if (!DefKind) {
7697 assert(FD->getDeclContext()->isDependentContext());
7698 return;
7699 }
7700
7701 if (DefKind.isComparison()) {
7702 auto PT = FD->getParamDecl(i: 0)->getType();
7703 if (const CXXRecordDecl *RD =
7704 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7705 for (FieldDecl *Field : RD->fields()) {
7706 UnusedPrivateFields.remove(X: Field);
7707 }
7708 }
7709 }
7710
7711 if (DefKind.isSpecialMember()
7712 ? CheckExplicitlyDefaultedSpecialMember(MD: cast<CXXMethodDecl>(Val: FD),
7713 CSM: DefKind.asSpecialMember(),
7714 DefaultLoc: FD->getDefaultLoc())
7715 : CheckExplicitlyDefaultedComparison(S, MD: FD, DCK: DefKind.asComparison()))
7716 FD->setInvalidDecl();
7717}
7718
7719bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7720 CXXSpecialMemberKind CSM,
7721 SourceLocation DefaultLoc) {
7722 CXXRecordDecl *RD = MD->getParent();
7723
7724 assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7725 "not an explicitly-defaulted special member");
7726
7727 // Defer all checking for special members of a dependent type.
7728 if (RD->isDependentType())
7729 return false;
7730
7731 // Whether this was the first-declared instance of the constructor.
7732 // This affects whether we implicitly add an exception spec and constexpr.
7733 bool First = MD == MD->getCanonicalDecl();
7734
7735 bool HadError = false;
7736
7737 // C++11 [dcl.fct.def.default]p1:
7738 // A function that is explicitly defaulted shall
7739 // -- be a special member function [...] (checked elsewhere),
7740 // -- have the same type (except for ref-qualifiers, and except that a
7741 // copy operation can take a non-const reference) as an implicit
7742 // declaration, and
7743 // -- not have default arguments.
7744 // C++2a changes the second bullet to instead delete the function if it's
7745 // defaulted on its first declaration, unless it's "an assignment operator,
7746 // and its return type differs or its parameter type is not a reference".
7747 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7748 bool ShouldDeleteForTypeMismatch = false;
7749 unsigned ExpectedParams = 1;
7750 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7751 CSM == CXXSpecialMemberKind::Destructor)
7752 ExpectedParams = 0;
7753 if (MD->getNumExplicitParams() != ExpectedParams) {
7754 // This checks for default arguments: a copy or move constructor with a
7755 // default argument is classified as a default constructor, and assignment
7756 // operations and destructors can't have default arguments.
7757 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_params)
7758 << CSM << MD->getSourceRange();
7759 HadError = true;
7760 } else if (MD->isVariadic()) {
7761 if (DeleteOnTypeMismatch)
7762 ShouldDeleteForTypeMismatch = true;
7763 else {
7764 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_variadic)
7765 << CSM << MD->getSourceRange();
7766 HadError = true;
7767 }
7768 }
7769
7770 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7771
7772 bool CanHaveConstParam = false;
7773 if (CSM == CXXSpecialMemberKind::CopyConstructor)
7774 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7775 else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7776 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7777
7778 QualType ReturnType = Context.VoidTy;
7779 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7780 CSM == CXXSpecialMemberKind::MoveAssignment) {
7781 // Check for return type matching.
7782 ReturnType = Type->getReturnType();
7783 QualType ThisType = MD->getFunctionObjectParameterType();
7784
7785 QualType DeclType = Context.getTypeDeclType(Decl: RD);
7786 DeclType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
7787 NamedType: DeclType, OwnedTagDecl: nullptr);
7788 DeclType = Context.getAddrSpaceQualType(
7789 T: DeclType, AddressSpace: ThisType.getQualifiers().getAddressSpace());
7790 QualType ExpectedReturnType = Context.getLValueReferenceType(T: DeclType);
7791
7792 if (!Context.hasSameType(T1: ReturnType, T2: ExpectedReturnType)) {
7793 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_return_type)
7794 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7795 << ExpectedReturnType;
7796 HadError = true;
7797 }
7798
7799 // A defaulted special member cannot have cv-qualifiers.
7800 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7801 if (DeleteOnTypeMismatch)
7802 ShouldDeleteForTypeMismatch = true;
7803 else {
7804 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_quals)
7805 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7806 << getLangOpts().CPlusPlus14;
7807 HadError = true;
7808 }
7809 }
7810 // [C++23][dcl.fct.def.default]/p2.2
7811 // if F2 has an implicit object parameter of type “reference to C”,
7812 // F1 may be an explicit object member function whose explicit object
7813 // parameter is of (possibly different) type “reference to C”,
7814 // in which case the type of F1 would differ from the type of F2
7815 // in that the type of F1 has an additional parameter;
7816 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7817 ? MD->getParamDecl(i: 0)->getType()
7818 : QualType();
7819 if (!ExplicitObjectParameter.isNull() &&
7820 (!ExplicitObjectParameter->isReferenceType() ||
7821 !Context.hasSameType(T1: ExplicitObjectParameter.getNonReferenceType(),
7822 T2: Context.getRecordType(Decl: RD)))) {
7823 if (DeleteOnTypeMismatch)
7824 ShouldDeleteForTypeMismatch = true;
7825 else {
7826 Diag(Loc: MD->getLocation(),
7827 DiagID: diag::err_defaulted_special_member_explicit_object_mismatch)
7828 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7829 << MD->getSourceRange();
7830 HadError = true;
7831 }
7832 }
7833 }
7834
7835 // Check for parameter type matching.
7836 QualType ArgType =
7837 ExpectedParams
7838 ? Type->getParamType(i: MD->isExplicitObjectMemberFunction() ? 1 : 0)
7839 : QualType();
7840 bool HasConstParam = false;
7841 if (ExpectedParams && ArgType->isReferenceType()) {
7842 // Argument must be reference to possibly-const T.
7843 QualType ReferentType = ArgType->getPointeeType();
7844 HasConstParam = ReferentType.isConstQualified();
7845
7846 if (ReferentType.isVolatileQualified()) {
7847 if (DeleteOnTypeMismatch)
7848 ShouldDeleteForTypeMismatch = true;
7849 else {
7850 Diag(Loc: MD->getLocation(),
7851 DiagID: diag::err_defaulted_special_member_volatile_param)
7852 << CSM;
7853 HadError = true;
7854 }
7855 }
7856
7857 if (HasConstParam && !CanHaveConstParam) {
7858 if (DeleteOnTypeMismatch)
7859 ShouldDeleteForTypeMismatch = true;
7860 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7861 CSM == CXXSpecialMemberKind::CopyAssignment) {
7862 Diag(Loc: MD->getLocation(),
7863 DiagID: diag::err_defaulted_special_member_copy_const_param)
7864 << (CSM == CXXSpecialMemberKind::CopyAssignment);
7865 // FIXME: Explain why this special member can't be const.
7866 HadError = true;
7867 } else {
7868 Diag(Loc: MD->getLocation(),
7869 DiagID: diag::err_defaulted_special_member_move_const_param)
7870 << (CSM == CXXSpecialMemberKind::MoveAssignment);
7871 HadError = true;
7872 }
7873 }
7874 } else if (ExpectedParams) {
7875 // A copy assignment operator can take its argument by value, but a
7876 // defaulted one cannot.
7877 assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
7878 "unexpected non-ref argument");
7879 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_copy_assign_not_ref);
7880 HadError = true;
7881 }
7882
7883 // C++11 [dcl.fct.def.default]p2:
7884 // An explicitly-defaulted function may be declared constexpr only if it
7885 // would have been implicitly declared as constexpr,
7886 // Do not apply this rule to members of class templates, since core issue 1358
7887 // makes such functions always instantiate to constexpr functions. For
7888 // functions which cannot be constexpr (for non-constructors in C++11 and for
7889 // destructors in C++14 and C++17), this is checked elsewhere.
7890 //
7891 // FIXME: This should not apply if the member is deleted.
7892 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: RD, CSM,
7893 ConstArg: HasConstParam);
7894
7895 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7896 // If the instantiated template specialization of a constexpr function
7897 // template or member function of a class template would fail to satisfy
7898 // the requirements for a constexpr function or constexpr constructor, that
7899 // specialization is still a constexpr function or constexpr constructor,
7900 // even though a call to such a function cannot appear in a constant
7901 // expression.
7902 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7903 Constexpr = true;
7904
7905 if ((getLangOpts().CPlusPlus20 ||
7906 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(Val: MD)
7907 : isa<CXXConstructorDecl>(Val: MD))) &&
7908 MD->isConstexpr() && !Constexpr &&
7909 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7910 if (!MD->isConsteval() && RD->getNumVBases()) {
7911 Diag(Loc: MD->getBeginLoc(),
7912 DiagID: diag::err_incorrect_defaulted_constexpr_with_vb)
7913 << CSM;
7914 for (const auto &I : RD->vbases())
7915 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here);
7916 } else {
7917 Diag(Loc: MD->getBeginLoc(), DiagID: diag::err_incorrect_defaulted_constexpr)
7918 << CSM << MD->isConsteval();
7919 }
7920 HadError = true;
7921 // FIXME: Explain why the special member can't be constexpr.
7922 }
7923
7924 if (First) {
7925 // C++2a [dcl.fct.def.default]p3:
7926 // If a function is explicitly defaulted on its first declaration, it is
7927 // implicitly considered to be constexpr if the implicit declaration
7928 // would be.
7929 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7930 ? ConstexprSpecKind::Consteval
7931 : ConstexprSpecKind::Constexpr)
7932 : ConstexprSpecKind::Unspecified);
7933
7934 if (!Type->hasExceptionSpec()) {
7935 // C++2a [except.spec]p3:
7936 // If a declaration of a function does not have a noexcept-specifier
7937 // [and] is defaulted on its first declaration, [...] the exception
7938 // specification is as specified below
7939 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7940 EPI.ExceptionSpec.Type = EST_Unevaluated;
7941 EPI.ExceptionSpec.SourceDecl = MD;
7942 MD->setType(
7943 Context.getFunctionType(ResultTy: ReturnType, Args: Type->getParamTypes(), EPI));
7944 }
7945 }
7946
7947 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7948 if (First) {
7949 SetDeclDeleted(dcl: MD, DelLoc: MD->getLocation());
7950 if (!inTemplateInstantiation() && !HadError) {
7951 Diag(Loc: MD->getLocation(), DiagID: diag::warn_defaulted_method_deleted) << CSM;
7952 if (ShouldDeleteForTypeMismatch) {
7953 Diag(Loc: MD->getLocation(), DiagID: diag::note_deleted_type_mismatch) << CSM;
7954 } else if (ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr,
7955 /*Diagnose*/ true) &&
7956 DefaultLoc.isValid()) {
7957 Diag(Loc: DefaultLoc, DiagID: diag::note_replace_equals_default_to_delete)
7958 << FixItHint::CreateReplacement(RemoveRange: DefaultLoc, Code: "delete");
7959 }
7960 }
7961 if (ShouldDeleteForTypeMismatch && !HadError) {
7962 Diag(Loc: MD->getLocation(),
7963 DiagID: diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7964 << CSM;
7965 }
7966 } else {
7967 // C++11 [dcl.fct.def.default]p4:
7968 // [For a] user-provided explicitly-defaulted function [...] if such a
7969 // function is implicitly defined as deleted, the program is ill-formed.
7970 Diag(Loc: MD->getLocation(), DiagID: diag::err_out_of_line_default_deletes) << CSM;
7971 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7972 ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, /*Diagnose*/true);
7973 HadError = true;
7974 }
7975 }
7976
7977 return HadError;
7978}
7979
7980namespace {
7981/// Helper class for building and checking a defaulted comparison.
7982///
7983/// Defaulted functions are built in two phases:
7984///
7985/// * First, the set of operations that the function will perform are
7986/// identified, and some of them are checked. If any of the checked
7987/// operations is invalid in certain ways, the comparison function is
7988/// defined as deleted and no body is built.
7989/// * Then, if the function is not defined as deleted, the body is built.
7990///
7991/// This is accomplished by performing two visitation steps over the eventual
7992/// body of the function.
7993template<typename Derived, typename ResultList, typename Result,
7994 typename Subobject>
7995class DefaultedComparisonVisitor {
7996public:
7997 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7998
7999 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8000 DefaultedComparisonKind DCK)
8001 : S(S), RD(RD), FD(FD), DCK(DCK) {
8002 if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
8003 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8004 // UnresolvedSet to avoid this copy.
8005 Fns.assign(I: Info->getUnqualifiedLookups().begin(),
8006 E: Info->getUnqualifiedLookups().end());
8007 }
8008 }
8009
8010 ResultList visit() {
8011 // The type of an lvalue naming a parameter of this function.
8012 QualType ParamLvalType =
8013 FD->getParamDecl(i: 0)->getType().getNonReferenceType();
8014
8015 ResultList Results;
8016
8017 switch (DCK) {
8018 case DefaultedComparisonKind::None:
8019 llvm_unreachable("not a defaulted comparison");
8020
8021 case DefaultedComparisonKind::Equal:
8022 case DefaultedComparisonKind::ThreeWay:
8023 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8024 return Results;
8025
8026 case DefaultedComparisonKind::NotEqual:
8027 case DefaultedComparisonKind::Relational:
8028 Results.add(getDerived().visitExpandedSubobject(
8029 ParamLvalType, getDerived().getCompleteObject()));
8030 return Results;
8031 }
8032 llvm_unreachable("");
8033 }
8034
8035protected:
8036 Derived &getDerived() { return static_cast<Derived&>(*this); }
8037
8038 /// Visit the expanded list of subobjects of the given type, as specified in
8039 /// C++2a [class.compare.default].
8040 ///
8041 /// \return \c true if the ResultList object said we're done, \c false if not.
8042 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8043 Qualifiers Quals) {
8044 // C++2a [class.compare.default]p4:
8045 // The direct base class subobjects of C
8046 for (CXXBaseSpecifier &Base : Record->bases())
8047 if (Results.add(getDerived().visitSubobject(
8048 S.Context.getQualifiedType(T: Base.getType(), Qs: Quals),
8049 getDerived().getBase(&Base))))
8050 return true;
8051
8052 // followed by the non-static data members of C
8053 for (FieldDecl *Field : Record->fields()) {
8054 // C++23 [class.bit]p2:
8055 // Unnamed bit-fields are not members ...
8056 if (Field->isUnnamedBitField())
8057 continue;
8058 // Recursively expand anonymous structs.
8059 if (Field->isAnonymousStructOrUnion()) {
8060 if (visitSubobjects(Results, Record: Field->getType()->getAsCXXRecordDecl(),
8061 Quals))
8062 return true;
8063 continue;
8064 }
8065
8066 // Figure out the type of an lvalue denoting this field.
8067 Qualifiers FieldQuals = Quals;
8068 if (Field->isMutable())
8069 FieldQuals.removeConst();
8070 QualType FieldType =
8071 S.Context.getQualifiedType(T: Field->getType(), Qs: FieldQuals);
8072
8073 if (Results.add(getDerived().visitSubobject(
8074 FieldType, getDerived().getField(Field))))
8075 return true;
8076 }
8077
8078 // form a list of subobjects.
8079 return false;
8080 }
8081
8082 Result visitSubobject(QualType Type, Subobject Subobj) {
8083 // In that list, any subobject of array type is recursively expanded
8084 const ArrayType *AT = S.Context.getAsArrayType(T: Type);
8085 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(Val: AT))
8086 return getDerived().visitSubobjectArray(CAT->getElementType(),
8087 CAT->getSize(), Subobj);
8088 return getDerived().visitExpandedSubobject(Type, Subobj);
8089 }
8090
8091 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8092 Subobject Subobj) {
8093 return getDerived().visitSubobject(Type, Subobj);
8094 }
8095
8096protected:
8097 Sema &S;
8098 CXXRecordDecl *RD;
8099 FunctionDecl *FD;
8100 DefaultedComparisonKind DCK;
8101 UnresolvedSet<16> Fns;
8102};
8103
8104/// Information about a defaulted comparison, as determined by
8105/// DefaultedComparisonAnalyzer.
8106struct DefaultedComparisonInfo {
8107 bool Deleted = false;
8108 bool Constexpr = true;
8109 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8110
8111 static DefaultedComparisonInfo deleted() {
8112 DefaultedComparisonInfo Deleted;
8113 Deleted.Deleted = true;
8114 return Deleted;
8115 }
8116
8117 bool add(const DefaultedComparisonInfo &R) {
8118 Deleted |= R.Deleted;
8119 Constexpr &= R.Constexpr;
8120 Category = commonComparisonType(A: Category, B: R.Category);
8121 return Deleted;
8122 }
8123};
8124
8125/// An element in the expanded list of subobjects of a defaulted comparison, as
8126/// specified in C++2a [class.compare.default]p4.
8127struct DefaultedComparisonSubobject {
8128 enum { CompleteObject, Member, Base } Kind;
8129 NamedDecl *Decl;
8130 SourceLocation Loc;
8131};
8132
8133/// A visitor over the notional body of a defaulted comparison that determines
8134/// whether that body would be deleted or constexpr.
8135class DefaultedComparisonAnalyzer
8136 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8137 DefaultedComparisonInfo,
8138 DefaultedComparisonInfo,
8139 DefaultedComparisonSubobject> {
8140public:
8141 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8142
8143private:
8144 DiagnosticKind Diagnose;
8145
8146public:
8147 using Base = DefaultedComparisonVisitor;
8148 using Result = DefaultedComparisonInfo;
8149 using Subobject = DefaultedComparisonSubobject;
8150
8151 friend Base;
8152
8153 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8154 DefaultedComparisonKind DCK,
8155 DiagnosticKind Diagnose = NoDiagnostics)
8156 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8157
8158 Result visit() {
8159 if ((DCK == DefaultedComparisonKind::Equal ||
8160 DCK == DefaultedComparisonKind::ThreeWay) &&
8161 RD->hasVariantMembers()) {
8162 // C++2a [class.compare.default]p2 [P2002R0]:
8163 // A defaulted comparison operator function for class C is defined as
8164 // deleted if [...] C has variant members.
8165 if (Diagnose == ExplainDeleted) {
8166 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_defaulted_comparison_union)
8167 << FD << RD->isUnion() << RD;
8168 }
8169 return Result::deleted();
8170 }
8171
8172 return Base::visit();
8173 }
8174
8175private:
8176 Subobject getCompleteObject() {
8177 return Subobject{.Kind: Subobject::CompleteObject, .Decl: RD, .Loc: FD->getLocation()};
8178 }
8179
8180 Subobject getBase(CXXBaseSpecifier *Base) {
8181 return Subobject{.Kind: Subobject::Base, .Decl: Base->getType()->getAsCXXRecordDecl(),
8182 .Loc: Base->getBaseTypeLoc()};
8183 }
8184
8185 Subobject getField(FieldDecl *Field) {
8186 return Subobject{.Kind: Subobject::Member, .Decl: Field, .Loc: Field->getLocation()};
8187 }
8188
8189 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8190 // C++2a [class.compare.default]p2 [P2002R0]:
8191 // A defaulted <=> or == operator function for class C is defined as
8192 // deleted if any non-static data member of C is of reference type
8193 if (Type->isReferenceType()) {
8194 if (Diagnose == ExplainDeleted) {
8195 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_reference_member)
8196 << FD << RD;
8197 }
8198 return Result::deleted();
8199 }
8200
8201 // [...] Let xi be an lvalue denoting the ith element [...]
8202 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8203 Expr *Args[] = {&Xi, &Xi};
8204
8205 // All operators start by trying to apply that same operator recursively.
8206 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8207 assert(OO != OO_None && "not an overloaded operator!");
8208 return visitBinaryOperator(OO, Args, Subobj);
8209 }
8210
8211 Result
8212 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8213 Subobject Subobj,
8214 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8215 // Note that there is no need to consider rewritten candidates here if
8216 // we've already found there is no viable 'operator<=>' candidate (and are
8217 // considering synthesizing a '<=>' from '==' and '<').
8218 OverloadCandidateSet CandidateSet(
8219 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8220 OverloadCandidateSet::OperatorRewriteInfo(
8221 OO, FD->getLocation(),
8222 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8223
8224 /// C++2a [class.compare.default]p1 [P2002R0]:
8225 /// [...] the defaulted function itself is never a candidate for overload
8226 /// resolution [...]
8227 CandidateSet.exclude(F: FD);
8228
8229 if (Args[0]->getType()->isOverloadableType())
8230 S.LookupOverloadedBinOp(CandidateSet, Op: OO, Fns, Args);
8231 else
8232 // FIXME: We determine whether this is a valid expression by checking to
8233 // see if there's a viable builtin operator candidate for it. That isn't
8234 // really what the rules ask us to do, but should give the right results.
8235 S.AddBuiltinOperatorCandidates(Op: OO, OpLoc: FD->getLocation(), Args, CandidateSet);
8236
8237 Result R;
8238
8239 OverloadCandidateSet::iterator Best;
8240 switch (CandidateSet.BestViableFunction(S, Loc: FD->getLocation(), Best)) {
8241 case OR_Success: {
8242 // C++2a [class.compare.secondary]p2 [P2002R0]:
8243 // The operator function [...] is defined as deleted if [...] the
8244 // candidate selected by overload resolution is not a rewritten
8245 // candidate.
8246 if ((DCK == DefaultedComparisonKind::NotEqual ||
8247 DCK == DefaultedComparisonKind::Relational) &&
8248 !Best->RewriteKind) {
8249 if (Diagnose == ExplainDeleted) {
8250 if (Best->Function) {
8251 S.Diag(Loc: Best->Function->getLocation(),
8252 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8253 << FD;
8254 } else {
8255 assert(Best->Conversions.size() == 2 &&
8256 Best->Conversions[0].isUserDefined() &&
8257 "non-user-defined conversion from class to built-in "
8258 "comparison");
8259 S.Diag(Loc: Best->Conversions[0]
8260 .UserDefined.FoundConversionFunction.getDecl()
8261 ->getLocation(),
8262 DiagID: diag::note_defaulted_comparison_not_rewritten_conversion)
8263 << FD;
8264 }
8265 }
8266 return Result::deleted();
8267 }
8268
8269 // Throughout C++2a [class.compare]: if overload resolution does not
8270 // result in a usable function, the candidate function is defined as
8271 // deleted. This requires that we selected an accessible function.
8272 //
8273 // Note that this only considers the access of the function when named
8274 // within the type of the subobject, and not the access path for any
8275 // derived-to-base conversion.
8276 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8277 if (ArgClass && Best->FoundDecl.getDecl() &&
8278 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8279 QualType ObjectType = Subobj.Kind == Subobject::Member
8280 ? Args[0]->getType()
8281 : S.Context.getRecordType(Decl: RD);
8282 if (!S.isMemberAccessibleForDeletion(
8283 NamingClass: ArgClass, Found: Best->FoundDecl, ObjectType, Loc: Subobj.Loc,
8284 Diag: Diagnose == ExplainDeleted
8285 ? S.PDiag(DiagID: diag::note_defaulted_comparison_inaccessible)
8286 << FD << Subobj.Kind << Subobj.Decl
8287 : S.PDiag()))
8288 return Result::deleted();
8289 }
8290
8291 bool NeedsDeducing =
8292 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8293
8294 if (FunctionDecl *BestFD = Best->Function) {
8295 // C++2a [class.compare.default]p3 [P2002R0]:
8296 // A defaulted comparison function is constexpr-compatible if
8297 // [...] no overlod resolution performed [...] results in a
8298 // non-constexpr function.
8299 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8300 // If it's not constexpr, explain why not.
8301 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8302 if (Subobj.Kind != Subobject::CompleteObject)
8303 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_not_constexpr)
8304 << Subobj.Kind << Subobj.Decl;
8305 S.Diag(Loc: BestFD->getLocation(),
8306 DiagID: diag::note_defaulted_comparison_not_constexpr_here);
8307 // Bail out after explaining; we don't want any more notes.
8308 return Result::deleted();
8309 }
8310 R.Constexpr &= BestFD->isConstexpr();
8311
8312 if (NeedsDeducing) {
8313 // If any callee has an undeduced return type, deduce it now.
8314 // FIXME: It's not clear how a failure here should be handled. For
8315 // now, we produce an eager diagnostic, because that is forward
8316 // compatible with most (all?) other reasonable options.
8317 if (BestFD->getReturnType()->isUndeducedType() &&
8318 S.DeduceReturnType(FD: BestFD, Loc: FD->getLocation(),
8319 /*Diagnose=*/false)) {
8320 // Don't produce a duplicate error when asked to explain why the
8321 // comparison is deleted: we diagnosed that when initially checking
8322 // the defaulted operator.
8323 if (Diagnose == NoDiagnostics) {
8324 S.Diag(
8325 Loc: FD->getLocation(),
8326 DiagID: diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8327 << Subobj.Kind << Subobj.Decl;
8328 S.Diag(
8329 Loc: Subobj.Loc,
8330 DiagID: diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8331 << Subobj.Kind << Subobj.Decl;
8332 S.Diag(Loc: BestFD->getLocation(),
8333 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8334 << Subobj.Kind << Subobj.Decl;
8335 }
8336 return Result::deleted();
8337 }
8338 auto *Info = S.Context.CompCategories.lookupInfoForType(
8339 Ty: BestFD->getCallResultType());
8340 if (!Info) {
8341 if (Diagnose == ExplainDeleted) {
8342 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_cannot_deduce)
8343 << Subobj.Kind << Subobj.Decl
8344 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8345 S.Diag(Loc: BestFD->getLocation(),
8346 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8347 << Subobj.Kind << Subobj.Decl;
8348 }
8349 return Result::deleted();
8350 }
8351 R.Category = Info->Kind;
8352 }
8353 } else {
8354 QualType T = Best->BuiltinParamTypes[0];
8355 assert(T == Best->BuiltinParamTypes[1] &&
8356 "builtin comparison for different types?");
8357 assert(Best->BuiltinParamTypes[2].isNull() &&
8358 "invalid builtin comparison");
8359
8360 // FIXME: If the type we deduced is a vector type, we mark the
8361 // comparison as deleted because we don't yet support this.
8362 if (isa<VectorType>(Val: T)) {
8363 if (Diagnose == ExplainDeleted) {
8364 S.Diag(Loc: FD->getLocation(),
8365 DiagID: diag::note_defaulted_comparison_vector_types)
8366 << FD;
8367 S.Diag(Loc: Subobj.Decl->getLocation(), DiagID: diag::note_declared_at);
8368 }
8369 return Result::deleted();
8370 }
8371
8372 if (NeedsDeducing) {
8373 std::optional<ComparisonCategoryType> Cat =
8374 getComparisonCategoryForBuiltinCmp(T);
8375 assert(Cat && "no category for builtin comparison?");
8376 R.Category = *Cat;
8377 }
8378 }
8379
8380 // Note that we might be rewriting to a different operator. That call is
8381 // not considered until we come to actually build the comparison function.
8382 break;
8383 }
8384
8385 case OR_Ambiguous:
8386 if (Diagnose == ExplainDeleted) {
8387 unsigned Kind = 0;
8388 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8389 Kind = OO == OO_EqualEqual ? 1 : 2;
8390 CandidateSet.NoteCandidates(
8391 PA: PartialDiagnosticAt(
8392 Subobj.Loc, S.PDiag(DiagID: diag::note_defaulted_comparison_ambiguous)
8393 << FD << Kind << Subobj.Kind << Subobj.Decl),
8394 S, OCD: OCD_AmbiguousCandidates, Args);
8395 }
8396 R = Result::deleted();
8397 break;
8398
8399 case OR_Deleted:
8400 if (Diagnose == ExplainDeleted) {
8401 if ((DCK == DefaultedComparisonKind::NotEqual ||
8402 DCK == DefaultedComparisonKind::Relational) &&
8403 !Best->RewriteKind) {
8404 S.Diag(Loc: Best->Function->getLocation(),
8405 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8406 << FD;
8407 } else {
8408 S.Diag(Loc: Subobj.Loc,
8409 DiagID: diag::note_defaulted_comparison_calls_deleted)
8410 << FD << Subobj.Kind << Subobj.Decl;
8411 S.NoteDeletedFunction(FD: Best->Function);
8412 }
8413 }
8414 R = Result::deleted();
8415 break;
8416
8417 case OR_No_Viable_Function:
8418 // If there's no usable candidate, we're done unless we can rewrite a
8419 // '<=>' in terms of '==' and '<'.
8420 if (OO == OO_Spaceship &&
8421 S.Context.CompCategories.lookupInfoForType(Ty: FD->getReturnType())) {
8422 // For any kind of comparison category return type, we need a usable
8423 // '==' and a usable '<'.
8424 if (!R.add(R: visitBinaryOperator(OO: OO_EqualEqual, Args, Subobj,
8425 SpaceshipCandidates: &CandidateSet)))
8426 R.add(R: visitBinaryOperator(OO: OO_Less, Args, Subobj, SpaceshipCandidates: &CandidateSet));
8427 break;
8428 }
8429
8430 if (Diagnose == ExplainDeleted) {
8431 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_no_viable_function)
8432 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8433 << Subobj.Kind << Subobj.Decl;
8434
8435 // For a three-way comparison, list both the candidates for the
8436 // original operator and the candidates for the synthesized operator.
8437 if (SpaceshipCandidates) {
8438 SpaceshipCandidates->NoteCandidates(
8439 S, Args,
8440 Cands: SpaceshipCandidates->CompleteCandidates(S, OCD: OCD_AllCandidates,
8441 Args, OpLoc: FD->getLocation()));
8442 S.Diag(Loc: Subobj.Loc,
8443 DiagID: diag::note_defaulted_comparison_no_viable_function_synthesized)
8444 << (OO == OO_EqualEqual ? 0 : 1);
8445 }
8446
8447 CandidateSet.NoteCandidates(
8448 S, Args,
8449 Cands: CandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
8450 OpLoc: FD->getLocation()));
8451 }
8452 R = Result::deleted();
8453 break;
8454 }
8455
8456 return R;
8457 }
8458};
8459
8460/// A list of statements.
8461struct StmtListResult {
8462 bool IsInvalid = false;
8463 llvm::SmallVector<Stmt*, 16> Stmts;
8464
8465 bool add(const StmtResult &S) {
8466 IsInvalid |= S.isInvalid();
8467 if (IsInvalid)
8468 return true;
8469 Stmts.push_back(Elt: S.get());
8470 return false;
8471 }
8472};
8473
8474/// A visitor over the notional body of a defaulted comparison that synthesizes
8475/// the actual body.
8476class DefaultedComparisonSynthesizer
8477 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8478 StmtListResult, StmtResult,
8479 std::pair<ExprResult, ExprResult>> {
8480 SourceLocation Loc;
8481 unsigned ArrayDepth = 0;
8482
8483public:
8484 using Base = DefaultedComparisonVisitor;
8485 using ExprPair = std::pair<ExprResult, ExprResult>;
8486
8487 friend Base;
8488
8489 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8490 DefaultedComparisonKind DCK,
8491 SourceLocation BodyLoc)
8492 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8493
8494 /// Build a suitable function body for this defaulted comparison operator.
8495 StmtResult build() {
8496 Sema::CompoundScopeRAII CompoundScope(S);
8497
8498 StmtListResult Stmts = visit();
8499 if (Stmts.IsInvalid)
8500 return StmtError();
8501
8502 ExprResult RetVal;
8503 switch (DCK) {
8504 case DefaultedComparisonKind::None:
8505 llvm_unreachable("not a defaulted comparison");
8506
8507 case DefaultedComparisonKind::Equal: {
8508 // C++2a [class.eq]p3:
8509 // [...] compar[e] the corresponding elements [...] until the first
8510 // index i where xi == yi yields [...] false. If no such index exists,
8511 // V is true. Otherwise, V is false.
8512 //
8513 // Join the comparisons with '&&'s and return the result. Use a right
8514 // fold (traversing the conditions right-to-left), because that
8515 // short-circuits more naturally.
8516 auto OldStmts = std::move(Stmts.Stmts);
8517 Stmts.Stmts.clear();
8518 ExprResult CmpSoFar;
8519 // Finish a particular comparison chain.
8520 auto FinishCmp = [&] {
8521 if (Expr *Prior = CmpSoFar.get()) {
8522 // Convert the last expression to 'return ...;'
8523 if (RetVal.isUnset() && Stmts.Stmts.empty())
8524 RetVal = CmpSoFar;
8525 // Convert any prior comparison to 'if (!(...)) return false;'
8526 else if (Stmts.add(S: buildIfNotCondReturnFalse(Cond: Prior)))
8527 return true;
8528 CmpSoFar = ExprResult();
8529 }
8530 return false;
8531 };
8532 for (Stmt *EAsStmt : llvm::reverse(C&: OldStmts)) {
8533 Expr *E = dyn_cast<Expr>(Val: EAsStmt);
8534 if (!E) {
8535 // Found an array comparison.
8536 if (FinishCmp() || Stmts.add(S: EAsStmt))
8537 return StmtError();
8538 continue;
8539 }
8540
8541 if (CmpSoFar.isUnset()) {
8542 CmpSoFar = E;
8543 continue;
8544 }
8545 CmpSoFar = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_LAnd, LHSExpr: E, RHSExpr: CmpSoFar.get());
8546 if (CmpSoFar.isInvalid())
8547 return StmtError();
8548 }
8549 if (FinishCmp())
8550 return StmtError();
8551 std::reverse(first: Stmts.Stmts.begin(), last: Stmts.Stmts.end());
8552 // If no such index exists, V is true.
8553 if (RetVal.isUnset())
8554 RetVal = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_true);
8555 break;
8556 }
8557
8558 case DefaultedComparisonKind::ThreeWay: {
8559 // Per C++2a [class.spaceship]p3, as a fallback add:
8560 // return static_cast<R>(std::strong_ordering::equal);
8561 QualType StrongOrdering = S.CheckComparisonCategoryType(
8562 Kind: ComparisonCategoryType::StrongOrdering, Loc,
8563 Usage: Sema::ComparisonCategoryUsage::DefaultedOperator);
8564 if (StrongOrdering.isNull())
8565 return StmtError();
8566 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(Ty: StrongOrdering)
8567 .getValueInfo(ValueKind: ComparisonCategoryResult::Equal)
8568 ->VD;
8569 RetVal = getDecl(VD: EqualVD);
8570 if (RetVal.isInvalid())
8571 return StmtError();
8572 RetVal = buildStaticCastToR(E: RetVal.get());
8573 break;
8574 }
8575
8576 case DefaultedComparisonKind::NotEqual:
8577 case DefaultedComparisonKind::Relational:
8578 RetVal = cast<Expr>(Val: Stmts.Stmts.pop_back_val());
8579 break;
8580 }
8581
8582 // Build the final return statement.
8583 if (RetVal.isInvalid())
8584 return StmtError();
8585 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: RetVal.get());
8586 if (ReturnStmt.isInvalid())
8587 return StmtError();
8588 Stmts.Stmts.push_back(Elt: ReturnStmt.get());
8589
8590 return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts.Stmts, /*IsStmtExpr=*/isStmtExpr: false);
8591 }
8592
8593private:
8594 ExprResult getDecl(ValueDecl *VD) {
8595 return S.BuildDeclarationNameExpr(
8596 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8597 }
8598
8599 ExprResult getParam(unsigned I) {
8600 ParmVarDecl *PD = FD->getParamDecl(i: I);
8601 return getDecl(VD: PD);
8602 }
8603
8604 ExprPair getCompleteObject() {
8605 unsigned Param = 0;
8606 ExprResult LHS;
8607 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
8608 MD && MD->isImplicitObjectMemberFunction()) {
8609 // LHS is '*this'.
8610 LHS = S.ActOnCXXThis(Loc);
8611 if (!LHS.isInvalid())
8612 LHS = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: LHS.get());
8613 } else {
8614 LHS = getParam(I: Param++);
8615 }
8616 ExprResult RHS = getParam(I: Param++);
8617 assert(Param == FD->getNumParams());
8618 return {LHS, RHS};
8619 }
8620
8621 ExprPair getBase(CXXBaseSpecifier *Base) {
8622 ExprPair Obj = getCompleteObject();
8623 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8624 return {ExprError(), ExprError()};
8625 CXXCastPath Path = {Base};
8626 const auto CastToBase = [&](Expr *E) {
8627 QualType ToType = S.Context.getQualifiedType(
8628 T: Base->getType(), Qs: E->getType().getQualifiers());
8629 return S.ImpCastExprToType(E, Type: ToType, CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path);
8630 };
8631 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8632 }
8633
8634 ExprPair getField(FieldDecl *Field) {
8635 ExprPair Obj = getCompleteObject();
8636 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8637 return {ExprError(), ExprError()};
8638
8639 DeclAccessPair Found = DeclAccessPair::make(D: Field, AS: Field->getAccess());
8640 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8641 return {S.BuildFieldReferenceExpr(BaseExpr: Obj.first.get(), /*IsArrow=*/false, OpLoc: Loc,
8642 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo),
8643 S.BuildFieldReferenceExpr(BaseExpr: Obj.second.get(), /*IsArrow=*/false, OpLoc: Loc,
8644 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo)};
8645 }
8646
8647 // FIXME: When expanding a subobject, register a note in the code synthesis
8648 // stack to say which subobject we're comparing.
8649
8650 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8651 if (Cond.isInvalid())
8652 return StmtError();
8653
8654 ExprResult NotCond = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_LNot, InputExpr: Cond.get());
8655 if (NotCond.isInvalid())
8656 return StmtError();
8657
8658 ExprResult False = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_false);
8659 assert(!False.isInvalid() && "should never fail");
8660 StmtResult ReturnFalse = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: False.get());
8661 if (ReturnFalse.isInvalid())
8662 return StmtError();
8663
8664 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt: nullptr,
8665 Cond: S.ActOnCondition(S: nullptr, Loc, SubExpr: NotCond.get(),
8666 CK: Sema::ConditionKind::Boolean),
8667 RParenLoc: Loc, ThenVal: ReturnFalse.get(), ElseLoc: SourceLocation(), ElseVal: nullptr);
8668 }
8669
8670 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8671 ExprPair Subobj) {
8672 QualType SizeType = S.Context.getSizeType();
8673 Size = Size.zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
8674
8675 // Build 'size_t i$n = 0'.
8676 IdentifierInfo *IterationVarName = nullptr;
8677 {
8678 SmallString<8> Str;
8679 llvm::raw_svector_ostream OS(Str);
8680 OS << "i" << ArrayDepth;
8681 IterationVarName = &S.Context.Idents.get(Name: OS.str());
8682 }
8683 VarDecl *IterationVar = VarDecl::Create(
8684 C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: IterationVarName, T: SizeType,
8685 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), S: SC_None);
8686 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
8687 IterationVar->setInit(
8688 IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
8689 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8690
8691 auto IterRef = [&] {
8692 ExprResult Ref = S.BuildDeclarationNameExpr(
8693 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(IterationVarName, Loc),
8694 D: IterationVar);
8695 assert(!Ref.isInvalid() && "can't reference our own variable?");
8696 return Ref.get();
8697 };
8698
8699 // Build 'i$n != Size'.
8700 ExprResult Cond = S.CreateBuiltinBinOp(
8701 OpLoc: Loc, Opc: BO_NE, LHSExpr: IterRef(),
8702 RHSExpr: IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc));
8703 assert(!Cond.isInvalid() && "should never fail");
8704
8705 // Build '++i$n'.
8706 ExprResult Inc = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_PreInc, InputExpr: IterRef());
8707 assert(!Inc.isInvalid() && "should never fail");
8708
8709 // Build 'a[i$n]' and 'b[i$n]'.
8710 auto Index = [&](ExprResult E) {
8711 if (E.isInvalid())
8712 return ExprError();
8713 return S.CreateBuiltinArraySubscriptExpr(Base: E.get(), LLoc: Loc, Idx: IterRef(), RLoc: Loc);
8714 };
8715 Subobj.first = Index(Subobj.first);
8716 Subobj.second = Index(Subobj.second);
8717
8718 // Compare the array elements.
8719 ++ArrayDepth;
8720 StmtResult Substmt = visitSubobject(Type, Subobj);
8721 --ArrayDepth;
8722
8723 if (Substmt.isInvalid())
8724 return StmtError();
8725
8726 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8727 // For outer levels or for an 'operator<=>' we already have a suitable
8728 // statement that returns as necessary.
8729 if (Expr *ElemCmp = dyn_cast<Expr>(Val: Substmt.get())) {
8730 assert(DCK == DefaultedComparisonKind::Equal &&
8731 "should have non-expression statement");
8732 Substmt = buildIfNotCondReturnFalse(Cond: ElemCmp);
8733 if (Substmt.isInvalid())
8734 return StmtError();
8735 }
8736
8737 // Build 'for (...) ...'
8738 return S.ActOnForStmt(ForLoc: Loc, LParenLoc: Loc, First: Init,
8739 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Cond.get(),
8740 CK: Sema::ConditionKind::Boolean),
8741 Third: S.MakeFullDiscardedValueExpr(Arg: Inc.get()), RParenLoc: Loc,
8742 Body: Substmt.get());
8743 }
8744
8745 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8746 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8747 return StmtError();
8748
8749 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8750 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8751 ExprResult Op;
8752 if (Type->isOverloadableType())
8753 Op = S.CreateOverloadedBinOp(OpLoc: Loc, Opc, Fns, LHS: Obj.first.get(),
8754 RHS: Obj.second.get(), /*PerformADL=*/RequiresADL: true,
8755 /*AllowRewrittenCandidates=*/true, DefaultedFn: FD);
8756 else
8757 Op = S.CreateBuiltinBinOp(OpLoc: Loc, Opc, LHSExpr: Obj.first.get(), RHSExpr: Obj.second.get());
8758 if (Op.isInvalid())
8759 return StmtError();
8760
8761 switch (DCK) {
8762 case DefaultedComparisonKind::None:
8763 llvm_unreachable("not a defaulted comparison");
8764
8765 case DefaultedComparisonKind::Equal:
8766 // Per C++2a [class.eq]p2, each comparison is individually contextually
8767 // converted to bool.
8768 Op = S.PerformContextuallyConvertToBool(From: Op.get());
8769 if (Op.isInvalid())
8770 return StmtError();
8771 return Op.get();
8772
8773 case DefaultedComparisonKind::ThreeWay: {
8774 // Per C++2a [class.spaceship]p3, form:
8775 // if (R cmp = static_cast<R>(op); cmp != 0)
8776 // return cmp;
8777 QualType R = FD->getReturnType();
8778 Op = buildStaticCastToR(E: Op.get());
8779 if (Op.isInvalid())
8780 return StmtError();
8781
8782 // R cmp = ...;
8783 IdentifierInfo *Name = &S.Context.Idents.get(Name: "cmp");
8784 VarDecl *VD =
8785 VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: Name, T: R,
8786 TInfo: S.Context.getTrivialTypeSourceInfo(T: R, Loc), S: SC_None);
8787 S.AddInitializerToDecl(dcl: VD, init: Op.get(), /*DirectInit=*/false);
8788 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8789
8790 // cmp != 0
8791 ExprResult VDRef = getDecl(VD);
8792 if (VDRef.isInvalid())
8793 return StmtError();
8794 llvm::APInt ZeroVal(S.Context.getIntWidth(T: S.Context.IntTy), 0);
8795 Expr *Zero =
8796 IntegerLiteral::Create(C: S.Context, V: ZeroVal, type: S.Context.IntTy, l: Loc);
8797 ExprResult Comp;
8798 if (VDRef.get()->getType()->isOverloadableType())
8799 Comp = S.CreateOverloadedBinOp(OpLoc: Loc, Opc: BO_NE, Fns, LHS: VDRef.get(), RHS: Zero, RequiresADL: true,
8800 AllowRewrittenCandidates: true, DefaultedFn: FD);
8801 else
8802 Comp = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_NE, LHSExpr: VDRef.get(), RHSExpr: Zero);
8803 if (Comp.isInvalid())
8804 return StmtError();
8805 Sema::ConditionResult Cond = S.ActOnCondition(
8806 S: nullptr, Loc, SubExpr: Comp.get(), CK: Sema::ConditionKind::Boolean);
8807 if (Cond.isInvalid())
8808 return StmtError();
8809
8810 // return cmp;
8811 VDRef = getDecl(VD);
8812 if (VDRef.isInvalid())
8813 return StmtError();
8814 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: VDRef.get());
8815 if (ReturnStmt.isInvalid())
8816 return StmtError();
8817
8818 // if (...)
8819 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt, Cond,
8820 RParenLoc: Loc, ThenVal: ReturnStmt.get(),
8821 /*ElseLoc=*/SourceLocation(), /*Else=*/ElseVal: nullptr);
8822 }
8823
8824 case DefaultedComparisonKind::NotEqual:
8825 case DefaultedComparisonKind::Relational:
8826 // C++2a [class.compare.secondary]p2:
8827 // Otherwise, the operator function yields x @ y.
8828 return Op.get();
8829 }
8830 llvm_unreachable("");
8831 }
8832
8833 /// Build "static_cast<R>(E)".
8834 ExprResult buildStaticCastToR(Expr *E) {
8835 QualType R = FD->getReturnType();
8836 assert(!R->isUndeducedType() && "type should have been deduced already");
8837
8838 // Don't bother forming a no-op cast in the common case.
8839 if (E->isPRValue() && S.Context.hasSameType(T1: E->getType(), T2: R))
8840 return E;
8841 return S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast,
8842 Ty: S.Context.getTrivialTypeSourceInfo(T: R, Loc), E,
8843 AngleBrackets: SourceRange(Loc, Loc), Parens: SourceRange(Loc, Loc));
8844 }
8845};
8846}
8847
8848/// Perform the unqualified lookups that might be needed to form a defaulted
8849/// comparison function for the given operator.
8850static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8851 UnresolvedSetImpl &Operators,
8852 OverloadedOperatorKind Op) {
8853 auto Lookup = [&](OverloadedOperatorKind OO) {
8854 Self.LookupOverloadedOperatorName(Op: OO, S, Functions&: Operators);
8855 };
8856
8857 // Every defaulted operator looks up itself.
8858 Lookup(Op);
8859 // ... and the rewritten form of itself, if any.
8860 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: Op))
8861 Lookup(ExtraOp);
8862
8863 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8864 // synthesize a three-way comparison from '<' and '=='. In a dependent
8865 // context, we also need to look up '==' in case we implicitly declare a
8866 // defaulted 'operator=='.
8867 if (Op == OO_Spaceship) {
8868 Lookup(OO_ExclaimEqual);
8869 Lookup(OO_Less);
8870 Lookup(OO_EqualEqual);
8871 }
8872}
8873
8874bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8875 DefaultedComparisonKind DCK) {
8876 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8877
8878 // Perform any unqualified lookups we're going to need to default this
8879 // function.
8880 if (S) {
8881 UnresolvedSet<32> Operators;
8882 lookupOperatorsForDefaultedComparison(Self&: *this, S, Operators,
8883 Op: FD->getOverloadedOperator());
8884 FD->setDefaultedOrDeletedInfo(
8885 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
8886 Context, Lookups: Operators.pairs()));
8887 }
8888
8889 // C++2a [class.compare.default]p1:
8890 // A defaulted comparison operator function for some class C shall be a
8891 // non-template function declared in the member-specification of C that is
8892 // -- a non-static const non-volatile member of C having one parameter of
8893 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8894 // -- a friend of C having two parameters of type const C& or two
8895 // parameters of type C.
8896
8897 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext());
8898 bool IsMethod = isa<CXXMethodDecl>(Val: FD);
8899 if (IsMethod) {
8900 auto *MD = cast<CXXMethodDecl>(Val: FD);
8901 assert(!MD->isStatic() && "comparison function cannot be a static member");
8902
8903 if (MD->getRefQualifier() == RQ_RValue) {
8904 Diag(Loc: MD->getLocation(), DiagID: diag::err_ref_qualifier_comparison_operator);
8905
8906 // Remove the ref qualifier to recover.
8907 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8908 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8909 EPI.RefQualifier = RQ_None;
8910 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
8911 Args: FPT->getParamTypes(), EPI));
8912 }
8913
8914 // If we're out-of-class, this is the class we're comparing.
8915 if (!RD)
8916 RD = MD->getParent();
8917 QualType T = MD->getFunctionObjectParameterReferenceType();
8918 if (!T.getNonReferenceType().isConstQualified() &&
8919 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
8920 SourceLocation Loc, InsertLoc;
8921 if (MD->isExplicitObjectMemberFunction()) {
8922 Loc = MD->getParamDecl(i: 0)->getBeginLoc();
8923 InsertLoc = getLocForEndOfToken(
8924 Loc: MD->getParamDecl(i: 0)->getExplicitObjectParamThisLoc());
8925 } else {
8926 Loc = MD->getLocation();
8927 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8928 InsertLoc = Loc.getRParenLoc();
8929 }
8930 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8931 // corresponding defaulted 'operator<=>' already.
8932 if (!MD->isImplicit()) {
8933 Diag(Loc, DiagID: diag::err_defaulted_comparison_non_const)
8934 << (int)DCK << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " const");
8935 }
8936
8937 // Add the 'const' to the type to recover.
8938 if (MD->isExplicitObjectMemberFunction()) {
8939 assert(T->isLValueReferenceType());
8940 MD->getParamDecl(i: 0)->setType(Context.getLValueReferenceType(
8941 T: T.getNonReferenceType().withConst()));
8942 } else {
8943 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8944 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8945 EPI.TypeQuals.addConst();
8946 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
8947 Args: FPT->getParamTypes(), EPI));
8948 }
8949 }
8950
8951 if (MD->isVolatile()) {
8952 Diag(Loc: MD->getLocation(), DiagID: diag::err_volatile_comparison_operator);
8953
8954 // Remove the 'volatile' from the type to recover.
8955 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8956 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8957 EPI.TypeQuals.removeVolatile();
8958 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
8959 Args: FPT->getParamTypes(), EPI));
8960 }
8961 }
8962
8963 if ((FD->getNumParams() -
8964 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8965 (IsMethod ? 1 : 2)) {
8966 // Let's not worry about using a variadic template pack here -- who would do
8967 // such a thing?
8968 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_num_args)
8969 << int(IsMethod) << int(DCK);
8970 return true;
8971 }
8972
8973 const ParmVarDecl *KnownParm = nullptr;
8974 for (const ParmVarDecl *Param : FD->parameters()) {
8975 QualType ParmTy = Param->getType();
8976 if (!KnownParm) {
8977 auto CTy = ParmTy;
8978 // Is it `T const &`?
8979 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
8980 QualType ExpectedTy;
8981 if (RD)
8982 ExpectedTy = Context.getRecordType(Decl: RD);
8983 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
8984 CTy = Ref->getPointeeType();
8985 if (RD)
8986 ExpectedTy.addConst();
8987 Ok = true;
8988 }
8989
8990 // Is T a class?
8991 if (RD) {
8992 Ok &= RD->isDependentType() || Context.hasSameType(T1: CTy, T2: ExpectedTy);
8993 } else {
8994 RD = CTy->getAsCXXRecordDecl();
8995 Ok &= RD != nullptr;
8996 }
8997
8998 if (Ok) {
8999 KnownParm = Param;
9000 } else {
9001 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9002 // corresponding defaulted 'operator<=>' already.
9003 if (!FD->isImplicit()) {
9004 if (RD) {
9005 QualType PlainTy = Context.getRecordType(Decl: RD);
9006 QualType RefTy =
9007 Context.getLValueReferenceType(T: PlainTy.withConst());
9008 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param)
9009 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9010 << Param->getSourceRange();
9011 } else {
9012 assert(!IsMethod && "should know expected type for method");
9013 Diag(Loc: FD->getLocation(),
9014 DiagID: diag::err_defaulted_comparison_param_unknown)
9015 << int(DCK) << ParmTy << Param->getSourceRange();
9016 }
9017 }
9018 return true;
9019 }
9020 } else if (!Context.hasSameType(T1: KnownParm->getType(), T2: ParmTy)) {
9021 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param_mismatch)
9022 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9023 << ParmTy << Param->getSourceRange();
9024 return true;
9025 }
9026 }
9027
9028 assert(RD && "must have determined class");
9029 if (IsMethod) {
9030 } else if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9031 // In-class, must be a friend decl.
9032 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9033 } else {
9034 // Out of class, require the defaulted comparison to be a friend (of a
9035 // complete type, per CWG2547).
9036 if (RequireCompleteType(Loc: FD->getLocation(), T: Context.getRecordType(Decl: RD),
9037 DiagID: diag::err_defaulted_comparison_not_friend, Args: int(DCK),
9038 Args: int(1)))
9039 return true;
9040
9041 if (llvm::none_of(Range: RD->friends(), P: [&](const FriendDecl *F) {
9042 return declaresSameEntity(D1: F->getFriendDecl(), D2: FD);
9043 })) {
9044 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_not_friend)
9045 << int(DCK) << int(0) << RD;
9046 Diag(Loc: RD->getCanonicalDecl()->getLocation(), DiagID: diag::note_declared_at);
9047 return true;
9048 }
9049 }
9050
9051 // C++2a [class.eq]p1, [class.rel]p1:
9052 // A [defaulted comparison other than <=>] shall have a declared return
9053 // type bool.
9054 if (DCK != DefaultedComparisonKind::ThreeWay &&
9055 !FD->getDeclaredReturnType()->isDependentType() &&
9056 !Context.hasSameType(T1: FD->getDeclaredReturnType(), T2: Context.BoolTy)) {
9057 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_return_type_not_bool)
9058 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9059 << FD->getReturnTypeSourceRange();
9060 return true;
9061 }
9062 // C++2a [class.spaceship]p2 [P2002R0]:
9063 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9064 // R shall not contain a placeholder type.
9065 if (QualType RT = FD->getDeclaredReturnType();
9066 DCK == DefaultedComparisonKind::ThreeWay &&
9067 RT->getContainedDeducedType() &&
9068 (!Context.hasSameType(T1: RT, T2: Context.getAutoDeductType()) ||
9069 RT->getContainedAutoType()->isConstrained())) {
9070 Diag(Loc: FD->getLocation(),
9071 DiagID: diag::err_defaulted_comparison_deduced_return_type_not_auto)
9072 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9073 << FD->getReturnTypeSourceRange();
9074 return true;
9075 }
9076
9077 // For a defaulted function in a dependent class, defer all remaining checks
9078 // until instantiation.
9079 if (RD->isDependentType())
9080 return false;
9081
9082 // Determine whether the function should be defined as deleted.
9083 DefaultedComparisonInfo Info =
9084 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9085
9086 bool First = FD == FD->getCanonicalDecl();
9087
9088 if (!First) {
9089 if (Info.Deleted) {
9090 // C++11 [dcl.fct.def.default]p4:
9091 // [For a] user-provided explicitly-defaulted function [...] if such a
9092 // function is implicitly defined as deleted, the program is ill-formed.
9093 //
9094 // This is really just a consequence of the general rule that you can
9095 // only delete a function on its first declaration.
9096 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_deletes)
9097 << FD->isImplicit() << (int)DCK;
9098 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9099 DefaultedComparisonAnalyzer::ExplainDeleted)
9100 .visit();
9101 return true;
9102 }
9103 if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9104 // C++20 [class.compare.default]p1:
9105 // [...] A definition of a comparison operator as defaulted that appears
9106 // in a class shall be the first declaration of that function.
9107 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_in_class)
9108 << (int)DCK;
9109 Diag(Loc: FD->getCanonicalDecl()->getLocation(),
9110 DiagID: diag::note_previous_declaration);
9111 return true;
9112 }
9113 }
9114
9115 // If we want to delete the function, then do so; there's nothing else to
9116 // check in that case.
9117 if (Info.Deleted) {
9118 SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation());
9119 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9120 Diag(Loc: FD->getLocation(), DiagID: diag::warn_defaulted_comparison_deleted)
9121 << (int)DCK;
9122 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9123 DefaultedComparisonAnalyzer::ExplainDeleted)
9124 .visit();
9125 if (FD->getDefaultLoc().isValid())
9126 Diag(Loc: FD->getDefaultLoc(), DiagID: diag::note_replace_equals_default_to_delete)
9127 << FixItHint::CreateReplacement(RemoveRange: FD->getDefaultLoc(), Code: "delete");
9128 }
9129 return false;
9130 }
9131
9132 // C++2a [class.spaceship]p2:
9133 // The return type is deduced as the common comparison type of R0, R1, ...
9134 if (DCK == DefaultedComparisonKind::ThreeWay &&
9135 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9136 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9137 if (RetLoc.isInvalid())
9138 RetLoc = FD->getBeginLoc();
9139 // FIXME: Should we really care whether we have the complete type and the
9140 // 'enumerator' constants here? A forward declaration seems sufficient.
9141 QualType Cat = CheckComparisonCategoryType(
9142 Kind: Info.Category, Loc: RetLoc, Usage: ComparisonCategoryUsage::DefaultedOperator);
9143 if (Cat.isNull())
9144 return true;
9145 Context.adjustDeducedFunctionResultType(
9146 FD, ResultType: SubstAutoType(TypeWithAuto: FD->getDeclaredReturnType(), Replacement: Cat));
9147 }
9148
9149 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9150 // An explicitly-defaulted function that is not defined as deleted may be
9151 // declared constexpr or consteval only if it is constexpr-compatible.
9152 // C++2a [class.compare.default]p3 [P2002R0]:
9153 // A defaulted comparison function is constexpr-compatible if it satisfies
9154 // the requirements for a constexpr function [...]
9155 // The only relevant requirements are that the parameter and return types are
9156 // literal types. The remaining conditions are checked by the analyzer.
9157 //
9158 // We support P2448R2 in language modes earlier than C++23 as an extension.
9159 // The concept of constexpr-compatible was removed.
9160 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9161 // A function explicitly defaulted on its first declaration is implicitly
9162 // inline, and is implicitly constexpr if it is constexpr-suitable.
9163 // C++23 [dcl.constexpr]p3
9164 // A function is constexpr-suitable if
9165 // - it is not a coroutine, and
9166 // - if the function is a constructor or destructor, its class does not
9167 // have any virtual base classes.
9168 if (FD->isConstexpr()) {
9169 if (!getLangOpts().CPlusPlus23 &&
9170 CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9171 CheckConstexprParameterTypes(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9172 !Info.Constexpr) {
9173 Diag(Loc: FD->getBeginLoc(), DiagID: diag::err_defaulted_comparison_constexpr_mismatch)
9174 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9175 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9176 DefaultedComparisonAnalyzer::ExplainConstexpr)
9177 .visit();
9178 }
9179 }
9180
9181 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9182 // If a constexpr-compatible function is explicitly defaulted on its first
9183 // declaration, it is implicitly considered to be constexpr.
9184 // FIXME: Only applying this to the first declaration seems problematic, as
9185 // simple reorderings can affect the meaning of the program.
9186 if (First && !FD->isConstexpr() && Info.Constexpr)
9187 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9188
9189 // C++2a [except.spec]p3:
9190 // If a declaration of a function does not have a noexcept-specifier
9191 // [and] is defaulted on its first declaration, [...] the exception
9192 // specification is as specified below
9193 if (FD->getExceptionSpecType() == EST_None) {
9194 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9195 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9196 EPI.ExceptionSpec.Type = EST_Unevaluated;
9197 EPI.ExceptionSpec.SourceDecl = FD;
9198 FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9199 Args: FPT->getParamTypes(), EPI));
9200 }
9201
9202 return false;
9203}
9204
9205void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9206 FunctionDecl *Spaceship) {
9207 Sema::CodeSynthesisContext Ctx;
9208 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9209 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9210 Ctx.Entity = Spaceship;
9211 pushCodeSynthesisContext(Ctx);
9212
9213 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9214 EqualEqual->setImplicit();
9215
9216 popCodeSynthesisContext();
9217}
9218
9219void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9220 DefaultedComparisonKind DCK) {
9221 assert(FD->isDefaulted() && !FD->isDeleted() &&
9222 !FD->doesThisDeclarationHaveABody());
9223 if (FD->willHaveBody() || FD->isInvalidDecl())
9224 return;
9225
9226 SynthesizedFunctionScope Scope(*this, FD);
9227
9228 // Add a context note for diagnostics produced after this point.
9229 Scope.addContextNote(UseLoc);
9230
9231 {
9232 // Build and set up the function body.
9233 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9234 // the type of the class being compared.
9235 auto PT = FD->getParamDecl(i: 0)->getType();
9236 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9237 SourceLocation BodyLoc =
9238 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9239 StmtResult Body =
9240 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9241 if (Body.isInvalid()) {
9242 FD->setInvalidDecl();
9243 return;
9244 }
9245 FD->setBody(Body.get());
9246 FD->markUsed(C&: Context);
9247 }
9248
9249 // The exception specification is needed because we are defining the
9250 // function. Note that this will reuse the body we just built.
9251 ResolveExceptionSpec(Loc: UseLoc, FPT: FD->getType()->castAs<FunctionProtoType>());
9252
9253 if (ASTMutationListener *L = getASTMutationListener())
9254 L->CompletedImplicitDefinition(D: FD);
9255}
9256
9257static Sema::ImplicitExceptionSpecification
9258ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9259 FunctionDecl *FD,
9260 Sema::DefaultedComparisonKind DCK) {
9261 ComputingExceptionSpec CES(S, FD, Loc);
9262 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9263
9264 if (FD->isInvalidDecl())
9265 return ExceptSpec;
9266
9267 // The common case is that we just defined the comparison function. In that
9268 // case, just look at whether the body can throw.
9269 if (FD->hasBody()) {
9270 ExceptSpec.CalledStmt(S: FD->getBody());
9271 } else {
9272 // Otherwise, build a body so we can check it. This should ideally only
9273 // happen when we're not actually marking the function referenced. (This is
9274 // only really important for efficiency: we don't want to build and throw
9275 // away bodies for comparison functions more than we strictly need to.)
9276
9277 // Pretend to synthesize the function body in an unevaluated context.
9278 // Note that we can't actually just go ahead and define the function here:
9279 // we are not permitted to mark its callees as referenced.
9280 Sema::SynthesizedFunctionScope Scope(S, FD);
9281 EnterExpressionEvaluationContext Context(
9282 S, Sema::ExpressionEvaluationContext::Unevaluated);
9283
9284 CXXRecordDecl *RD =
9285 cast<CXXRecordDecl>(Val: FD->getFriendObjectKind() == Decl::FOK_None
9286 ? FD->getDeclContext()
9287 : FD->getLexicalDeclContext());
9288 SourceLocation BodyLoc =
9289 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9290 StmtResult Body =
9291 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9292 if (!Body.isInvalid())
9293 ExceptSpec.CalledStmt(S: Body.get());
9294
9295 // FIXME: Can we hold onto this body and just transform it to potentially
9296 // evaluated when we're asked to define the function rather than rebuilding
9297 // it? Either that, or we should only build the bits of the body that we
9298 // need (the expressions, not the statements).
9299 }
9300
9301 return ExceptSpec;
9302}
9303
9304void Sema::CheckDelayedMemberExceptionSpecs() {
9305 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9306 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9307
9308 std::swap(LHS&: Overriding, RHS&: DelayedOverridingExceptionSpecChecks);
9309 std::swap(LHS&: Equivalent, RHS&: DelayedEquivalentExceptionSpecChecks);
9310
9311 // Perform any deferred checking of exception specifications for virtual
9312 // destructors.
9313 for (auto &Check : Overriding)
9314 CheckOverridingFunctionExceptionSpec(New: Check.first, Old: Check.second);
9315
9316 // Perform any deferred checking of exception specifications for befriended
9317 // special members.
9318 for (auto &Check : Equivalent)
9319 CheckEquivalentExceptionSpec(Old: Check.second, New: Check.first);
9320}
9321
9322namespace {
9323/// CRTP base class for visiting operations performed by a special member
9324/// function (or inherited constructor).
9325template<typename Derived>
9326struct SpecialMemberVisitor {
9327 Sema &S;
9328 CXXMethodDecl *MD;
9329 CXXSpecialMemberKind CSM;
9330 Sema::InheritedConstructorInfo *ICI;
9331
9332 // Properties of the special member, computed for convenience.
9333 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9334
9335 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9336 Sema::InheritedConstructorInfo *ICI)
9337 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9338 switch (CSM) {
9339 case CXXSpecialMemberKind::DefaultConstructor:
9340 case CXXSpecialMemberKind::CopyConstructor:
9341 case CXXSpecialMemberKind::MoveConstructor:
9342 IsConstructor = true;
9343 break;
9344 case CXXSpecialMemberKind::CopyAssignment:
9345 case CXXSpecialMemberKind::MoveAssignment:
9346 IsAssignment = true;
9347 break;
9348 case CXXSpecialMemberKind::Destructor:
9349 break;
9350 case CXXSpecialMemberKind::Invalid:
9351 llvm_unreachable("invalid special member kind");
9352 }
9353
9354 if (MD->getNumExplicitParams()) {
9355 if (const ReferenceType *RT =
9356 MD->getNonObjectParameter(I: 0)->getType()->getAs<ReferenceType>())
9357 ConstArg = RT->getPointeeType().isConstQualified();
9358 }
9359 }
9360
9361 Derived &getDerived() { return static_cast<Derived&>(*this); }
9362
9363 /// Is this a "move" special member?
9364 bool isMove() const {
9365 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9366 CSM == CXXSpecialMemberKind::MoveAssignment;
9367 }
9368
9369 /// Look up the corresponding special member in the given class.
9370 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9371 unsigned Quals, bool IsMutable) {
9372 return lookupCallFromSpecialMember(S, Class, CSM, FieldQuals: Quals,
9373 ConstRHS: ConstArg && !IsMutable);
9374 }
9375
9376 /// Look up the constructor for the specified base class to see if it's
9377 /// overridden due to this being an inherited constructor.
9378 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9379 if (!ICI)
9380 return {};
9381 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9382 auto *BaseCtor =
9383 cast<CXXConstructorDecl>(Val: MD)->getInheritedConstructor().getConstructor();
9384 if (auto *MD = ICI->findConstructorForBase(Base: Class, Ctor: BaseCtor).first)
9385 return MD;
9386 return {};
9387 }
9388
9389 /// A base or member subobject.
9390 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9391
9392 /// Get the location to use for a subobject in diagnostics.
9393 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9394 // FIXME: For an indirect virtual base, the direct base leading to
9395 // the indirect virtual base would be a more useful choice.
9396 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Val&: Subobj))
9397 return B->getBaseTypeLoc();
9398 else
9399 return cast<FieldDecl *>(Val&: Subobj)->getLocation();
9400 }
9401
9402 enum BasesToVisit {
9403 /// Visit all non-virtual (direct) bases.
9404 VisitNonVirtualBases,
9405 /// Visit all direct bases, virtual or not.
9406 VisitDirectBases,
9407 /// Visit all non-virtual bases, and all virtual bases if the class
9408 /// is not abstract.
9409 VisitPotentiallyConstructedBases,
9410 /// Visit all direct or virtual bases.
9411 VisitAllBases
9412 };
9413
9414 // Visit the bases and members of the class.
9415 bool visit(BasesToVisit Bases) {
9416 CXXRecordDecl *RD = MD->getParent();
9417
9418 if (Bases == VisitPotentiallyConstructedBases)
9419 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9420
9421 for (auto &B : RD->bases())
9422 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9423 getDerived().visitBase(&B))
9424 return true;
9425
9426 if (Bases == VisitAllBases)
9427 for (auto &B : RD->vbases())
9428 if (getDerived().visitBase(&B))
9429 return true;
9430
9431 for (auto *F : RD->fields())
9432 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9433 getDerived().visitField(F))
9434 return true;
9435
9436 return false;
9437 }
9438};
9439}
9440
9441namespace {
9442struct SpecialMemberDeletionInfo
9443 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9444 bool Diagnose;
9445
9446 SourceLocation Loc;
9447
9448 bool AllFieldsAreConst;
9449
9450 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9451 CXXSpecialMemberKind CSM,
9452 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9453 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9454 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9455
9456 bool inUnion() const { return MD->getParent()->isUnion(); }
9457
9458 CXXSpecialMemberKind getEffectiveCSM() {
9459 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9460 }
9461
9462 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9463
9464 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9465
9466 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9467 bool visitField(FieldDecl *Field) { return shouldDeleteForField(FD: Field); }
9468
9469 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9470 bool shouldDeleteForField(FieldDecl *FD);
9471 bool shouldDeleteForAllConstMembers();
9472
9473 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9474 unsigned Quals);
9475 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9476 Sema::SpecialMemberOverloadResult SMOR,
9477 bool IsDtorCallInCtor);
9478
9479 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9480};
9481}
9482
9483/// Is the given special member inaccessible when used on the given
9484/// sub-object.
9485bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9486 CXXMethodDecl *target) {
9487 /// If we're operating on a base class, the object type is the
9488 /// type of this special member.
9489 QualType objectTy;
9490 AccessSpecifier access = target->getAccess();
9491 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9492 objectTy = S.Context.getTypeDeclType(Decl: MD->getParent());
9493 access = CXXRecordDecl::MergeAccess(PathAccess: base->getAccessSpecifier(), DeclAccess: access);
9494
9495 // If we're operating on a field, the object type is the type of the field.
9496 } else {
9497 objectTy = S.Context.getTypeDeclType(Decl: target->getParent());
9498 }
9499
9500 return S.isMemberAccessibleForDeletion(
9501 NamingClass: target->getParent(), Found: DeclAccessPair::make(D: target, AS: access), ObjectType: objectTy);
9502}
9503
9504/// Check whether we should delete a special member due to the implicit
9505/// definition containing a call to a special member of a subobject.
9506bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9507 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9508 bool IsDtorCallInCtor) {
9509 CXXMethodDecl *Decl = SMOR.getMethod();
9510 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9511
9512 int DiagKind = -1;
9513
9514 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9515 DiagKind = !Decl ? 0 : 1;
9516 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9517 DiagKind = 2;
9518 else if (!isAccessible(Subobj, target: Decl))
9519 DiagKind = 3;
9520 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9521 !Decl->isTrivial()) {
9522 // A member of a union must have a trivial corresponding special member.
9523 // As a weird special case, a destructor call from a union's constructor
9524 // must be accessible and non-deleted, but need not be trivial. Such a
9525 // destructor is never actually called, but is semantically checked as
9526 // if it were.
9527 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9528 // [class.default.ctor]p2:
9529 // A defaulted default constructor for class X is defined as deleted if
9530 // - X is a union that has a variant member with a non-trivial default
9531 // constructor and no variant member of X has a default member
9532 // initializer
9533 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9534 if (!RD->hasInClassInitializer())
9535 DiagKind = 4;
9536 } else {
9537 DiagKind = 4;
9538 }
9539 }
9540
9541 if (DiagKind == -1)
9542 return false;
9543
9544 if (Diagnose) {
9545 if (Field) {
9546 S.Diag(Loc: Field->getLocation(),
9547 DiagID: diag::note_deleted_special_member_class_subobject)
9548 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9549 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9550 } else {
9551 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Val&: Subobj);
9552 S.Diag(Loc: Base->getBeginLoc(),
9553 DiagID: diag::note_deleted_special_member_class_subobject)
9554 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9555 << Base->getType() << DiagKind << IsDtorCallInCtor
9556 << /*IsObjCPtr*/ false;
9557 }
9558
9559 if (DiagKind == 1)
9560 S.NoteDeletedFunction(FD: Decl);
9561 // FIXME: Explain inaccessibility if DiagKind == 3.
9562 }
9563
9564 return true;
9565}
9566
9567/// Check whether we should delete a special member function due to having a
9568/// direct or virtual base class or non-static data member of class type M.
9569bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9570 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9571 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9572 bool IsMutable = Field && Field->isMutable();
9573
9574 // C++11 [class.ctor]p5:
9575 // -- any direct or virtual base class, or non-static data member with no
9576 // brace-or-equal-initializer, has class type M (or array thereof) and
9577 // either M has no default constructor or overload resolution as applied
9578 // to M's default constructor results in an ambiguity or in a function
9579 // that is deleted or inaccessible
9580 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9581 // -- a direct or virtual base class B that cannot be copied/moved because
9582 // overload resolution, as applied to B's corresponding special member,
9583 // results in an ambiguity or a function that is deleted or inaccessible
9584 // from the defaulted special member
9585 // C++11 [class.dtor]p5:
9586 // -- any direct or virtual base class [...] has a type with a destructor
9587 // that is deleted or inaccessible
9588 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9589 Field->hasInClassInitializer()) &&
9590 shouldDeleteForSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable),
9591 IsDtorCallInCtor: false))
9592 return true;
9593
9594 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9595 // -- any direct or virtual base class or non-static data member has a
9596 // type with a destructor that is deleted or inaccessible
9597 if (IsConstructor) {
9598 Sema::SpecialMemberOverloadResult SMOR =
9599 S.LookupSpecialMember(D: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false,
9600 VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false);
9601 if (shouldDeleteForSubobjectCall(Subobj, SMOR, IsDtorCallInCtor: true))
9602 return true;
9603 }
9604
9605 return false;
9606}
9607
9608bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9609 FieldDecl *FD, QualType FieldType) {
9610 // The defaulted special functions are defined as deleted if this is a variant
9611 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9612 // type under ARC.
9613 if (!FieldType.hasNonTrivialObjCLifetime())
9614 return false;
9615
9616 // Don't make the defaulted default constructor defined as deleted if the
9617 // member has an in-class initializer.
9618 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9619 FD->hasInClassInitializer())
9620 return false;
9621
9622 if (Diagnose) {
9623 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9624 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9625 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9626 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9627 }
9628
9629 return true;
9630}
9631
9632bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9633 const FieldDecl *FD) {
9634 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9635 // Copy/move constructors/assignment operators are deleted if the field has an
9636 // address-discriminated ptrauth qualifier.
9637 PointerAuthQualifier Q = FieldType.getPointerAuth();
9638
9639 if (!Q || !Q.isAddressDiscriminated())
9640 return false;
9641
9642 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9643 CSM == CXXSpecialMemberKind::Destructor)
9644 return false;
9645
9646 if (Diagnose) {
9647 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9648 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9649 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9650 << /*IsDtorCallInCtor*/ false << 2;
9651 }
9652
9653 return true;
9654}
9655
9656/// Check whether we should delete a special member function due to the class
9657/// having a particular direct or virtual base class.
9658bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9659 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9660 // If program is correct, BaseClass cannot be null, but if it is, the error
9661 // must be reported elsewhere.
9662 if (!BaseClass)
9663 return false;
9664 // If we have an inheriting constructor, check whether we're calling an
9665 // inherited constructor instead of a default constructor.
9666 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
9667 if (auto *BaseCtor = SMOR.getMethod()) {
9668 // Note that we do not check access along this path; other than that,
9669 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9670 // FIXME: Check that the base has a usable destructor! Sink this into
9671 // shouldDeleteForClassSubobject.
9672 if (BaseCtor->isDeleted() && Diagnose) {
9673 S.Diag(Loc: Base->getBeginLoc(),
9674 DiagID: diag::note_deleted_special_member_class_subobject)
9675 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9676 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9677 << /*IsObjCPtr*/ false;
9678 S.NoteDeletedFunction(FD: BaseCtor);
9679 }
9680 return BaseCtor->isDeleted();
9681 }
9682 return shouldDeleteForClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
9683}
9684
9685/// Check whether we should delete a special member function due to the class
9686/// having a particular non-static data member.
9687bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9688 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9689 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9690
9691 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9692 return true;
9693
9694 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9695 return true;
9696
9697 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9698 // For a default constructor, all references must be initialized in-class
9699 // and, if a union, it must have a non-const member.
9700 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9701 if (Diagnose)
9702 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9703 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9704 return true;
9705 }
9706 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9707 // data member of const-qualified type (or array thereof) with no
9708 // brace-or-equal-initializer is not const-default-constructible.
9709 if (!inUnion() && FieldType.isConstQualified() &&
9710 !FD->hasInClassInitializer() &&
9711 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9712 if (Diagnose)
9713 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9714 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9715 return true;
9716 }
9717
9718 if (inUnion() && !FieldType.isConstQualified())
9719 AllFieldsAreConst = false;
9720 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9721 // For a copy constructor, data members must not be of rvalue reference
9722 // type.
9723 if (FieldType->isRValueReferenceType()) {
9724 if (Diagnose)
9725 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_copy_ctor_rvalue_reference)
9726 << MD->getParent() << FD << FieldType;
9727 return true;
9728 }
9729 } else if (IsAssignment) {
9730 // For an assignment operator, data members must not be of reference type.
9731 if (FieldType->isReferenceType()) {
9732 if (Diagnose)
9733 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9734 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9735 return true;
9736 }
9737 if (!FieldRecord && FieldType.isConstQualified()) {
9738 // C++11 [class.copy]p23:
9739 // -- a non-static data member of const non-class type (or array thereof)
9740 if (Diagnose)
9741 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9742 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9743 return true;
9744 }
9745 }
9746
9747 if (FieldRecord) {
9748 // Some additional restrictions exist on the variant members.
9749 if (!inUnion() && FieldRecord->isUnion() &&
9750 FieldRecord->isAnonymousStructOrUnion()) {
9751 bool AllVariantFieldsAreConst = true;
9752
9753 // FIXME: Handle anonymous unions declared within anonymous unions.
9754 for (auto *UI : FieldRecord->fields()) {
9755 QualType UnionFieldType = S.Context.getBaseElementType(QT: UI->getType());
9756
9757 if (shouldDeleteForVariantObjCPtrMember(FD: &*UI, FieldType: UnionFieldType))
9758 return true;
9759
9760 if (shouldDeleteForVariantPtrAuthMember(FD: &*UI))
9761 return true;
9762
9763 if (!UnionFieldType.isConstQualified())
9764 AllVariantFieldsAreConst = false;
9765
9766 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9767 if (UnionFieldRecord &&
9768 shouldDeleteForClassSubobject(Class: UnionFieldRecord, Subobj: UI,
9769 Quals: UnionFieldType.getCVRQualifiers()))
9770 return true;
9771 }
9772
9773 // At least one member in each anonymous union must be non-const
9774 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9775 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9776 if (Diagnose)
9777 S.Diag(Loc: FieldRecord->getLocation(),
9778 DiagID: diag::note_deleted_default_ctor_all_const)
9779 << !!ICI << MD->getParent() << /*anonymous union*/1;
9780 return true;
9781 }
9782
9783 // Don't check the implicit member of the anonymous union type.
9784 // This is technically non-conformant but supported, and we have a
9785 // diagnostic for this elsewhere.
9786 return false;
9787 }
9788
9789 if (shouldDeleteForClassSubobject(Class: FieldRecord, Subobj: FD,
9790 Quals: FieldType.getCVRQualifiers()))
9791 return true;
9792 }
9793
9794 return false;
9795}
9796
9797/// C++11 [class.ctor] p5:
9798/// A defaulted default constructor for a class X is defined as deleted if
9799/// X is a union and all of its variant members are of const-qualified type.
9800bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9801 // This is a silly definition, because it gives an empty union a deleted
9802 // default constructor. Don't do that.
9803 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9804 AllFieldsAreConst) {
9805 bool AnyFields = false;
9806 for (auto *F : MD->getParent()->fields())
9807 if ((AnyFields = !F->isUnnamedBitField()))
9808 break;
9809 if (!AnyFields)
9810 return false;
9811 if (Diagnose)
9812 S.Diag(Loc: MD->getParent()->getLocation(),
9813 DiagID: diag::note_deleted_default_ctor_all_const)
9814 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9815 return true;
9816 }
9817 return false;
9818}
9819
9820/// Determine whether a defaulted special member function should be defined as
9821/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9822/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9823bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
9824 CXXSpecialMemberKind CSM,
9825 InheritedConstructorInfo *ICI,
9826 bool Diagnose) {
9827 if (MD->isInvalidDecl())
9828 return false;
9829 CXXRecordDecl *RD = MD->getParent();
9830 assert(!RD->isDependentType() && "do deletion after instantiation");
9831 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9832 RD->isInvalidDecl())
9833 return false;
9834
9835 // C++11 [expr.lambda.prim]p19:
9836 // The closure type associated with a lambda-expression has a
9837 // deleted (8.4.3) default constructor and a deleted copy
9838 // assignment operator.
9839 // C++2a adds back these operators if the lambda has no lambda-capture.
9840 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9841 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9842 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9843 if (Diagnose)
9844 Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
9845 return true;
9846 }
9847
9848 // For an anonymous struct or union, the copy and assignment special members
9849 // will never be used, so skip the check. For an anonymous union declared at
9850 // namespace scope, the constructor and destructor are used.
9851 if (CSM != CXXSpecialMemberKind::DefaultConstructor &&
9852 CSM != CXXSpecialMemberKind::Destructor && RD->isAnonymousStructOrUnion())
9853 return false;
9854
9855 // C++11 [class.copy]p7, p18:
9856 // If the class definition declares a move constructor or move assignment
9857 // operator, an implicitly declared copy constructor or copy assignment
9858 // operator is defined as deleted.
9859 if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
9860 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9861 CXXMethodDecl *UserDeclaredMove = nullptr;
9862
9863 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9864 // deletion of the corresponding copy operation, not both copy operations.
9865 // MSVC 2015 has adopted the standards conforming behavior.
9866 bool DeletesOnlyMatchingCopy =
9867 getLangOpts().MSVCCompat &&
9868 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
9869
9870 if (RD->hasUserDeclaredMoveConstructor() &&
9871 (!DeletesOnlyMatchingCopy ||
9872 CSM == CXXSpecialMemberKind::CopyConstructor)) {
9873 if (!Diagnose) return true;
9874
9875 // Find any user-declared move constructor.
9876 for (auto *I : RD->ctors()) {
9877 if (I->isMoveConstructor()) {
9878 UserDeclaredMove = I;
9879 break;
9880 }
9881 }
9882 assert(UserDeclaredMove);
9883 } else if (RD->hasUserDeclaredMoveAssignment() &&
9884 (!DeletesOnlyMatchingCopy ||
9885 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9886 if (!Diagnose) return true;
9887
9888 // Find any user-declared move assignment operator.
9889 for (auto *I : RD->methods()) {
9890 if (I->isMoveAssignmentOperator()) {
9891 UserDeclaredMove = I;
9892 break;
9893 }
9894 }
9895 assert(UserDeclaredMove);
9896 }
9897
9898 if (UserDeclaredMove) {
9899 Diag(Loc: UserDeclaredMove->getLocation(),
9900 DiagID: diag::note_deleted_copy_user_declared_move)
9901 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9902 << UserDeclaredMove->isMoveAssignmentOperator();
9903 return true;
9904 }
9905 }
9906
9907 // Do access control from the special member function
9908 ContextRAII MethodContext(*this, MD);
9909
9910 // C++11 [class.dtor]p5:
9911 // -- for a virtual destructor, lookup of the non-array deallocation function
9912 // results in an ambiguity or in a function that is deleted or inaccessible
9913 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9914 FunctionDecl *OperatorDelete = nullptr;
9915 QualType DeallocType = Context.getRecordType(Decl: RD);
9916 DeclarationName Name =
9917 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
9918 ImplicitDeallocationParameters IDP = {
9919 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
9920 AlignedAllocationMode::No, SizedDeallocationMode::No};
9921 if (FindDeallocationFunction(StartLoc: MD->getLocation(), RD: MD->getParent(), Name,
9922 Operator&: OperatorDelete, IDP,
9923 /*Diagnose=*/false)) {
9924 if (Diagnose)
9925 Diag(Loc: RD->getLocation(), DiagID: diag::note_deleted_dtor_no_operator_delete);
9926 return true;
9927 }
9928 }
9929
9930 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9931
9932 // Per DR1611, do not consider virtual bases of constructors of abstract
9933 // classes, since we are not going to construct them.
9934 // Per DR1658, do not consider virtual bases of destructors of abstract
9935 // classes either.
9936 // Per DR2180, for assignment operators we only assign (and thus only
9937 // consider) direct bases.
9938 if (SMI.visit(Bases: SMI.IsAssignment ? SMI.VisitDirectBases
9939 : SMI.VisitPotentiallyConstructedBases))
9940 return true;
9941
9942 if (SMI.shouldDeleteForAllConstMembers())
9943 return true;
9944
9945 if (getLangOpts().CUDA) {
9946 // We should delete the special member in CUDA mode if target inference
9947 // failed.
9948 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9949 // is treated as certain special member, which may not reflect what special
9950 // member MD really is. However inferTargetForImplicitSpecialMember
9951 // expects CSM to match MD, therefore recalculate CSM.
9952 assert(ICI || CSM == getSpecialMember(MD));
9953 auto RealCSM = CSM;
9954 if (ICI)
9955 RealCSM = getSpecialMember(MD);
9956
9957 return CUDA().inferTargetForImplicitSpecialMember(ClassDecl: RD, CSM: RealCSM, MemberDecl: MD,
9958 ConstRHS: SMI.ConstArg, Diagnose);
9959 }
9960
9961 return false;
9962}
9963
9964void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9965 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9966 assert(DFK && "not a defaultable function");
9967 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9968
9969 if (DFK.isSpecialMember()) {
9970 ShouldDeleteSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(),
9971 ICI: nullptr, /*Diagnose=*/true);
9972 } else {
9973 DefaultedComparisonAnalyzer(
9974 *this, cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()), FD,
9975 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9976 .visit();
9977 }
9978}
9979
9980/// Perform lookup for a special member of the specified kind, and determine
9981/// whether it is trivial. If the triviality can be determined without the
9982/// lookup, skip it. This is intended for use when determining whether a
9983/// special member of a containing object is trivial, and thus does not ever
9984/// perform overload resolution for default constructors.
9985///
9986/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9987/// member that was most likely to be intended to be trivial, if any.
9988///
9989/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9990/// determine whether the special member is trivial.
9991static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9992 CXXSpecialMemberKind CSM, unsigned Quals,
9993 bool ConstRHS, TrivialABIHandling TAH,
9994 CXXMethodDecl **Selected) {
9995 if (Selected)
9996 *Selected = nullptr;
9997
9998 switch (CSM) {
9999 case CXXSpecialMemberKind::Invalid:
10000 llvm_unreachable("not a special member");
10001
10002 case CXXSpecialMemberKind::DefaultConstructor:
10003 // C++11 [class.ctor]p5:
10004 // A default constructor is trivial if:
10005 // - all the [direct subobjects] have trivial default constructors
10006 //
10007 // Note, no overload resolution is performed in this case.
10008 if (RD->hasTrivialDefaultConstructor())
10009 return true;
10010
10011 if (Selected) {
10012 // If there's a default constructor which could have been trivial, dig it
10013 // out. Otherwise, if there's any user-provided default constructor, point
10014 // to that as an example of why there's not a trivial one.
10015 CXXConstructorDecl *DefCtor = nullptr;
10016 if (RD->needsImplicitDefaultConstructor())
10017 S.DeclareImplicitDefaultConstructor(ClassDecl: RD);
10018 for (auto *CI : RD->ctors()) {
10019 if (!CI->isDefaultConstructor())
10020 continue;
10021 DefCtor = CI;
10022 if (!DefCtor->isUserProvided())
10023 break;
10024 }
10025
10026 *Selected = DefCtor;
10027 }
10028
10029 return false;
10030
10031 case CXXSpecialMemberKind::Destructor:
10032 // C++11 [class.dtor]p5:
10033 // A destructor is trivial if:
10034 // - all the direct [subobjects] have trivial destructors
10035 if (RD->hasTrivialDestructor() ||
10036 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10037 RD->hasTrivialDestructorForCall()))
10038 return true;
10039
10040 if (Selected) {
10041 if (RD->needsImplicitDestructor())
10042 S.DeclareImplicitDestructor(ClassDecl: RD);
10043 *Selected = RD->getDestructor();
10044 }
10045
10046 return false;
10047
10048 case CXXSpecialMemberKind::CopyConstructor:
10049 // C++11 [class.copy]p12:
10050 // A copy constructor is trivial if:
10051 // - the constructor selected to copy each direct [subobject] is trivial
10052 if (RD->hasTrivialCopyConstructor() ||
10053 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10054 RD->hasTrivialCopyConstructorForCall())) {
10055 if (Quals == Qualifiers::Const)
10056 // We must either select the trivial copy constructor or reach an
10057 // ambiguity; no need to actually perform overload resolution.
10058 return true;
10059 } else if (!Selected) {
10060 return false;
10061 }
10062 // In C++98, we are not supposed to perform overload resolution here, but we
10063 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10064 // cases like B as having a non-trivial copy constructor:
10065 // struct A { template<typename T> A(T&); };
10066 // struct B { mutable A a; };
10067 goto NeedOverloadResolution;
10068
10069 case CXXSpecialMemberKind::CopyAssignment:
10070 // C++11 [class.copy]p25:
10071 // A copy assignment operator is trivial if:
10072 // - the assignment operator selected to copy each direct [subobject] is
10073 // trivial
10074 if (RD->hasTrivialCopyAssignment()) {
10075 if (Quals == Qualifiers::Const)
10076 return true;
10077 } else if (!Selected) {
10078 return false;
10079 }
10080 // In C++98, we are not supposed to perform overload resolution here, but we
10081 // treat that as a language defect.
10082 goto NeedOverloadResolution;
10083
10084 case CXXSpecialMemberKind::MoveConstructor:
10085 case CXXSpecialMemberKind::MoveAssignment:
10086 NeedOverloadResolution:
10087 Sema::SpecialMemberOverloadResult SMOR =
10088 lookupCallFromSpecialMember(S, Class: RD, CSM, FieldQuals: Quals, ConstRHS);
10089
10090 // The standard doesn't describe how to behave if the lookup is ambiguous.
10091 // We treat it as not making the member non-trivial, just like the standard
10092 // mandates for the default constructor. This should rarely matter, because
10093 // the member will also be deleted.
10094 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10095 return true;
10096
10097 if (!SMOR.getMethod()) {
10098 assert(SMOR.getKind() ==
10099 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
10100 return false;
10101 }
10102
10103 // We deliberately don't check if we found a deleted special member. We're
10104 // not supposed to!
10105 if (Selected)
10106 *Selected = SMOR.getMethod();
10107
10108 if (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10109 (CSM == CXXSpecialMemberKind::CopyConstructor ||
10110 CSM == CXXSpecialMemberKind::MoveConstructor))
10111 return SMOR.getMethod()->isTrivialForCall();
10112 return SMOR.getMethod()->isTrivial();
10113 }
10114
10115 llvm_unreachable("unknown special method kind");
10116}
10117
10118static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10119 for (auto *CI : RD->ctors())
10120 if (!CI->isImplicit())
10121 return CI;
10122
10123 // Look for constructor templates.
10124 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10125 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10126 if (CXXConstructorDecl *CD =
10127 dyn_cast<CXXConstructorDecl>(Val: TI->getTemplatedDecl()))
10128 return CD;
10129 }
10130
10131 return nullptr;
10132}
10133
10134/// The kind of subobject we are checking for triviality. The values of this
10135/// enumeration are used in diagnostics.
10136enum TrivialSubobjectKind {
10137 /// The subobject is a base class.
10138 TSK_BaseClass,
10139 /// The subobject is a non-static data member.
10140 TSK_Field,
10141 /// The object is actually the complete object.
10142 TSK_CompleteObject
10143};
10144
10145/// Check whether the special member selected for a given type would be trivial.
10146static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10147 QualType SubType, bool ConstRHS,
10148 CXXSpecialMemberKind CSM,
10149 TrivialSubobjectKind Kind,
10150 TrivialABIHandling TAH, bool Diagnose) {
10151 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10152 if (!SubRD)
10153 return true;
10154
10155 CXXMethodDecl *Selected;
10156 if (findTrivialSpecialMember(S, RD: SubRD, CSM, Quals: SubType.getCVRQualifiers(),
10157 ConstRHS, TAH, Selected: Diagnose ? &Selected : nullptr))
10158 return true;
10159
10160 if (Diagnose) {
10161 if (ConstRHS)
10162 SubType.addConst();
10163
10164 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10165 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_def_ctor)
10166 << Kind << SubType.getUnqualifiedType();
10167 if (CXXConstructorDecl *CD = findUserDeclaredCtor(RD: SubRD))
10168 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_user_declared_ctor);
10169 } else if (!Selected)
10170 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_copy)
10171 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10172 else if (Selected->isUserProvided()) {
10173 if (Kind == TSK_CompleteObject)
10174 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_nontrivial_user_provided)
10175 << Kind << SubType.getUnqualifiedType() << CSM;
10176 else {
10177 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_user_provided)
10178 << Kind << SubType.getUnqualifiedType() << CSM;
10179 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_declared_at);
10180 }
10181 } else {
10182 if (Kind != TSK_CompleteObject)
10183 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_subobject)
10184 << Kind << SubType.getUnqualifiedType() << CSM;
10185
10186 // Explain why the defaulted or deleted special member isn't trivial.
10187 S.SpecialMemberIsTrivial(MD: Selected, CSM,
10188 TAH: TrivialABIHandling::IgnoreTrivialABI, Diagnose);
10189 }
10190 }
10191
10192 return false;
10193}
10194
10195/// Check whether the members of a class type allow a special member to be
10196/// trivial.
10197static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10198 CXXSpecialMemberKind CSM, bool ConstArg,
10199 TrivialABIHandling TAH, bool Diagnose) {
10200 for (const auto *FI : RD->fields()) {
10201 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10202 continue;
10203
10204 QualType FieldType = S.Context.getBaseElementType(QT: FI->getType());
10205
10206 // Pretend anonymous struct or union members are members of this class.
10207 if (FI->isAnonymousStructOrUnion()) {
10208 if (!checkTrivialClassMembers(S, RD: FieldType->getAsCXXRecordDecl(),
10209 CSM, ConstArg, TAH, Diagnose))
10210 return false;
10211 continue;
10212 }
10213
10214 // C++11 [class.ctor]p5:
10215 // A default constructor is trivial if [...]
10216 // -- no non-static data member of its class has a
10217 // brace-or-equal-initializer
10218 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10219 FI->hasInClassInitializer()) {
10220 if (Diagnose)
10221 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_default_member_init)
10222 << FI;
10223 return false;
10224 }
10225
10226 // Objective C ARC 4.3.5:
10227 // [...] nontrivally ownership-qualified types are [...] not trivially
10228 // default constructible, copy constructible, move constructible, copy
10229 // assignable, move assignable, or destructible [...]
10230 if (FieldType.hasNonTrivialObjCLifetime()) {
10231 if (Diagnose)
10232 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_objc_ownership)
10233 << RD << FieldType.getObjCLifetime();
10234 return false;
10235 }
10236
10237 bool ConstRHS = ConstArg && !FI->isMutable();
10238 if (!checkTrivialSubobjectCall(S, SubobjLoc: FI->getLocation(), SubType: FieldType, ConstRHS,
10239 CSM, Kind: TSK_Field, TAH, Diagnose))
10240 return false;
10241 }
10242
10243 return true;
10244}
10245
10246void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10247 CXXSpecialMemberKind CSM) {
10248 QualType Ty = Context.getRecordType(Decl: RD);
10249
10250 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10251 CSM == CXXSpecialMemberKind::CopyAssignment);
10252 checkTrivialSubobjectCall(S&: *this, SubobjLoc: RD->getLocation(), SubType: Ty, ConstRHS: ConstArg, CSM,
10253 Kind: TSK_CompleteObject,
10254 TAH: TrivialABIHandling::IgnoreTrivialABI,
10255 /*Diagnose*/ true);
10256}
10257
10258bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10259 TrivialABIHandling TAH, bool Diagnose) {
10260 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10261 "not special enough");
10262
10263 CXXRecordDecl *RD = MD->getParent();
10264
10265 bool ConstArg = false;
10266
10267 // C++11 [class.copy]p12, p25: [DR1593]
10268 // A [special member] is trivial if [...] its parameter-type-list is
10269 // equivalent to the parameter-type-list of an implicit declaration [...]
10270 switch (CSM) {
10271 case CXXSpecialMemberKind::DefaultConstructor:
10272 case CXXSpecialMemberKind::Destructor:
10273 // Trivial default constructors and destructors cannot have parameters.
10274 break;
10275
10276 case CXXSpecialMemberKind::CopyConstructor:
10277 case CXXSpecialMemberKind::CopyAssignment: {
10278 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10279 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10280
10281 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10282 // if they are not user-provided and their parameter-type-list is equivalent
10283 // to the parameter-type-list of an implicit declaration. This maintains the
10284 // behavior before dr2171 was implemented.
10285 //
10286 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10287 // trivial, if they are not user-provided, regardless of the qualifiers on
10288 // the reference type.
10289 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10290 LangOptions::ClangABI::Ver14;
10291 if (!RT ||
10292 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10293 ClangABICompat14)) {
10294 if (Diagnose)
10295 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10296 << Param0->getSourceRange() << Param0->getType()
10297 << Context.getLValueReferenceType(
10298 T: Context.getRecordType(Decl: RD).withConst());
10299 return false;
10300 }
10301
10302 ConstArg = RT->getPointeeType().isConstQualified();
10303 break;
10304 }
10305
10306 case CXXSpecialMemberKind::MoveConstructor:
10307 case CXXSpecialMemberKind::MoveAssignment: {
10308 // Trivial move operations always have non-cv-qualified parameters.
10309 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10310 const RValueReferenceType *RT =
10311 Param0->getType()->getAs<RValueReferenceType>();
10312 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10313 if (Diagnose)
10314 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10315 << Param0->getSourceRange() << Param0->getType()
10316 << Context.getRValueReferenceType(T: Context.getRecordType(Decl: RD));
10317 return false;
10318 }
10319 break;
10320 }
10321
10322 case CXXSpecialMemberKind::Invalid:
10323 llvm_unreachable("not a special member");
10324 }
10325
10326 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10327 if (Diagnose)
10328 Diag(Loc: MD->getParamDecl(i: MD->getMinRequiredArguments())->getLocation(),
10329 DiagID: diag::note_nontrivial_default_arg)
10330 << MD->getParamDecl(i: MD->getMinRequiredArguments())->getSourceRange();
10331 return false;
10332 }
10333 if (MD->isVariadic()) {
10334 if (Diagnose)
10335 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_variadic);
10336 return false;
10337 }
10338
10339 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10340 // A copy/move [constructor or assignment operator] is trivial if
10341 // -- the [member] selected to copy/move each direct base class subobject
10342 // is trivial
10343 //
10344 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10345 // A [default constructor or destructor] is trivial if
10346 // -- all the direct base classes have trivial [default constructors or
10347 // destructors]
10348 for (const auto &BI : RD->bases())
10349 if (!checkTrivialSubobjectCall(S&: *this, SubobjLoc: BI.getBeginLoc(), SubType: BI.getType(),
10350 ConstRHS: ConstArg, CSM, Kind: TSK_BaseClass, TAH, Diagnose))
10351 return false;
10352
10353 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10354 // A copy/move [constructor or assignment operator] for a class X is
10355 // trivial if
10356 // -- for each non-static data member of X that is of class type (or array
10357 // thereof), the constructor selected to copy/move that member is
10358 // trivial
10359 //
10360 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10361 // A [default constructor or destructor] is trivial if
10362 // -- for all of the non-static data members of its class that are of class
10363 // type (or array thereof), each such class has a trivial [default
10364 // constructor or destructor]
10365 if (!checkTrivialClassMembers(S&: *this, RD, CSM, ConstArg, TAH, Diagnose))
10366 return false;
10367
10368 // C++11 [class.dtor]p5:
10369 // A destructor is trivial if [...]
10370 // -- the destructor is not virtual
10371 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10372 if (Diagnose)
10373 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_virtual_dtor) << RD;
10374 return false;
10375 }
10376
10377 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10378 // A [special member] for class X is trivial if [...]
10379 // -- class X has no virtual functions and no virtual base classes
10380 if (CSM != CXXSpecialMemberKind::Destructor &&
10381 MD->getParent()->isDynamicClass()) {
10382 if (!Diagnose)
10383 return false;
10384
10385 if (RD->getNumVBases()) {
10386 // Check for virtual bases. We already know that the corresponding
10387 // member in all bases is trivial, so vbases must all be direct.
10388 CXXBaseSpecifier &BS = *RD->vbases_begin();
10389 assert(BS.isVirtual());
10390 Diag(Loc: BS.getBeginLoc(), DiagID: diag::note_nontrivial_has_virtual) << RD << 1;
10391 return false;
10392 }
10393
10394 // Must have a virtual method.
10395 for (const auto *MI : RD->methods()) {
10396 if (MI->isVirtual()) {
10397 SourceLocation MLoc = MI->getBeginLoc();
10398 Diag(Loc: MLoc, DiagID: diag::note_nontrivial_has_virtual) << RD << 0;
10399 return false;
10400 }
10401 }
10402
10403 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10404 }
10405
10406 // Looks like it's trivial!
10407 return true;
10408}
10409
10410namespace {
10411struct FindHiddenVirtualMethod {
10412 Sema *S;
10413 CXXMethodDecl *Method;
10414 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10415 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10416
10417private:
10418 /// Check whether any most overridden method from MD in Methods
10419 static bool CheckMostOverridenMethods(
10420 const CXXMethodDecl *MD,
10421 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10422 if (MD->size_overridden_methods() == 0)
10423 return Methods.count(Ptr: MD->getCanonicalDecl());
10424 for (const CXXMethodDecl *O : MD->overridden_methods())
10425 if (CheckMostOverridenMethods(MD: O, Methods))
10426 return true;
10427 return false;
10428 }
10429
10430public:
10431 /// Member lookup function that determines whether a given C++
10432 /// method overloads virtual methods in a base class without overriding any,
10433 /// to be used with CXXRecordDecl::lookupInBases().
10434 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10435 RecordDecl *BaseRecord =
10436 Specifier->getType()->castAs<RecordType>()->getDecl();
10437
10438 DeclarationName Name = Method->getDeclName();
10439 assert(Name.getNameKind() == DeclarationName::Identifier);
10440
10441 bool foundSameNameMethod = false;
10442 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10443 for (Path.Decls = BaseRecord->lookup(Name).begin();
10444 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10445 NamedDecl *D = *Path.Decls;
10446 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
10447 MD = MD->getCanonicalDecl();
10448 foundSameNameMethod = true;
10449 // Interested only in hidden virtual methods.
10450 if (!MD->isVirtual())
10451 continue;
10452 // If the method we are checking overrides a method from its base
10453 // don't warn about the other overloaded methods. Clang deviates from
10454 // GCC by only diagnosing overloads of inherited virtual functions that
10455 // do not override any other virtual functions in the base. GCC's
10456 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10457 // function from a base class. These cases may be better served by a
10458 // warning (not specific to virtual functions) on call sites when the
10459 // call would select a different function from the base class, were it
10460 // visible.
10461 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10462 if (!S->IsOverload(New: Method, Old: MD, UseMemberUsingDeclRules: false))
10463 return true;
10464 // Collect the overload only if its hidden.
10465 if (!CheckMostOverridenMethods(MD, Methods: OverridenAndUsingBaseMethods))
10466 overloadedMethods.push_back(Elt: MD);
10467 }
10468 }
10469
10470 if (foundSameNameMethod)
10471 OverloadedMethods.append(in_start: overloadedMethods.begin(),
10472 in_end: overloadedMethods.end());
10473 return foundSameNameMethod;
10474 }
10475};
10476} // end anonymous namespace
10477
10478/// Add the most overridden methods from MD to Methods
10479static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10480 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10481 if (MD->size_overridden_methods() == 0)
10482 Methods.insert(Ptr: MD->getCanonicalDecl());
10483 else
10484 for (const CXXMethodDecl *O : MD->overridden_methods())
10485 AddMostOverridenMethods(MD: O, Methods);
10486}
10487
10488void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10489 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10490 if (!MD->getDeclName().isIdentifier())
10491 return;
10492
10493 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10494 /*bool RecordPaths=*/false,
10495 /*bool DetectVirtual=*/false);
10496 FindHiddenVirtualMethod FHVM;
10497 FHVM.Method = MD;
10498 FHVM.S = this;
10499
10500 // Keep the base methods that were overridden or introduced in the subclass
10501 // by 'using' in a set. A base method not in this set is hidden.
10502 CXXRecordDecl *DC = MD->getParent();
10503 DeclContext::lookup_result R = DC->lookup(Name: MD->getDeclName());
10504 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10505 NamedDecl *ND = *I;
10506 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(Val: *I))
10507 ND = shad->getTargetDecl();
10508 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ND))
10509 AddMostOverridenMethods(MD, Methods&: FHVM.OverridenAndUsingBaseMethods);
10510 }
10511
10512 if (DC->lookupInBases(BaseMatches: FHVM, Paths))
10513 OverloadedMethods = FHVM.OverloadedMethods;
10514}
10515
10516void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10517 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10518 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10519 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10520 PartialDiagnostic PD = PDiag(
10521 DiagID: diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10522 HandleFunctionTypeMismatch(PDiag&: PD, FromType: MD->getType(), ToType: overloadedMD->getType());
10523 Diag(Loc: overloadedMD->getLocation(), PD);
10524 }
10525}
10526
10527void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10528 if (MD->isInvalidDecl())
10529 return;
10530
10531 if (Diags.isIgnored(DiagID: diag::warn_overloaded_virtual, Loc: MD->getLocation()))
10532 return;
10533
10534 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10535 FindHiddenVirtualMethods(MD, OverloadedMethods);
10536 if (!OverloadedMethods.empty()) {
10537 Diag(Loc: MD->getLocation(), DiagID: diag::warn_overloaded_virtual)
10538 << MD << (OverloadedMethods.size() > 1);
10539
10540 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10541 }
10542}
10543
10544void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10545 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10546 // No diagnostics if this is a template instantiation.
10547 if (!isTemplateInstantiation(Kind: RD.getTemplateSpecializationKind())) {
10548 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10549 DiagID: diag::ext_cannot_use_trivial_abi) << &RD;
10550 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10551 DiagID: diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10552 }
10553 RD.dropAttr<TrivialABIAttr>();
10554 };
10555
10556 // Ill-formed if the struct has virtual functions.
10557 if (RD.isPolymorphic()) {
10558 PrintDiagAndRemoveAttr(1);
10559 return;
10560 }
10561
10562 for (const auto &B : RD.bases()) {
10563 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10564 // virtual base.
10565 if (!B.getType()->isDependentType() &&
10566 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10567 PrintDiagAndRemoveAttr(2);
10568 return;
10569 }
10570
10571 if (B.isVirtual()) {
10572 PrintDiagAndRemoveAttr(3);
10573 return;
10574 }
10575 }
10576
10577 for (const auto *FD : RD.fields()) {
10578 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10579 // non-trivial for the purpose of calls.
10580 QualType FT = FD->getType();
10581 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10582 PrintDiagAndRemoveAttr(4);
10583 return;
10584 }
10585
10586 // Ill-formed if the field is an address-discriminated value.
10587 if (FT.hasAddressDiscriminatedPointerAuth()) {
10588 PrintDiagAndRemoveAttr(6);
10589 return;
10590 }
10591
10592 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10593 if (!RT->isDependentType() &&
10594 !cast<CXXRecordDecl>(Val: RT->getDecl())->canPassInRegisters()) {
10595 PrintDiagAndRemoveAttr(5);
10596 return;
10597 }
10598 }
10599
10600 if (IsCXXTriviallyRelocatableType(RD))
10601 return;
10602
10603 // Ill-formed if the copy and move constructors are deleted.
10604 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10605 // If the type is dependent, then assume it might have
10606 // implicit copy or move ctor because we won't know yet at this point.
10607 if (RD.isDependentType())
10608 return true;
10609 if (RD.needsImplicitCopyConstructor() &&
10610 !RD.defaultedCopyConstructorIsDeleted())
10611 return true;
10612 if (RD.needsImplicitMoveConstructor() &&
10613 !RD.defaultedMoveConstructorIsDeleted())
10614 return true;
10615 for (const CXXConstructorDecl *CD : RD.ctors())
10616 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10617 return true;
10618 return false;
10619 };
10620
10621 if (!HasNonDeletedCopyOrMoveConstructor()) {
10622 PrintDiagAndRemoveAttr(0);
10623 return;
10624 }
10625}
10626
10627void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
10628 CXXRecordDecl &RD) {
10629 if (RequireCompleteType(Loc: RD.getLocation(), T: Context.getRecordType(Decl: &RD),
10630 DiagID: diag::err_incomplete_type_vtable_pointer_auth))
10631 return;
10632
10633 const CXXRecordDecl *PrimaryBase = &RD;
10634 if (PrimaryBase->hasAnyDependentBases())
10635 return;
10636
10637 while (1) {
10638 assert(PrimaryBase);
10639 const CXXRecordDecl *Base = nullptr;
10640 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10641 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10642 continue;
10643 Base = BasePtr.getType()->getAsCXXRecordDecl();
10644 break;
10645 }
10646 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10647 break;
10648 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10649 DiagID: diag::err_non_top_level_vtable_pointer_auth)
10650 << &RD << Base;
10651 PrimaryBase = Base;
10652 }
10653
10654 if (!RD.isPolymorphic())
10655 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10656 DiagID: diag::err_non_polymorphic_vtable_pointer_auth)
10657 << &RD;
10658}
10659
10660void Sema::ActOnFinishCXXMemberSpecification(
10661 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10662 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10663 if (!TagDecl)
10664 return;
10665
10666 AdjustDeclIfTemplate(Decl&: TagDecl);
10667
10668 for (const ParsedAttr &AL : AttrList) {
10669 if (AL.getKind() != ParsedAttr::AT_Visibility)
10670 continue;
10671 AL.setInvalid();
10672 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_after_definition_ignored) << AL;
10673 }
10674
10675 ActOnFields(S, RecLoc: RLoc, TagDecl,
10676 Fields: llvm::ArrayRef(
10677 // strict aliasing violation!
10678 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10679 FieldCollector->getCurNumFields()),
10680 LBrac, RBrac, AttrList);
10681
10682 CheckCompletedCXXClass(S, Record: cast<CXXRecordDecl>(Val: TagDecl));
10683}
10684
10685/// Find the equality comparison functions that should be implicitly declared
10686/// in a given class definition, per C++2a [class.compare.default]p3.
10687static void findImplicitlyDeclaredEqualityComparisons(
10688 ASTContext &Ctx, CXXRecordDecl *RD,
10689 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10690 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual);
10691 if (!RD->lookup(Name: EqEq).empty())
10692 // Member operator== explicitly declared: no implicit operator==s.
10693 return;
10694
10695 // Traverse friends looking for an '==' or a '<=>'.
10696 for (FriendDecl *Friend : RD->friends()) {
10697 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Friend->getFriendDecl());
10698 if (!FD) continue;
10699
10700 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10701 // Friend operator== explicitly declared: no implicit operator==s.
10702 Spaceships.clear();
10703 return;
10704 }
10705
10706 if (FD->getOverloadedOperator() == OO_Spaceship &&
10707 FD->isExplicitlyDefaulted())
10708 Spaceships.push_back(Elt: FD);
10709 }
10710
10711 // Look for members named 'operator<=>'.
10712 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_Spaceship);
10713 for (NamedDecl *ND : RD->lookup(Name: Cmp)) {
10714 // Note that we could find a non-function here (either a function template
10715 // or a using-declaration). Neither case results in an implicit
10716 // 'operator=='.
10717 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
10718 if (FD->isExplicitlyDefaulted())
10719 Spaceships.push_back(Elt: FD);
10720 }
10721}
10722
10723void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10724 // Don't add implicit special members to templated classes.
10725 // FIXME: This means unqualified lookups for 'operator=' within a class
10726 // template don't work properly.
10727 if (!ClassDecl->isDependentType()) {
10728 if (ClassDecl->needsImplicitDefaultConstructor()) {
10729 ++getASTContext().NumImplicitDefaultConstructors;
10730
10731 if (ClassDecl->hasInheritedConstructor())
10732 DeclareImplicitDefaultConstructor(ClassDecl);
10733 }
10734
10735 if (ClassDecl->needsImplicitCopyConstructor()) {
10736 ++getASTContext().NumImplicitCopyConstructors;
10737
10738 // If the properties or semantics of the copy constructor couldn't be
10739 // determined while the class was being declared, force a declaration
10740 // of it now.
10741 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10742 ClassDecl->hasInheritedConstructor())
10743 DeclareImplicitCopyConstructor(ClassDecl);
10744 // For the MS ABI we need to know whether the copy ctor is deleted. A
10745 // prerequisite for deleting the implicit copy ctor is that the class has
10746 // a move ctor or move assignment that is either user-declared or whose
10747 // semantics are inherited from a subobject. FIXME: We should provide a
10748 // more direct way for CodeGen to ask whether the constructor was deleted.
10749 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10750 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10751 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10752 ClassDecl->hasUserDeclaredMoveAssignment() ||
10753 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10754 DeclareImplicitCopyConstructor(ClassDecl);
10755 }
10756
10757 if (getLangOpts().CPlusPlus11 &&
10758 ClassDecl->needsImplicitMoveConstructor()) {
10759 ++getASTContext().NumImplicitMoveConstructors;
10760
10761 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10762 ClassDecl->hasInheritedConstructor())
10763 DeclareImplicitMoveConstructor(ClassDecl);
10764 }
10765
10766 if (ClassDecl->needsImplicitCopyAssignment()) {
10767 ++getASTContext().NumImplicitCopyAssignmentOperators;
10768
10769 // If we have a dynamic class, then the copy assignment operator may be
10770 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10771 // it shows up in the right place in the vtable and that we diagnose
10772 // problems with the implicit exception specification.
10773 if (ClassDecl->isDynamicClass() ||
10774 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10775 ClassDecl->hasInheritedAssignment())
10776 DeclareImplicitCopyAssignment(ClassDecl);
10777 }
10778
10779 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10780 ++getASTContext().NumImplicitMoveAssignmentOperators;
10781
10782 // Likewise for the move assignment operator.
10783 if (ClassDecl->isDynamicClass() ||
10784 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10785 ClassDecl->hasInheritedAssignment())
10786 DeclareImplicitMoveAssignment(ClassDecl);
10787 }
10788
10789 if (ClassDecl->needsImplicitDestructor()) {
10790 ++getASTContext().NumImplicitDestructors;
10791
10792 // If we have a dynamic class, then the destructor may be virtual, so we
10793 // have to declare the destructor immediately. This ensures that, e.g., it
10794 // shows up in the right place in the vtable and that we diagnose problems
10795 // with the implicit exception specification.
10796 if (ClassDecl->isDynamicClass() ||
10797 ClassDecl->needsOverloadResolutionForDestructor())
10798 DeclareImplicitDestructor(ClassDecl);
10799 }
10800 }
10801
10802 // C++2a [class.compare.default]p3:
10803 // If the member-specification does not explicitly declare any member or
10804 // friend named operator==, an == operator function is declared implicitly
10805 // for each defaulted three-way comparison operator function defined in
10806 // the member-specification
10807 // FIXME: Consider doing this lazily.
10808 // We do this during the initial parse for a class template, not during
10809 // instantiation, so that we can handle unqualified lookups for 'operator=='
10810 // when parsing the template.
10811 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10812 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10813 findImplicitlyDeclaredEqualityComparisons(Ctx&: Context, RD: ClassDecl,
10814 Spaceships&: DefaultedSpaceships);
10815 for (auto *FD : DefaultedSpaceships)
10816 DeclareImplicitEqualityComparison(RD: ClassDecl, Spaceship: FD);
10817 }
10818}
10819
10820unsigned
10821Sema::ActOnReenterTemplateScope(Decl *D,
10822 llvm::function_ref<Scope *()> EnterScope) {
10823 if (!D)
10824 return 0;
10825 AdjustDeclIfTemplate(Decl&: D);
10826
10827 // In order to get name lookup right, reenter template scopes in order from
10828 // outermost to innermost.
10829 SmallVector<TemplateParameterList *, 4> ParameterLists;
10830 DeclContext *LookupDC = dyn_cast<DeclContext>(Val: D);
10831
10832 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
10833 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10834 ParameterLists.push_back(Elt: DD->getTemplateParameterList(index: i));
10835
10836 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
10837 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10838 ParameterLists.push_back(Elt: FTD->getTemplateParameters());
10839 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
10840 LookupDC = VD->getDeclContext();
10841
10842 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10843 ParameterLists.push_back(Elt: VTD->getTemplateParameters());
10844 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D))
10845 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
10846 }
10847 } else if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
10848 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10849 ParameterLists.push_back(Elt: TD->getTemplateParameterList(i));
10850
10851 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TD)) {
10852 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10853 ParameterLists.push_back(Elt: CTD->getTemplateParameters());
10854 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D))
10855 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
10856 }
10857 }
10858 // FIXME: Alias declarations and concepts.
10859
10860 unsigned Count = 0;
10861 Scope *InnermostTemplateScope = nullptr;
10862 for (TemplateParameterList *Params : ParameterLists) {
10863 // Ignore explicit specializations; they don't contribute to the template
10864 // depth.
10865 if (Params->size() == 0)
10866 continue;
10867
10868 InnermostTemplateScope = EnterScope();
10869 for (NamedDecl *Param : *Params) {
10870 if (Param->getDeclName()) {
10871 InnermostTemplateScope->AddDecl(D: Param);
10872 IdResolver.AddDecl(D: Param);
10873 }
10874 }
10875 ++Count;
10876 }
10877
10878 // Associate the new template scopes with the corresponding entities.
10879 if (InnermostTemplateScope) {
10880 assert(LookupDC && "no enclosing DeclContext for template lookup");
10881 EnterTemplatedContext(S: InnermostTemplateScope, DC: LookupDC);
10882 }
10883
10884 return Count;
10885}
10886
10887void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10888 if (!RecordD) return;
10889 AdjustDeclIfTemplate(Decl&: RecordD);
10890 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: RecordD);
10891 PushDeclContext(S, DC: Record);
10892}
10893
10894void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10895 if (!RecordD) return;
10896 PopDeclContext();
10897}
10898
10899void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10900 if (!Param)
10901 return;
10902
10903 S->AddDecl(D: Param);
10904 if (Param->getDeclName())
10905 IdResolver.AddDecl(D: Param);
10906}
10907
10908void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10909}
10910
10911/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10912/// C++ method declaration. We're (re-)introducing the given
10913/// function parameter into scope for use in parsing later parts of
10914/// the method declaration. For example, we could see an
10915/// ActOnParamDefaultArgument event for this parameter.
10916void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10917 if (!ParamD)
10918 return;
10919
10920 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamD);
10921
10922 S->AddDecl(D: Param);
10923 if (Param->getDeclName())
10924 IdResolver.AddDecl(D: Param);
10925}
10926
10927void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10928 if (!MethodD)
10929 return;
10930
10931 AdjustDeclIfTemplate(Decl&: MethodD);
10932
10933 FunctionDecl *Method = cast<FunctionDecl>(Val: MethodD);
10934
10935 // Now that we have our default arguments, check the constructor
10936 // again. It could produce additional diagnostics or affect whether
10937 // the class has implicitly-declared destructors, among other
10938 // things.
10939 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method))
10940 CheckConstructor(Constructor);
10941
10942 // Check the default arguments, which we may have added.
10943 if (!Method->isInvalidDecl())
10944 CheckCXXDefaultArguments(FD: Method);
10945}
10946
10947// Emit the given diagnostic for each non-address-space qualifier.
10948// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10949static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10950 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10951 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10952 bool DiagOccured = false;
10953 FTI.MethodQualifiers->forEachQualifier(
10954 Handle: [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10955 SourceLocation SL) {
10956 // This diagnostic should be emitted on any qualifier except an addr
10957 // space qualifier. However, forEachQualifier currently doesn't visit
10958 // addr space qualifiers, so there's no way to write this condition
10959 // right now; we just diagnose on everything.
10960 S.Diag(Loc: SL, DiagID) << QualName << SourceRange(SL);
10961 DiagOccured = true;
10962 });
10963 if (DiagOccured)
10964 D.setInvalidType();
10965 }
10966}
10967
10968static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,
10969 unsigned Kind) {
10970 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
10971 return;
10972
10973 DeclaratorChunk &Chunk = D.getTypeObject(i: D.getNumTypeObjects() - 1);
10974 if (Chunk.Kind == DeclaratorChunk::Paren ||
10975 Chunk.Kind == DeclaratorChunk::Function)
10976 return;
10977
10978 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
10979 S.Diag(Loc: PointerLoc, DiagID: diag::err_invalid_ctor_dtor_decl)
10980 << Kind << Chunk.getSourceRange();
10981 D.setInvalidType();
10982}
10983
10984QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10985 StorageClass &SC) {
10986 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10987
10988 // C++ [class.ctor]p3:
10989 // A constructor shall not be virtual (10.3) or static (9.4). A
10990 // constructor can be invoked for a const, volatile or const
10991 // volatile object. A constructor shall not be declared const,
10992 // volatile, or const volatile (9.3.2).
10993 if (isVirtual) {
10994 if (!D.isInvalidType())
10995 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
10996 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10997 << SourceRange(D.getIdentifierLoc());
10998 D.setInvalidType();
10999 }
11000 if (SC == SC_Static) {
11001 if (!D.isInvalidType())
11002 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11003 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11004 << SourceRange(D.getIdentifierLoc());
11005 D.setInvalidType();
11006 SC = SC_None;
11007 }
11008
11009 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11010 diagnoseIgnoredQualifiers(
11011 DiagID: diag::err_constructor_return_type, Quals: TypeQuals, FallbackLoc: SourceLocation(),
11012 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(), VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11013 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11014 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11015 D.setInvalidType();
11016 }
11017
11018 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_constructor);
11019 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*constructor*/ Kind: 0);
11020
11021 // C++0x [class.ctor]p4:
11022 // A constructor shall not be declared with a ref-qualifier.
11023 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11024 if (FTI.hasRefQualifier()) {
11025 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_constructor)
11026 << FTI.RefQualifierIsLValueRef
11027 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11028 D.setInvalidType();
11029 }
11030
11031 // Rebuild the function type "R" without any type qualifiers (in
11032 // case any of the errors above fired) and with "void" as the
11033 // return type, since constructors don't have return types.
11034 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11035 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11036 return R;
11037
11038 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11039 EPI.TypeQuals = Qualifiers();
11040 EPI.RefQualifier = RQ_None;
11041
11042 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: Proto->getParamTypes(), EPI);
11043}
11044
11045void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
11046 CXXRecordDecl *ClassDecl
11047 = dyn_cast<CXXRecordDecl>(Val: Constructor->getDeclContext());
11048 if (!ClassDecl)
11049 return Constructor->setInvalidDecl();
11050
11051 // C++ [class.copy]p3:
11052 // A declaration of a constructor for a class X is ill-formed if
11053 // its first parameter is of type (optionally cv-qualified) X and
11054 // either there are no other parameters or else all other
11055 // parameters have default arguments.
11056 if (!Constructor->isInvalidDecl() &&
11057 Constructor->hasOneParamOrDefaultArgs() &&
11058 !Constructor->isFunctionTemplateSpecialization()) {
11059 QualType ParamType = Constructor->getParamDecl(i: 0)->getType();
11060 QualType ClassTy = Context.getTagDeclType(Decl: ClassDecl);
11061 if (Context.getCanonicalType(T: ParamType).getUnqualifiedType() == ClassTy) {
11062 SourceLocation ParamLoc = Constructor->getParamDecl(i: 0)->getLocation();
11063 const char *ConstRef
11064 = Constructor->getParamDecl(i: 0)->getIdentifier() ? "const &"
11065 : " const &";
11066 Diag(Loc: ParamLoc, DiagID: diag::err_constructor_byvalue_arg)
11067 << FixItHint::CreateInsertion(InsertionLoc: ParamLoc, Code: ConstRef);
11068
11069 // FIXME: Rather that making the constructor invalid, we should endeavor
11070 // to fix the type.
11071 Constructor->setInvalidDecl();
11072 }
11073 }
11074}
11075
11076bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
11077 CXXRecordDecl *RD = Destructor->getParent();
11078
11079 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11080 SourceLocation Loc;
11081
11082 if (!Destructor->isImplicit())
11083 Loc = Destructor->getLocation();
11084 else
11085 Loc = RD->getLocation();
11086
11087 // If we have a virtual destructor, look up the deallocation function
11088 if (FunctionDecl *OperatorDelete =
11089 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD)) {
11090 Expr *ThisArg = nullptr;
11091
11092 // If the notional 'delete this' expression requires a non-trivial
11093 // conversion from 'this' to the type of a destroying operator delete's
11094 // first parameter, perform that conversion now.
11095 if (OperatorDelete->isDestroyingOperatorDelete()) {
11096 unsigned AddressParamIndex = 0;
11097 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11098 ++AddressParamIndex;
11099 QualType ParamType =
11100 OperatorDelete->getParamDecl(i: AddressParamIndex)->getType();
11101 if (!declaresSameEntity(D1: ParamType->getAsCXXRecordDecl(), D2: RD)) {
11102 // C++ [class.dtor]p13:
11103 // ... as if for the expression 'delete this' appearing in a
11104 // non-virtual destructor of the destructor's class.
11105 ContextRAII SwitchContext(*this, Destructor);
11106 ExprResult This = ActOnCXXThis(
11107 Loc: OperatorDelete->getParamDecl(i: AddressParamIndex)->getLocation());
11108 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11109 This = PerformImplicitConversion(From: This.get(), ToType: ParamType,
11110 Action: AssignmentAction::Passing);
11111 if (This.isInvalid()) {
11112 // FIXME: Register this as a context note so that it comes out
11113 // in the right order.
11114 Diag(Loc, DiagID: diag::note_implicit_delete_this_in_destructor_here);
11115 return true;
11116 }
11117 ThisArg = This.get();
11118 }
11119 }
11120
11121 DiagnoseUseOfDecl(D: OperatorDelete, Locs: Loc);
11122 MarkFunctionReferenced(Loc, Func: OperatorDelete);
11123 Destructor->setOperatorDelete(OD: OperatorDelete, ThisArg);
11124 }
11125 }
11126
11127 return false;
11128}
11129
11130QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11131 StorageClass& SC) {
11132 // C++ [class.dtor]p1:
11133 // [...] A typedef-name that names a class is a class-name
11134 // (7.1.3); however, a typedef-name that names a class shall not
11135 // be used as the identifier in the declarator for a destructor
11136 // declaration.
11137 QualType DeclaratorType = GetTypeFromParser(Ty: D.getName().DestructorName);
11138 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11139 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11140 << DeclaratorType << isa<TypeAliasDecl>(Val: TT->getDecl());
11141 else if (const TemplateSpecializationType *TST =
11142 DeclaratorType->getAs<TemplateSpecializationType>())
11143 if (TST->isTypeAlias())
11144 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11145 << DeclaratorType << 1;
11146
11147 // C++ [class.dtor]p2:
11148 // A destructor is used to destroy objects of its class type. A
11149 // destructor takes no parameters, and no return type can be
11150 // specified for it (not even void). The address of a destructor
11151 // shall not be taken. A destructor shall not be static. A
11152 // destructor can be invoked for a const, volatile or const
11153 // volatile object. A destructor shall not be declared const,
11154 // volatile or const volatile (9.3.2).
11155 if (SC == SC_Static) {
11156 if (!D.isInvalidType())
11157 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_cannot_be)
11158 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11159 << SourceRange(D.getIdentifierLoc())
11160 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
11161
11162 SC = SC_None;
11163 }
11164 if (!D.isInvalidType()) {
11165 // Destructors don't have return types, but the parser will
11166 // happily parse something like:
11167 //
11168 // class X {
11169 // float ~X();
11170 // };
11171 //
11172 // The return type will be eliminated later.
11173 if (D.getDeclSpec().hasTypeSpecifier())
11174 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_return_type)
11175 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11176 << SourceRange(D.getIdentifierLoc());
11177 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11178 diagnoseIgnoredQualifiers(DiagID: diag::err_destructor_return_type, Quals: TypeQuals,
11179 FallbackLoc: SourceLocation(),
11180 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(),
11181 VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11182 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11183 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11184 D.setInvalidType();
11185 }
11186 }
11187
11188 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_destructor);
11189 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*destructor*/ Kind: 1);
11190
11191 // C++0x [class.dtor]p2:
11192 // A destructor shall not be declared with a ref-qualifier.
11193 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11194 if (FTI.hasRefQualifier()) {
11195 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_destructor)
11196 << FTI.RefQualifierIsLValueRef
11197 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11198 D.setInvalidType();
11199 }
11200
11201 // Make sure we don't have any parameters.
11202 if (FTIHasNonVoidParameters(FTI)) {
11203 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_with_params);
11204
11205 // Delete the parameters.
11206 FTI.freeParams();
11207 D.setInvalidType();
11208 }
11209
11210 // Make sure the destructor isn't variadic.
11211 if (FTI.isVariadic) {
11212 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_variadic);
11213 D.setInvalidType();
11214 }
11215
11216 // Rebuild the function type "R" without any type qualifiers or
11217 // parameters (in case any of the errors above fired) and with
11218 // "void" as the return type, since destructors don't have return
11219 // types.
11220 if (!D.isInvalidType())
11221 return R;
11222
11223 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11224 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11225 EPI.Variadic = false;
11226 EPI.TypeQuals = Qualifiers();
11227 EPI.RefQualifier = RQ_None;
11228 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI);
11229}
11230
11231static void extendLeft(SourceRange &R, SourceRange Before) {
11232 if (Before.isInvalid())
11233 return;
11234 R.setBegin(Before.getBegin());
11235 if (R.getEnd().isInvalid())
11236 R.setEnd(Before.getEnd());
11237}
11238
11239static void extendRight(SourceRange &R, SourceRange After) {
11240 if (After.isInvalid())
11241 return;
11242 if (R.getBegin().isInvalid())
11243 R.setBegin(After.getBegin());
11244 R.setEnd(After.getEnd());
11245}
11246
11247void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11248 StorageClass& SC) {
11249 // C++ [class.conv.fct]p1:
11250 // Neither parameter types nor return type can be specified. The
11251 // type of a conversion function (8.3.5) is "function taking no
11252 // parameter returning conversion-type-id."
11253 if (SC == SC_Static) {
11254 if (!D.isInvalidType())
11255 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_not_member)
11256 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11257 << D.getName().getSourceRange();
11258 D.setInvalidType();
11259 SC = SC_None;
11260 }
11261
11262 TypeSourceInfo *ConvTSI = nullptr;
11263 QualType ConvType =
11264 GetTypeFromParser(Ty: D.getName().ConversionFunctionId, TInfo: &ConvTSI);
11265
11266 const DeclSpec &DS = D.getDeclSpec();
11267 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11268 // Conversion functions don't have return types, but the parser will
11269 // happily parse something like:
11270 //
11271 // class X {
11272 // float operator bool();
11273 // };
11274 //
11275 // The return type will be changed later anyway.
11276 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_return_type)
11277 << SourceRange(DS.getTypeSpecTypeLoc())
11278 << SourceRange(D.getIdentifierLoc());
11279 D.setInvalidType();
11280 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11281 // It's also plausible that the user writes type qualifiers in the wrong
11282 // place, such as:
11283 // struct S { const operator int(); };
11284 // FIXME: we could provide a fixit to move the qualifiers onto the
11285 // conversion type.
11286 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_complex_decl)
11287 << SourceRange(D.getIdentifierLoc()) << 0;
11288 D.setInvalidType();
11289 }
11290 const auto *Proto = R->castAs<FunctionProtoType>();
11291 // Make sure we don't have any parameters.
11292 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11293 unsigned NumParam = Proto->getNumParams();
11294
11295 // [C++2b]
11296 // A conversion function shall have no non-object parameters.
11297 if (NumParam == 1) {
11298 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11299 if (const auto *First =
11300 dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param);
11301 First && First->isExplicitObjectParameter())
11302 NumParam--;
11303 }
11304
11305 if (NumParam != 0) {
11306 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_params);
11307 // Delete the parameters.
11308 FTI.freeParams();
11309 D.setInvalidType();
11310 } else if (Proto->isVariadic()) {
11311 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_variadic);
11312 D.setInvalidType();
11313 }
11314
11315 // Diagnose "&operator bool()" and other such nonsense. This
11316 // is actually a gcc extension which we don't support.
11317 if (Proto->getReturnType() != ConvType) {
11318 bool NeedsTypedef = false;
11319 SourceRange Before, After;
11320
11321 // Walk the chunks and extract information on them for our diagnostic.
11322 bool PastFunctionChunk = false;
11323 for (auto &Chunk : D.type_objects()) {
11324 switch (Chunk.Kind) {
11325 case DeclaratorChunk::Function:
11326 if (!PastFunctionChunk) {
11327 if (Chunk.Fun.HasTrailingReturnType) {
11328 TypeSourceInfo *TRT = nullptr;
11329 GetTypeFromParser(Ty: Chunk.Fun.getTrailingReturnType(), TInfo: &TRT);
11330 if (TRT) extendRight(R&: After, After: TRT->getTypeLoc().getSourceRange());
11331 }
11332 PastFunctionChunk = true;
11333 break;
11334 }
11335 [[fallthrough]];
11336 case DeclaratorChunk::Array:
11337 NeedsTypedef = true;
11338 extendRight(R&: After, After: Chunk.getSourceRange());
11339 break;
11340
11341 case DeclaratorChunk::Pointer:
11342 case DeclaratorChunk::BlockPointer:
11343 case DeclaratorChunk::Reference:
11344 case DeclaratorChunk::MemberPointer:
11345 case DeclaratorChunk::Pipe:
11346 extendLeft(R&: Before, Before: Chunk.getSourceRange());
11347 break;
11348
11349 case DeclaratorChunk::Paren:
11350 extendLeft(R&: Before, Before: Chunk.Loc);
11351 extendRight(R&: After, After: Chunk.EndLoc);
11352 break;
11353 }
11354 }
11355
11356 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11357 After.isValid() ? After.getBegin() :
11358 D.getIdentifierLoc();
11359 auto &&DB = Diag(Loc, DiagID: diag::err_conv_function_with_complex_decl);
11360 DB << Before << After;
11361
11362 if (!NeedsTypedef) {
11363 DB << /*don't need a typedef*/0;
11364
11365 // If we can provide a correct fix-it hint, do so.
11366 if (After.isInvalid() && ConvTSI) {
11367 SourceLocation InsertLoc =
11368 getLocForEndOfToken(Loc: ConvTSI->getTypeLoc().getEndLoc());
11369 DB << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " ")
11370 << FixItHint::CreateInsertionFromRange(
11371 InsertionLoc: InsertLoc, FromRange: CharSourceRange::getTokenRange(R: Before))
11372 << FixItHint::CreateRemoval(RemoveRange: Before);
11373 }
11374 } else if (!Proto->getReturnType()->isDependentType()) {
11375 DB << /*typedef*/1 << Proto->getReturnType();
11376 } else if (getLangOpts().CPlusPlus11) {
11377 DB << /*alias template*/2 << Proto->getReturnType();
11378 } else {
11379 DB << /*might not be fixable*/3;
11380 }
11381
11382 // Recover by incorporating the other type chunks into the result type.
11383 // Note, this does *not* change the name of the function. This is compatible
11384 // with the GCC extension:
11385 // struct S { &operator int(); } s;
11386 // int &r = s.operator int(); // ok in GCC
11387 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11388 ConvType = Proto->getReturnType();
11389 }
11390
11391 // C++ [class.conv.fct]p4:
11392 // The conversion-type-id shall not represent a function type nor
11393 // an array type.
11394 if (ConvType->isArrayType()) {
11395 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_array);
11396 ConvType = Context.getPointerType(T: ConvType);
11397 D.setInvalidType();
11398 } else if (ConvType->isFunctionType()) {
11399 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_function);
11400 ConvType = Context.getPointerType(T: ConvType);
11401 D.setInvalidType();
11402 }
11403
11404 // Rebuild the function type "R" without any parameters (in case any
11405 // of the errors above fired) and with the conversion type as the
11406 // return type.
11407 if (D.isInvalidType())
11408 R = Context.getFunctionType(ResultTy: ConvType, Args: {}, EPI: Proto->getExtProtoInfo());
11409
11410 // C++0x explicit conversion operators.
11411 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11412 Diag(Loc: DS.getExplicitSpecLoc(),
11413 DiagID: getLangOpts().CPlusPlus11
11414 ? diag::warn_cxx98_compat_explicit_conversion_functions
11415 : diag::ext_explicit_conversion_functions)
11416 << SourceRange(DS.getExplicitSpecRange());
11417}
11418
11419Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11420 assert(Conversion && "Expected to receive a conversion function declaration");
11421
11422 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Conversion->getDeclContext());
11423
11424 // Make sure we aren't redeclaring the conversion function.
11425 QualType ConvType = Context.getCanonicalType(T: Conversion->getConversionType());
11426 // C++ [class.conv.fct]p1:
11427 // [...] A conversion function is never used to convert a
11428 // (possibly cv-qualified) object to the (possibly cv-qualified)
11429 // same object type (or a reference to it), to a (possibly
11430 // cv-qualified) base class of that type (or a reference to it),
11431 // or to (possibly cv-qualified) void.
11432 QualType ClassType
11433 = Context.getCanonicalType(T: Context.getTypeDeclType(Decl: ClassDecl));
11434 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11435 ConvType = ConvTypeRef->getPointeeType();
11436 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11437 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11438 /* Suppress diagnostics for instantiations. */;
11439 else if (Conversion->size_overridden_methods() != 0)
11440 /* Suppress diagnostics for overriding virtual function in a base class. */;
11441 else if (ConvType->isRecordType()) {
11442 ConvType = Context.getCanonicalType(T: ConvType).getUnqualifiedType();
11443 if (ConvType == ClassType)
11444 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_self_not_used)
11445 << ClassType;
11446 else if (IsDerivedFrom(Loc: Conversion->getLocation(), Derived: ClassType, Base: ConvType))
11447 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_base_not_used)
11448 << ClassType << ConvType;
11449 } else if (ConvType->isVoidType()) {
11450 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_void_not_used)
11451 << ClassType << ConvType;
11452 }
11453
11454 if (FunctionTemplateDecl *ConversionTemplate =
11455 Conversion->getDescribedFunctionTemplate()) {
11456 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11457 ConvType = ConvTypePtr->getPointeeType();
11458 }
11459 if (ConvType->isUndeducedAutoType()) {
11460 Diag(Loc: Conversion->getTypeSpecStartLoc(), DiagID: diag::err_auto_not_allowed)
11461 << getReturnTypeLoc(FD: Conversion).getSourceRange()
11462 << ConvType->castAs<AutoType>()->getKeyword()
11463 << /* in declaration of conversion function template= */ 24;
11464 }
11465
11466 return ConversionTemplate;
11467 }
11468
11469 return Conversion;
11470}
11471
11472void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11473 DeclarationName Name, QualType R) {
11474 CheckExplicitObjectMemberFunction(D, Name, R, IsLambda: false, DC);
11475}
11476
11477void Sema::CheckExplicitObjectLambda(Declarator &D) {
11478 CheckExplicitObjectMemberFunction(D, Name: {}, R: {}, IsLambda: true);
11479}
11480
11481void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11482 DeclarationName Name, QualType R,
11483 bool IsLambda, DeclContext *DC) {
11484 if (!D.isFunctionDeclarator())
11485 return;
11486
11487 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11488 if (FTI.NumParams == 0)
11489 return;
11490 ParmVarDecl *ExplicitObjectParam = nullptr;
11491 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11492 const auto &ParamInfo = FTI.Params[Idx];
11493 if (!ParamInfo.Param)
11494 continue;
11495 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamInfo.Param);
11496 if (!Param->isExplicitObjectParameter())
11497 continue;
11498 if (Idx == 0) {
11499 ExplicitObjectParam = Param;
11500 continue;
11501 } else {
11502 Diag(Loc: Param->getLocation(),
11503 DiagID: diag::err_explicit_object_parameter_must_be_first)
11504 << IsLambda << Param->getSourceRange();
11505 }
11506 }
11507 if (!ExplicitObjectParam)
11508 return;
11509
11510 if (ExplicitObjectParam->hasDefaultArg()) {
11511 Diag(Loc: ExplicitObjectParam->getLocation(),
11512 DiagID: diag::err_explicit_object_default_arg)
11513 << ExplicitObjectParam->getSourceRange();
11514 }
11515
11516 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11517 (D.getContext() == clang::DeclaratorContext::Member &&
11518 D.isStaticMember())) {
11519 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11520 DiagID: diag::err_explicit_object_parameter_nonmember)
11521 << D.getSourceRange() << /*static=*/0 << IsLambda;
11522 D.setInvalidType();
11523 }
11524
11525 if (D.getDeclSpec().isVirtualSpecified()) {
11526 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11527 DiagID: diag::err_explicit_object_parameter_nonmember)
11528 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11529 D.setInvalidType();
11530 }
11531
11532 // Friend declarations require some care. Consider:
11533 //
11534 // namespace N {
11535 // struct A{};
11536 // int f(A);
11537 // }
11538 //
11539 // struct S {
11540 // struct T {
11541 // int f(this T);
11542 // };
11543 //
11544 // friend int T::f(this T); // Allow this.
11545 // friend int f(this S); // But disallow this.
11546 // friend int N::f(this A); // And disallow this.
11547 // };
11548 //
11549 // Here, it seems to suffice to check whether the scope
11550 // specifier designates a class type.
11551 if (D.getDeclSpec().isFriendSpecified() &&
11552 !isa_and_present<CXXRecordDecl>(
11553 Val: computeDeclContext(SS: D.getCXXScopeSpec()))) {
11554 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11555 DiagID: diag::err_explicit_object_parameter_nonmember)
11556 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11557 D.setInvalidType();
11558 }
11559
11560 if (IsLambda && FTI.hasMutableQualifier()) {
11561 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11562 DiagID: diag::err_explicit_object_parameter_mutable)
11563 << D.getSourceRange();
11564 }
11565
11566 if (IsLambda)
11567 return;
11568
11569 if (!DC || !DC->isRecord()) {
11570 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11571 "should have been diagnosed already");
11572 return;
11573 }
11574
11575 // CWG2674: constructors and destructors cannot have explicit parameters.
11576 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11577 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11578 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11579 DiagID: diag::err_explicit_object_parameter_constructor)
11580 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11581 << D.getSourceRange();
11582 D.setInvalidType();
11583 }
11584}
11585
11586namespace {
11587/// Utility class to accumulate and print a diagnostic listing the invalid
11588/// specifier(s) on a declaration.
11589struct BadSpecifierDiagnoser {
11590 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11591 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11592 ~BadSpecifierDiagnoser() {
11593 Diagnostic << Specifiers;
11594 }
11595
11596 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11597 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11598 }
11599 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11600 return check(SpecLoc,
11601 Spec: DeclSpec::getSpecifierName(T: Spec, Policy: S.getPrintingPolicy()));
11602 }
11603 void check(SourceLocation SpecLoc, const char *Spec) {
11604 if (SpecLoc.isInvalid()) return;
11605 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11606 if (!Specifiers.empty()) Specifiers += " ";
11607 Specifiers += Spec;
11608 }
11609
11610 Sema &S;
11611 Sema::SemaDiagnosticBuilder Diagnostic;
11612 std::string Specifiers;
11613};
11614}
11615
11616bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11617 StorageClass &SC) {
11618 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11619 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11620 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11621
11622 // C++ [temp.deduct.guide]p3:
11623 // A deduction-gide shall be declared in the same scope as the
11624 // corresponding class template.
11625 if (!CurContext->getRedeclContext()->Equals(
11626 DC: GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11627 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_wrong_scope)
11628 << GuidedTemplateDecl;
11629 NoteTemplateLocation(Decl: *GuidedTemplateDecl);
11630 }
11631
11632 auto &DS = D.getMutableDeclSpec();
11633 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11634 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11635 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11636 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11637 BadSpecifierDiagnoser Diagnoser(
11638 *this, D.getIdentifierLoc(),
11639 diag::err_deduction_guide_invalid_specifier);
11640
11641 Diagnoser.check(SpecLoc: DS.getStorageClassSpecLoc(), Spec: DS.getStorageClassSpec());
11642 DS.ClearStorageClassSpecs();
11643 SC = SC_None;
11644
11645 // 'explicit' is permitted.
11646 Diagnoser.check(SpecLoc: DS.getInlineSpecLoc(), Spec: "inline");
11647 Diagnoser.check(SpecLoc: DS.getNoreturnSpecLoc(), Spec: "_Noreturn");
11648 Diagnoser.check(SpecLoc: DS.getConstexprSpecLoc(), Spec: "constexpr");
11649 DS.ClearConstexprSpec();
11650
11651 Diagnoser.check(SpecLoc: DS.getConstSpecLoc(), Spec: "const");
11652 Diagnoser.check(SpecLoc: DS.getRestrictSpecLoc(), Spec: "__restrict");
11653 Diagnoser.check(SpecLoc: DS.getVolatileSpecLoc(), Spec: "volatile");
11654 Diagnoser.check(SpecLoc: DS.getAtomicSpecLoc(), Spec: "_Atomic");
11655 Diagnoser.check(SpecLoc: DS.getUnalignedSpecLoc(), Spec: "__unaligned");
11656 DS.ClearTypeQualifiers();
11657
11658 Diagnoser.check(SpecLoc: DS.getTypeSpecComplexLoc(), Spec: DS.getTypeSpecComplex());
11659 Diagnoser.check(SpecLoc: DS.getTypeSpecSignLoc(), Spec: DS.getTypeSpecSign());
11660 Diagnoser.check(SpecLoc: DS.getTypeSpecWidthLoc(), Spec: DS.getTypeSpecWidth());
11661 Diagnoser.check(SpecLoc: DS.getTypeSpecTypeLoc(), Spec: DS.getTypeSpecType());
11662 DS.ClearTypeSpecType();
11663 }
11664
11665 if (D.isInvalidType())
11666 return true;
11667
11668 // Check the declarator is simple enough.
11669 bool FoundFunction = false;
11670 for (const DeclaratorChunk &Chunk : llvm::reverse(C: D.type_objects())) {
11671 if (Chunk.Kind == DeclaratorChunk::Paren)
11672 continue;
11673 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11674 Diag(Loc: D.getDeclSpec().getBeginLoc(),
11675 DiagID: diag::err_deduction_guide_with_complex_decl)
11676 << D.getSourceRange();
11677 break;
11678 }
11679 if (!Chunk.Fun.hasTrailingReturnType())
11680 return Diag(Loc: D.getName().getBeginLoc(),
11681 DiagID: diag::err_deduction_guide_no_trailing_return_type);
11682
11683 // Check that the return type is written as a specialization of
11684 // the template specified as the deduction-guide's name.
11685 // The template name may not be qualified. [temp.deduct.guide]
11686 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11687 TypeSourceInfo *TSI = nullptr;
11688 QualType RetTy = GetTypeFromParser(Ty: TrailingReturnType, TInfo: &TSI);
11689 assert(TSI && "deduction guide has valid type but invalid return type?");
11690 bool AcceptableReturnType = false;
11691 bool MightInstantiateToSpecialization = false;
11692 if (auto RetTST =
11693 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11694 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11695 bool TemplateMatches = Context.hasSameTemplateName(
11696 X: SpecifiedName, Y: GuidedTemplate, /*IgnoreDeduced=*/true);
11697
11698 const QualifiedTemplateName *Qualifiers =
11699 SpecifiedName.getAsQualifiedTemplateName();
11700 assert(Qualifiers && "expected QualifiedTemplate");
11701 bool SimplyWritten = !Qualifiers->hasTemplateKeyword() &&
11702 Qualifiers->getQualifier() == nullptr;
11703 if (SimplyWritten && TemplateMatches)
11704 AcceptableReturnType = true;
11705 else {
11706 // This could still instantiate to the right type, unless we know it
11707 // names the wrong class template.
11708 auto *TD = SpecifiedName.getAsTemplateDecl();
11709 MightInstantiateToSpecialization =
11710 !(TD && isa<ClassTemplateDecl>(Val: TD) && !TemplateMatches);
11711 }
11712 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11713 MightInstantiateToSpecialization = true;
11714 }
11715
11716 if (!AcceptableReturnType)
11717 return Diag(Loc: TSI->getTypeLoc().getBeginLoc(),
11718 DiagID: diag::err_deduction_guide_bad_trailing_return_type)
11719 << GuidedTemplate << TSI->getType()
11720 << MightInstantiateToSpecialization
11721 << TSI->getTypeLoc().getSourceRange();
11722
11723 // Keep going to check that we don't have any inner declarator pieces (we
11724 // could still have a function returning a pointer to a function).
11725 FoundFunction = true;
11726 }
11727
11728 if (D.isFunctionDefinition())
11729 // we can still create a valid deduction guide here.
11730 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_defines_function);
11731 return false;
11732}
11733
11734//===----------------------------------------------------------------------===//
11735// Namespace Handling
11736//===----------------------------------------------------------------------===//
11737
11738/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11739/// reopened.
11740static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11741 SourceLocation Loc,
11742 IdentifierInfo *II, bool *IsInline,
11743 NamespaceDecl *PrevNS) {
11744 assert(*IsInline != PrevNS->isInline());
11745
11746 // 'inline' must appear on the original definition, but not necessarily
11747 // on all extension definitions, so the note should point to the first
11748 // definition to avoid confusion.
11749 PrevNS = PrevNS->getFirstDecl();
11750
11751 if (PrevNS->isInline())
11752 // The user probably just forgot the 'inline', so suggest that it
11753 // be added back.
11754 S.Diag(Loc, DiagID: diag::warn_inline_namespace_reopened_noninline)
11755 << FixItHint::CreateInsertion(InsertionLoc: KeywordLoc, Code: "inline ");
11756 else
11757 S.Diag(Loc, DiagID: diag::err_inline_namespace_mismatch);
11758
11759 S.Diag(Loc: PrevNS->getLocation(), DiagID: diag::note_previous_definition);
11760 *IsInline = PrevNS->isInline();
11761}
11762
11763/// ActOnStartNamespaceDef - This is called at the start of a namespace
11764/// definition.
11765Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11766 SourceLocation InlineLoc,
11767 SourceLocation NamespaceLoc,
11768 SourceLocation IdentLoc, IdentifierInfo *II,
11769 SourceLocation LBrace,
11770 const ParsedAttributesView &AttrList,
11771 UsingDirectiveDecl *&UD, bool IsNested) {
11772 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11773 // For anonymous namespace, take the location of the left brace.
11774 SourceLocation Loc = II ? IdentLoc : LBrace;
11775 bool IsInline = InlineLoc.isValid();
11776 bool IsInvalid = false;
11777 bool IsStd = false;
11778 bool AddToKnown = false;
11779 Scope *DeclRegionScope = NamespcScope->getParent();
11780
11781 NamespaceDecl *PrevNS = nullptr;
11782 if (II) {
11783 // C++ [namespace.std]p7:
11784 // A translation unit shall not declare namespace std to be an inline
11785 // namespace (9.8.2).
11786 //
11787 // Precondition: the std namespace is in the file scope and is declared to
11788 // be inline
11789 auto DiagnoseInlineStdNS = [&]() {
11790 assert(IsInline && II->isStr("std") &&
11791 CurContext->getRedeclContext()->isTranslationUnit() &&
11792 "Precondition of DiagnoseInlineStdNS not met");
11793 Diag(Loc: InlineLoc, DiagID: diag::err_inline_namespace_std)
11794 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(Offset: 6));
11795 IsInline = false;
11796 };
11797 // C++ [namespace.def]p2:
11798 // The identifier in an original-namespace-definition shall not
11799 // have been previously defined in the declarative region in
11800 // which the original-namespace-definition appears. The
11801 // identifier in an original-namespace-definition is the name of
11802 // the namespace. Subsequently in that declarative region, it is
11803 // treated as an original-namespace-name.
11804 //
11805 // Since namespace names are unique in their scope, and we don't
11806 // look through using directives, just look for any ordinary names
11807 // as if by qualified name lookup.
11808 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11809 RedeclarationKind::ForExternalRedeclaration);
11810 LookupQualifiedName(R, LookupCtx: CurContext->getRedeclContext());
11811 NamedDecl *PrevDecl =
11812 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11813 PrevNS = dyn_cast_or_null<NamespaceDecl>(Val: PrevDecl);
11814
11815 if (PrevNS) {
11816 // This is an extended namespace definition.
11817 if (IsInline && II->isStr(Str: "std") &&
11818 CurContext->getRedeclContext()->isTranslationUnit())
11819 DiagnoseInlineStdNS();
11820 else if (IsInline != PrevNS->isInline())
11821 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc, II,
11822 IsInline: &IsInline, PrevNS);
11823 } else if (PrevDecl) {
11824 // This is an invalid name redefinition.
11825 Diag(Loc, DiagID: diag::err_redefinition_different_kind)
11826 << II;
11827 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
11828 IsInvalid = true;
11829 // Continue on to push Namespc as current DeclContext and return it.
11830 } else if (II->isStr(Str: "std") &&
11831 CurContext->getRedeclContext()->isTranslationUnit()) {
11832 if (IsInline)
11833 DiagnoseInlineStdNS();
11834 // This is the first "real" definition of the namespace "std", so update
11835 // our cache of the "std" namespace to point at this definition.
11836 PrevNS = getStdNamespace();
11837 IsStd = true;
11838 AddToKnown = !IsInline;
11839 } else {
11840 // We've seen this namespace for the first time.
11841 AddToKnown = !IsInline;
11842 }
11843 } else {
11844 // Anonymous namespaces.
11845
11846 // Determine whether the parent already has an anonymous namespace.
11847 DeclContext *Parent = CurContext->getRedeclContext();
11848 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
11849 PrevNS = TU->getAnonymousNamespace();
11850 } else {
11851 NamespaceDecl *ND = cast<NamespaceDecl>(Val: Parent);
11852 PrevNS = ND->getAnonymousNamespace();
11853 }
11854
11855 if (PrevNS && IsInline != PrevNS->isInline())
11856 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc: NamespaceLoc, II,
11857 IsInline: &IsInline, PrevNS);
11858 }
11859
11860 NamespaceDecl *Namespc = NamespaceDecl::Create(
11861 C&: Context, DC: CurContext, Inline: IsInline, StartLoc, IdLoc: Loc, Id: II, PrevDecl: PrevNS, Nested: IsNested);
11862 if (IsInvalid)
11863 Namespc->setInvalidDecl();
11864
11865 ProcessDeclAttributeList(S: DeclRegionScope, D: Namespc, AttrList);
11866 AddPragmaAttributes(S: DeclRegionScope, D: Namespc);
11867 ProcessAPINotes(D: Namespc);
11868
11869 // FIXME: Should we be merging attributes?
11870 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11871 PushNamespaceVisibilityAttr(Attr, Loc);
11872
11873 if (IsStd)
11874 StdNamespace = Namespc;
11875 if (AddToKnown)
11876 KnownNamespaces[Namespc] = false;
11877
11878 if (II) {
11879 PushOnScopeChains(D: Namespc, S: DeclRegionScope);
11880 } else {
11881 // Link the anonymous namespace into its parent.
11882 DeclContext *Parent = CurContext->getRedeclContext();
11883 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
11884 TU->setAnonymousNamespace(Namespc);
11885 } else {
11886 cast<NamespaceDecl>(Val: Parent)->setAnonymousNamespace(Namespc);
11887 }
11888
11889 CurContext->addDecl(D: Namespc);
11890
11891 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11892 // behaves as if it were replaced by
11893 // namespace unique { /* empty body */ }
11894 // using namespace unique;
11895 // namespace unique { namespace-body }
11896 // where all occurrences of 'unique' in a translation unit are
11897 // replaced by the same identifier and this identifier differs
11898 // from all other identifiers in the entire program.
11899
11900 // We just create the namespace with an empty name and then add an
11901 // implicit using declaration, just like the standard suggests.
11902 //
11903 // CodeGen enforces the "universally unique" aspect by giving all
11904 // declarations semantically contained within an anonymous
11905 // namespace internal linkage.
11906
11907 if (!PrevNS) {
11908 UD = UsingDirectiveDecl::Create(C&: Context, DC: Parent,
11909 /* 'using' */ UsingLoc: LBrace,
11910 /* 'namespace' */ NamespaceLoc: SourceLocation(),
11911 /* qualifier */ QualifierLoc: NestedNameSpecifierLoc(),
11912 /* identifier */ IdentLoc: SourceLocation(),
11913 Nominated: Namespc,
11914 /* Ancestor */ CommonAncestor: Parent);
11915 UD->setImplicit();
11916 Parent->addDecl(D: UD);
11917 }
11918 }
11919
11920 ActOnDocumentableDecl(D: Namespc);
11921
11922 // Although we could have an invalid decl (i.e. the namespace name is a
11923 // redefinition), push it as current DeclContext and try to continue parsing.
11924 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11925 // for the namespace has the declarations that showed up in that particular
11926 // namespace definition.
11927 PushDeclContext(S: NamespcScope, DC: Namespc);
11928 return Namespc;
11929}
11930
11931/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11932/// is a namespace alias, returns the namespace it points to.
11933static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11934 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(Val: D))
11935 return AD->getNamespace();
11936 return dyn_cast_or_null<NamespaceDecl>(Val: D);
11937}
11938
11939void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11940 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Val: Dcl);
11941 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11942 Namespc->setRBraceLoc(RBrace);
11943 PopDeclContext();
11944 if (Namespc->hasAttr<VisibilityAttr>())
11945 PopPragmaVisibility(IsNamespaceEnd: true, EndLoc: RBrace);
11946 // If this namespace contains an export-declaration, export it now.
11947 if (DeferredExportedNamespaces.erase(Ptr: Namespc))
11948 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11949}
11950
11951CXXRecordDecl *Sema::getStdBadAlloc() const {
11952 return cast_or_null<CXXRecordDecl>(
11953 Val: StdBadAlloc.get(Source: Context.getExternalSource()));
11954}
11955
11956EnumDecl *Sema::getStdAlignValT() const {
11957 return cast_or_null<EnumDecl>(Val: StdAlignValT.get(Source: Context.getExternalSource()));
11958}
11959
11960NamespaceDecl *Sema::getStdNamespace() const {
11961 return cast_or_null<NamespaceDecl>(
11962 Val: StdNamespace.get(Source: Context.getExternalSource()));
11963}
11964
11965namespace {
11966
11967enum UnsupportedSTLSelect {
11968 USS_InvalidMember,
11969 USS_MissingMember,
11970 USS_NonTrivial,
11971 USS_Other
11972};
11973
11974struct InvalidSTLDiagnoser {
11975 Sema &S;
11976 SourceLocation Loc;
11977 QualType TyForDiags;
11978
11979 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11980 const VarDecl *VD = nullptr) {
11981 {
11982 auto D = S.Diag(Loc, DiagID: diag::err_std_compare_type_not_supported)
11983 << TyForDiags << ((int)Sel);
11984 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11985 assert(!Name.empty());
11986 D << Name;
11987 }
11988 }
11989 if (Sel == USS_InvalidMember) {
11990 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_var_declared_here)
11991 << VD << VD->getSourceRange();
11992 }
11993 return QualType();
11994 }
11995};
11996} // namespace
11997
11998QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11999 SourceLocation Loc,
12000 ComparisonCategoryUsage Usage) {
12001 assert(getLangOpts().CPlusPlus &&
12002 "Looking for comparison category type outside of C++.");
12003
12004 // Use an elaborated type for diagnostics which has a name containing the
12005 // prepended 'std' namespace but not any inline namespace names.
12006 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12007 auto *NNS =
12008 NestedNameSpecifier::Create(Context, Prefix: nullptr, NS: getStdNamespace());
12009 return Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS,
12010 NamedType: Info->getType());
12011 };
12012
12013 // Check if we've already successfully checked the comparison category type
12014 // before. If so, skip checking it again.
12015 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12016 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12017 // The only thing we need to check is that the type has a reachable
12018 // definition in the current context.
12019 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12020 return QualType();
12021
12022 return Info->getType();
12023 }
12024
12025 // If lookup failed
12026 if (!Info) {
12027 std::string NameForDiags = "std::";
12028 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12029 Diag(Loc, DiagID: diag::err_implied_comparison_category_type_not_found)
12030 << NameForDiags << (int)Usage;
12031 return QualType();
12032 }
12033
12034 assert(Info->Kind == Kind);
12035 assert(Info->Record);
12036
12037 // Update the Record decl in case we encountered a forward declaration on our
12038 // first pass. FIXME: This is a bit of a hack.
12039 if (Info->Record->hasDefinition())
12040 Info->Record = Info->Record->getDefinition();
12041
12042 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12043 return QualType();
12044
12045 InvalidSTLDiagnoser UnsupportedSTLError{.S: *this, .Loc: Loc, .TyForDiags: TyForDiags(Info)};
12046
12047 if (!Info->Record->isTriviallyCopyable())
12048 return UnsupportedSTLError(USS_NonTrivial);
12049
12050 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12051 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12052 // Tolerate empty base classes.
12053 if (Base->isEmpty())
12054 continue;
12055 // Reject STL implementations which have at least one non-empty base.
12056 return UnsupportedSTLError();
12057 }
12058
12059 // Check that the STL has implemented the types using a single integer field.
12060 // This expectation allows better codegen for builtin operators. We require:
12061 // (1) The class has exactly one field.
12062 // (2) The field is an integral or enumeration type.
12063 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12064 if (std::distance(first: FIt, last: FEnd) != 1 ||
12065 !FIt->getType()->isIntegralOrEnumerationType()) {
12066 return UnsupportedSTLError();
12067 }
12068
12069 // Build each of the require values and store them in Info.
12070 for (ComparisonCategoryResult CCR :
12071 ComparisonCategories::getPossibleResultsForType(Type: Kind)) {
12072 StringRef MemName = ComparisonCategories::getResultString(Kind: CCR);
12073 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(ValueKind: CCR);
12074
12075 if (!ValInfo)
12076 return UnsupportedSTLError(USS_MissingMember, MemName);
12077
12078 VarDecl *VD = ValInfo->VD;
12079 assert(VD && "should not be null!");
12080
12081 // Attempt to diagnose reasons why the STL definition of this type
12082 // might be foobar, including it failing to be a constant expression.
12083 // TODO Handle more ways the lookup or result can be invalid.
12084 if (!VD->isStaticDataMember() ||
12085 !VD->isUsableInConstantExpressions(C: Context))
12086 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12087
12088 // Attempt to evaluate the var decl as a constant expression and extract
12089 // the value of its first field as a ICE. If this fails, the STL
12090 // implementation is not supported.
12091 if (!ValInfo->hasValidIntValue())
12092 return UnsupportedSTLError();
12093
12094 MarkVariableReferenced(Loc, Var: VD);
12095 }
12096
12097 // We've successfully built the required types and expressions. Update
12098 // the cache and return the newly cached value.
12099 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12100 return Info->getType();
12101}
12102
12103NamespaceDecl *Sema::getOrCreateStdNamespace() {
12104 if (!StdNamespace) {
12105 // The "std" namespace has not yet been defined, so build one implicitly.
12106 StdNamespace = NamespaceDecl::Create(
12107 C&: Context, DC: Context.getTranslationUnitDecl(),
12108 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
12109 Id: &PP.getIdentifierTable().get(Name: "std"),
12110 /*PrevDecl=*/nullptr, /*Nested=*/false);
12111 getStdNamespace()->setImplicit(true);
12112 // We want the created NamespaceDecl to be available for redeclaration
12113 // lookups, but not for regular name lookups.
12114 Context.getTranslationUnitDecl()->addDecl(D: getStdNamespace());
12115 getStdNamespace()->clearIdentifierNamespace();
12116 }
12117
12118 return getStdNamespace();
12119}
12120
12121static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12122 const char *ClassName,
12123 ClassTemplateDecl **CachedDecl,
12124 const Decl **MalformedDecl) {
12125 // We're looking for implicit instantiations of
12126 // template <typename U> class std::{ClassName}.
12127
12128 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12129 // it.
12130 return false;
12131
12132 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12133 if (!MalformedDecl)
12134 return;
12135 if (!D)
12136 D = SugaredType->getAsTagDecl();
12137 if (!D || !D->isInStdNamespace())
12138 return;
12139 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12140 if (II && II == &S.PP.getIdentifierTable().get(Name: ClassName))
12141 *MalformedDecl = D;
12142 };
12143
12144 ClassTemplateDecl *Template = nullptr;
12145 ArrayRef<TemplateArgument> Arguments;
12146 {
12147 const TemplateSpecializationType *TST =
12148 SugaredType->getAsNonAliasTemplateSpecializationType();
12149 if (!TST)
12150 if (const auto *ICN = SugaredType->getAs<InjectedClassNameType>())
12151 TST = ICN->getInjectedTST();
12152 if (TST) {
12153 Template = dyn_cast_or_null<ClassTemplateDecl>(
12154 Val: TST->getTemplateName().getAsTemplateDecl());
12155 Arguments = TST->template_arguments();
12156 } else if (const RecordType *RT = SugaredType->getAs<RecordType>()) {
12157 ClassTemplateSpecializationDecl *Specialization =
12158 dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
12159 if (!Specialization) {
12160 ReportMatchingNameAsMalformed(RT->getDecl());
12161 return false;
12162 }
12163 Template = Specialization->getSpecializedTemplate();
12164 Arguments = Specialization->getTemplateArgs().asArray();
12165 }
12166 }
12167
12168 if (!Template) {
12169 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12170 return false;
12171 }
12172
12173 if (!*CachedDecl) {
12174 // Haven't recognized std::{ClassName} yet, maybe this is it.
12175 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12176 // semantics of this are slightly different, most notably the existing
12177 // "lookup" semantics explicitly diagnose an invalid definition as an
12178 // error.
12179 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12180 if (TemplateClass->getIdentifier() !=
12181 &S.PP.getIdentifierTable().get(Name: ClassName) ||
12182 !S.getStdNamespace()->InEnclosingNamespaceSetOf(
12183 NS: TemplateClass->getNonTransparentDeclContext()))
12184 return false;
12185 // This is a template called std::{ClassName}, but is it the right
12186 // template?
12187 TemplateParameterList *Params = Template->getTemplateParameters();
12188 if (Params->getMinRequiredArguments() != 1 ||
12189 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0)) ||
12190 Params->getParam(Idx: 0)->isTemplateParameterPack()) {
12191 if (MalformedDecl)
12192 *MalformedDecl = TemplateClass;
12193 return false;
12194 }
12195
12196 // It's the right template.
12197 *CachedDecl = Template;
12198 }
12199
12200 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12201 return false;
12202
12203 // This is an instance of std::{ClassName}. Find the argument type.
12204 if (TypeArg) {
12205 QualType ArgType = Arguments[0].getAsType();
12206 // FIXME: Since TST only has as-written arguments, we have to perform the
12207 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12208 // - If an explicitly-specified template argument type is a lifetime type
12209 // with no lifetime qualifier, the __strong lifetime qualifier is
12210 // inferred.
12211 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12212 !ArgType.getObjCLifetime()) {
12213 Qualifiers Qs;
12214 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
12215 ArgType = S.Context.getQualifiedType(T: ArgType, Qs);
12216 }
12217 *TypeArg = ArgType;
12218 }
12219
12220 return true;
12221}
12222
12223bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
12224 assert(getLangOpts().CPlusPlus &&
12225 "Looking for std::initializer_list outside of C++.");
12226
12227 // We're looking for implicit instantiations of
12228 // template <typename E> class std::initializer_list.
12229
12230 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "initializer_list",
12231 CachedDecl: &StdInitializerList, /*MalformedDecl=*/nullptr);
12232}
12233
12234bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,
12235 const Decl **MalformedDecl) {
12236 assert(getLangOpts().CPlusPlus &&
12237 "Looking for std::type_identity outside of C++.");
12238
12239 // We're looking for implicit instantiations of
12240 // template <typename T> struct std::type_identity.
12241
12242 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "type_identity",
12243 CachedDecl: &StdTypeIdentity, MalformedDecl);
12244}
12245
12246static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,
12247 const char *ClassName,
12248 bool *WasMalformed) {
12249 if (!S.StdNamespace)
12250 return nullptr;
12251
12252 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: ClassName), Loc,
12253 Sema::LookupOrdinaryName);
12254 if (!S.LookupQualifiedName(R&: Result, LookupCtx: S.getStdNamespace()))
12255 return nullptr;
12256
12257 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12258 if (!Template) {
12259 Result.suppressDiagnostics();
12260 // We found something weird. Complain about the first thing we found.
12261 NamedDecl *Found = *Result.begin();
12262 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_class_template)
12263 << ClassName;
12264 if (WasMalformed)
12265 *WasMalformed = true;
12266 return nullptr;
12267 }
12268
12269 // We found some template with the correct name. Now verify that it's
12270 // correct.
12271 TemplateParameterList *Params = Template->getTemplateParameters();
12272 if (Params->getMinRequiredArguments() != 1 ||
12273 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
12274 S.Diag(Loc: Template->getLocation(), DiagID: diag::err_malformed_std_class_template)
12275 << ClassName;
12276 if (WasMalformed)
12277 *WasMalformed = true;
12278 return nullptr;
12279 }
12280
12281 return Template;
12282}
12283
12284static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,
12285 QualType TypeParam, SourceLocation Loc) {
12286 assert(S.getStdNamespace());
12287 TemplateArgumentListInfo Args(Loc, Loc);
12288 auto TSI = S.Context.getTrivialTypeSourceInfo(T: TypeParam, Loc);
12289 Args.addArgument(Loc: TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12290
12291 QualType T = S.CheckTemplateIdType(Template: TemplateName(CTD), TemplateLoc: Loc, TemplateArgs&: Args);
12292 if (T.isNull())
12293 return QualType();
12294
12295 return S.Context.getElaboratedType(
12296 Keyword: ElaboratedTypeKeyword::None,
12297 NNS: NestedNameSpecifier::Create(Context: S.Context, Prefix: nullptr, NS: S.getStdNamespace()), NamedType: T);
12298}
12299
12300QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12301 if (!StdInitializerList) {
12302 bool WasMalformed = false;
12303 StdInitializerList =
12304 LookupStdClassTemplate(S&: *this, Loc, ClassName: "initializer_list", WasMalformed: &WasMalformed);
12305 if (!StdInitializerList) {
12306 if (!WasMalformed)
12307 Diag(Loc, DiagID: diag::err_implied_std_initializer_list_not_found);
12308 return QualType();
12309 }
12310 }
12311 return BuildStdClassTemplate(S&: *this, CTD: StdInitializerList, TypeParam: Element, Loc);
12312}
12313
12314QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {
12315 if (!StdTypeIdentity) {
12316 StdTypeIdentity = LookupStdClassTemplate(S&: *this, Loc, ClassName: "type_identity",
12317 /*WasMalformed=*/nullptr);
12318 if (!StdTypeIdentity)
12319 return QualType();
12320 }
12321 return BuildStdClassTemplate(S&: *this, CTD: StdTypeIdentity, TypeParam: Type, Loc);
12322}
12323
12324bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12325 // C++ [dcl.init.list]p2:
12326 // A constructor is an initializer-list constructor if its first parameter
12327 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12328 // std::initializer_list<E> for some type E, and either there are no other
12329 // parameters or else all other parameters have default arguments.
12330 if (!Ctor->hasOneParamOrDefaultArgs())
12331 return false;
12332
12333 QualType ArgType = Ctor->getParamDecl(i: 0)->getType();
12334 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12335 ArgType = RT->getPointeeType().getUnqualifiedType();
12336
12337 return isStdInitializerList(Ty: ArgType, Element: nullptr);
12338}
12339
12340/// Determine whether a using statement is in a context where it will be
12341/// apply in all contexts.
12342static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12343 switch (CurContext->getDeclKind()) {
12344 case Decl::TranslationUnit:
12345 return true;
12346 case Decl::LinkageSpec:
12347 return IsUsingDirectiveInToplevelContext(CurContext: CurContext->getParent());
12348 default:
12349 return false;
12350 }
12351}
12352
12353namespace {
12354
12355// Callback to only accept typo corrections that are namespaces.
12356class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12357public:
12358 bool ValidateCandidate(const TypoCorrection &candidate) override {
12359 if (NamedDecl *ND = candidate.getCorrectionDecl())
12360 return isa<NamespaceDecl>(Val: ND) || isa<NamespaceAliasDecl>(Val: ND);
12361 return false;
12362 }
12363
12364 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12365 return std::make_unique<NamespaceValidatorCCC>(args&: *this);
12366 }
12367};
12368
12369}
12370
12371static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12372 Sema &S) {
12373 auto *ND = cast<NamespaceDecl>(Val: Corrected.getFoundDecl());
12374 Module *M = ND->getOwningModule();
12375 assert(M && "hidden namespace definition not in a module?");
12376
12377 if (M->isExplicitGlobalModule())
12378 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12379 DiagID: diag::err_module_unimported_use_header)
12380 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12381 << /*Header Name*/ false;
12382 else
12383 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12384 DiagID: diag::err_module_unimported_use)
12385 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12386 << M->getTopLevelModuleName();
12387}
12388
12389static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12390 CXXScopeSpec &SS,
12391 SourceLocation IdentLoc,
12392 IdentifierInfo *Ident) {
12393 R.clear();
12394 NamespaceValidatorCCC CCC{};
12395 if (TypoCorrection Corrected =
12396 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Sc, SS: &SS, CCC,
12397 Mode: CorrectTypoKind::ErrorRecovery)) {
12398 // Generally we find it is confusing more than helpful to diagnose the
12399 // invisible namespace.
12400 // See https://github.com/llvm/llvm-project/issues/73893.
12401 //
12402 // However, we should diagnose when the users are trying to using an
12403 // invisible namespace. So we handle the case specially here.
12404 if (isa_and_nonnull<NamespaceDecl>(Val: Corrected.getFoundDecl()) &&
12405 Corrected.requiresImport()) {
12406 DiagnoseInvisibleNamespace(Corrected, S);
12407 } else if (DeclContext *DC = S.computeDeclContext(SS, EnteringContext: false)) {
12408 std::string CorrectedStr(Corrected.getAsString(LO: S.getLangOpts()));
12409 bool DroppedSpecifier =
12410 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12411 S.diagnoseTypo(Correction: Corrected,
12412 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_member_suggest)
12413 << Ident << DC << DroppedSpecifier << SS.getRange(),
12414 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12415 } else {
12416 S.diagnoseTypo(Correction: Corrected,
12417 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_suggest) << Ident,
12418 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12419 }
12420 R.addDecl(D: Corrected.getFoundDecl());
12421 return true;
12422 }
12423 return false;
12424}
12425
12426Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12427 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12428 SourceLocation IdentLoc,
12429 IdentifierInfo *NamespcName,
12430 const ParsedAttributesView &AttrList) {
12431 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12432 assert(NamespcName && "Invalid NamespcName.");
12433 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12434
12435 // Get the innermost enclosing declaration scope.
12436 S = S->getDeclParent();
12437
12438 UsingDirectiveDecl *UDir = nullptr;
12439 NestedNameSpecifier *Qualifier = nullptr;
12440 if (SS.isSet())
12441 Qualifier = SS.getScopeRep();
12442
12443 // Lookup namespace name.
12444 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12445 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
12446 if (R.isAmbiguous())
12447 return nullptr;
12448
12449 if (R.empty()) {
12450 R.clear();
12451 // Allow "using namespace std;" or "using namespace ::std;" even if
12452 // "std" hasn't been defined yet, for GCC compatibility.
12453 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12454 NamespcName->isStr(Str: "std")) {
12455 Diag(Loc: IdentLoc, DiagID: diag::ext_using_undefined_std);
12456 R.addDecl(D: getOrCreateStdNamespace());
12457 R.resolveKind();
12458 }
12459 // Otherwise, attempt typo correction.
12460 else TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident: NamespcName);
12461 }
12462
12463 if (!R.empty()) {
12464 NamedDecl *Named = R.getRepresentativeDecl();
12465 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12466 assert(NS && "expected namespace decl");
12467
12468 // The use of a nested name specifier may trigger deprecation warnings.
12469 DiagnoseUseOfDecl(D: Named, Locs: IdentLoc);
12470
12471 // C++ [namespace.udir]p1:
12472 // A using-directive specifies that the names in the nominated
12473 // namespace can be used in the scope in which the
12474 // using-directive appears after the using-directive. During
12475 // unqualified name lookup (3.4.1), the names appear as if they
12476 // were declared in the nearest enclosing namespace which
12477 // contains both the using-directive and the nominated
12478 // namespace. [Note: in this context, "contains" means "contains
12479 // directly or indirectly". ]
12480
12481 // Find enclosing context containing both using-directive and
12482 // nominated namespace.
12483 DeclContext *CommonAncestor = NS;
12484 while (CommonAncestor && !CommonAncestor->Encloses(DC: CurContext))
12485 CommonAncestor = CommonAncestor->getParent();
12486
12487 UDir = UsingDirectiveDecl::Create(C&: Context, DC: CurContext, UsingLoc, NamespaceLoc: NamespcLoc,
12488 QualifierLoc: SS.getWithLocInContext(Context),
12489 IdentLoc, Nominated: Named, CommonAncestor);
12490
12491 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12492 !SourceMgr.isInMainFile(Loc: SourceMgr.getExpansionLoc(Loc: IdentLoc))) {
12493 Diag(Loc: IdentLoc, DiagID: diag::warn_using_directive_in_header);
12494 }
12495
12496 PushUsingDirective(S, UDir);
12497 } else {
12498 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
12499 }
12500
12501 if (UDir) {
12502 ProcessDeclAttributeList(S, D: UDir, AttrList);
12503 ProcessAPINotes(D: UDir);
12504 }
12505
12506 return UDir;
12507}
12508
12509void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12510 // If the scope has an associated entity and the using directive is at
12511 // namespace or translation unit scope, add the UsingDirectiveDecl into
12512 // its lookup structure so qualified name lookup can find it.
12513 DeclContext *Ctx = S->getEntity();
12514 if (Ctx && !Ctx->isFunctionOrMethod())
12515 Ctx->addDecl(D: UDir);
12516 else
12517 // Otherwise, it is at block scope. The using-directives will affect lookup
12518 // only to the end of the scope.
12519 S->PushUsingDirective(UDir);
12520}
12521
12522Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12523 SourceLocation UsingLoc,
12524 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12525 UnqualifiedId &Name,
12526 SourceLocation EllipsisLoc,
12527 const ParsedAttributesView &AttrList) {
12528 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12529
12530 if (SS.isEmpty()) {
12531 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_requires_qualname);
12532 return nullptr;
12533 }
12534
12535 switch (Name.getKind()) {
12536 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12537 case UnqualifiedIdKind::IK_Identifier:
12538 case UnqualifiedIdKind::IK_OperatorFunctionId:
12539 case UnqualifiedIdKind::IK_LiteralOperatorId:
12540 case UnqualifiedIdKind::IK_ConversionFunctionId:
12541 break;
12542
12543 case UnqualifiedIdKind::IK_ConstructorName:
12544 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12545 // C++11 inheriting constructors.
12546 Diag(Loc: Name.getBeginLoc(),
12547 DiagID: getLangOpts().CPlusPlus11
12548 ? diag::warn_cxx98_compat_using_decl_constructor
12549 : diag::err_using_decl_constructor)
12550 << SS.getRange();
12551
12552 if (getLangOpts().CPlusPlus11) break;
12553
12554 return nullptr;
12555
12556 case UnqualifiedIdKind::IK_DestructorName:
12557 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_destructor) << SS.getRange();
12558 return nullptr;
12559
12560 case UnqualifiedIdKind::IK_TemplateId:
12561 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_template_id)
12562 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12563 return nullptr;
12564
12565 case UnqualifiedIdKind::IK_DeductionGuideName:
12566 llvm_unreachable("cannot parse qualified deduction guide name");
12567 }
12568
12569 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12570 DeclarationName TargetName = TargetNameInfo.getName();
12571 if (!TargetName)
12572 return nullptr;
12573
12574 // Warn about access declarations.
12575 if (UsingLoc.isInvalid()) {
12576 Diag(Loc: Name.getBeginLoc(), DiagID: getLangOpts().CPlusPlus11
12577 ? diag::err_access_decl
12578 : diag::warn_access_decl_deprecated)
12579 << FixItHint::CreateInsertion(InsertionLoc: SS.getRange().getBegin(), Code: "using ");
12580 }
12581
12582 if (EllipsisLoc.isInvalid()) {
12583 if (DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_UsingDeclaration) ||
12584 DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC: UPPC_UsingDeclaration))
12585 return nullptr;
12586 } else {
12587 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
12588 !TargetNameInfo.containsUnexpandedParameterPack()) {
12589 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
12590 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12591 EllipsisLoc = SourceLocation();
12592 }
12593 }
12594
12595 NamedDecl *UD =
12596 BuildUsingDeclaration(S, AS, UsingLoc, HasTypenameKeyword: TypenameLoc.isValid(), TypenameLoc,
12597 SS, NameInfo: TargetNameInfo, EllipsisLoc, AttrList,
12598 /*IsInstantiation*/ false,
12599 IsUsingIfExists: AttrList.hasAttribute(K: ParsedAttr::AT_UsingIfExists));
12600 if (UD)
12601 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12602
12603 return UD;
12604}
12605
12606Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12607 SourceLocation UsingLoc,
12608 SourceLocation EnumLoc, SourceRange TyLoc,
12609 const IdentifierInfo &II, ParsedType Ty,
12610 CXXScopeSpec *SS) {
12611 assert(SS && !SS->isInvalid() && "ScopeSpec is invalid");
12612 TypeSourceInfo *TSI = nullptr;
12613 SourceLocation IdentLoc = TyLoc.getBegin();
12614 QualType EnumTy = GetTypeFromParser(Ty, TInfo: &TSI);
12615 if (EnumTy.isNull()) {
12616 Diag(Loc: IdentLoc, DiagID: isDependentScopeSpecifier(SS: *SS)
12617 ? diag::err_using_enum_is_dependent
12618 : diag::err_unknown_typename)
12619 << II.getName() << SourceRange(SS->getBeginLoc(), TyLoc.getEnd());
12620 return nullptr;
12621 }
12622
12623 if (EnumTy->isDependentType()) {
12624 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_is_dependent);
12625 return nullptr;
12626 }
12627
12628 auto *Enum = dyn_cast_if_present<EnumDecl>(Val: EnumTy->getAsTagDecl());
12629 if (!Enum) {
12630 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_not_enum) << EnumTy;
12631 return nullptr;
12632 }
12633
12634 if (auto *Def = Enum->getDefinition())
12635 Enum = Def;
12636
12637 if (TSI == nullptr)
12638 TSI = Context.getTrivialTypeSourceInfo(T: EnumTy, Loc: IdentLoc);
12639
12640 auto *UD =
12641 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, NameLoc: IdentLoc, EnumType: TSI, ED: Enum);
12642
12643 if (UD)
12644 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12645
12646 return UD;
12647}
12648
12649/// Determine whether a using declaration considers the given
12650/// declarations as "equivalent", e.g., if they are redeclarations of
12651/// the same entity or are both typedefs of the same type.
12652static bool
12653IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12654 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12655 return true;
12656
12657 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(Val: D1))
12658 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(Val: D2))
12659 return Context.hasSameType(T1: TD1->getUnderlyingType(),
12660 T2: TD2->getUnderlyingType());
12661
12662 // Two using_if_exists using-declarations are equivalent if both are
12663 // unresolved.
12664 if (isa<UnresolvedUsingIfExistsDecl>(Val: D1) &&
12665 isa<UnresolvedUsingIfExistsDecl>(Val: D2))
12666 return true;
12667
12668 return false;
12669}
12670
12671bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12672 const LookupResult &Previous,
12673 UsingShadowDecl *&PrevShadow) {
12674 // Diagnose finding a decl which is not from a base class of the
12675 // current class. We do this now because there are cases where this
12676 // function will silently decide not to build a shadow decl, which
12677 // will pre-empt further diagnostics.
12678 //
12679 // We don't need to do this in C++11 because we do the check once on
12680 // the qualifier.
12681 //
12682 // FIXME: diagnose the following if we care enough:
12683 // struct A { int foo; };
12684 // struct B : A { using A::foo; };
12685 // template <class T> struct C : A {};
12686 // template <class T> struct D : C<T> { using B::foo; } // <---
12687 // This is invalid (during instantiation) in C++03 because B::foo
12688 // resolves to the using decl in B, which is not a base class of D<T>.
12689 // We can't diagnose it immediately because C<T> is an unknown
12690 // specialization. The UsingShadowDecl in D<T> then points directly
12691 // to A::foo, which will look well-formed when we instantiate.
12692 // The right solution is to not collapse the shadow-decl chain.
12693 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12694 if (auto *Using = dyn_cast<UsingDecl>(Val: BUD)) {
12695 DeclContext *OrigDC = Orig->getDeclContext();
12696
12697 // Handle enums and anonymous structs.
12698 if (isa<EnumDecl>(Val: OrigDC))
12699 OrigDC = OrigDC->getParent();
12700 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(Val: OrigDC);
12701 while (OrigRec->isAnonymousStructOrUnion())
12702 OrigRec = cast<CXXRecordDecl>(Val: OrigRec->getDeclContext());
12703
12704 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(Base: OrigRec)) {
12705 if (OrigDC == CurContext) {
12706 Diag(Loc: Using->getLocation(),
12707 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
12708 << Using->getQualifierLoc().getSourceRange();
12709 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12710 Using->setInvalidDecl();
12711 return true;
12712 }
12713
12714 Diag(Loc: Using->getQualifierLoc().getBeginLoc(),
12715 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
12716 << Using->getQualifier() << cast<CXXRecordDecl>(Val: CurContext)
12717 << Using->getQualifierLoc().getSourceRange();
12718 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12719 Using->setInvalidDecl();
12720 return true;
12721 }
12722 }
12723
12724 if (Previous.empty()) return false;
12725
12726 NamedDecl *Target = Orig;
12727 if (isa<UsingShadowDecl>(Val: Target))
12728 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12729
12730 // If the target happens to be one of the previous declarations, we
12731 // don't have a conflict.
12732 //
12733 // FIXME: but we might be increasing its access, in which case we
12734 // should redeclare it.
12735 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12736 bool FoundEquivalentDecl = false;
12737 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12738 I != E; ++I) {
12739 NamedDecl *D = (*I)->getUnderlyingDecl();
12740 // We can have UsingDecls in our Previous results because we use the same
12741 // LookupResult for checking whether the UsingDecl itself is a valid
12742 // redeclaration.
12743 if (isa<UsingDecl>(Val: D) || isa<UsingPackDecl>(Val: D) || isa<UsingEnumDecl>(Val: D))
12744 continue;
12745
12746 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
12747 // C++ [class.mem]p19:
12748 // If T is the name of a class, then [every named member other than
12749 // a non-static data member] shall have a name different from T
12750 if (RD->isInjectedClassName() && !isa<FieldDecl>(Val: Target) &&
12751 !isa<IndirectFieldDecl>(Val: Target) &&
12752 !isa<UnresolvedUsingValueDecl>(Val: Target) &&
12753 DiagnoseClassNameShadow(
12754 DC: CurContext,
12755 Info: DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12756 return true;
12757 }
12758
12759 if (IsEquivalentForUsingDecl(Context, D1: D, D2: Target)) {
12760 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: *I))
12761 PrevShadow = Shadow;
12762 FoundEquivalentDecl = true;
12763 } else if (isEquivalentInternalLinkageDeclaration(A: D, B: Target)) {
12764 // We don't conflict with an existing using shadow decl of an equivalent
12765 // declaration, but we're not a redeclaration of it.
12766 FoundEquivalentDecl = true;
12767 }
12768
12769 if (isVisible(D))
12770 (isa<TagDecl>(Val: D) ? Tag : NonTag) = D;
12771 }
12772
12773 if (FoundEquivalentDecl)
12774 return false;
12775
12776 // Always emit a diagnostic for a mismatch between an unresolved
12777 // using_if_exists and a resolved using declaration in either direction.
12778 if (isa<UnresolvedUsingIfExistsDecl>(Val: Target) !=
12779 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(Val: NonTag))) {
12780 if (!NonTag && !Tag)
12781 return false;
12782 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12783 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12784 Diag(Loc: (NonTag ? NonTag : Tag)->getLocation(),
12785 DiagID: diag::note_using_decl_conflict);
12786 BUD->setInvalidDecl();
12787 return true;
12788 }
12789
12790 if (FunctionDecl *FD = Target->getAsFunction()) {
12791 NamedDecl *OldDecl = nullptr;
12792 switch (CheckOverload(S: nullptr, New: FD, OldDecls: Previous, OldDecl,
12793 /*IsForUsingDecl*/ UseMemberUsingDeclRules: true)) {
12794 case OverloadKind::Overload:
12795 return false;
12796
12797 case OverloadKind::NonFunction:
12798 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12799 break;
12800
12801 // We found a decl with the exact signature.
12802 case OverloadKind::Match:
12803 // If we're in a record, we want to hide the target, so we
12804 // return true (without a diagnostic) to tell the caller not to
12805 // build a shadow decl.
12806 if (CurContext->isRecord())
12807 return true;
12808
12809 // If we're not in a record, this is an error.
12810 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12811 break;
12812 }
12813
12814 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12815 Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_using_decl_conflict);
12816 BUD->setInvalidDecl();
12817 return true;
12818 }
12819
12820 // Target is not a function.
12821
12822 if (isa<TagDecl>(Val: Target)) {
12823 // No conflict between a tag and a non-tag.
12824 if (!Tag) return false;
12825
12826 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12827 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12828 Diag(Loc: Tag->getLocation(), DiagID: diag::note_using_decl_conflict);
12829 BUD->setInvalidDecl();
12830 return true;
12831 }
12832
12833 // No conflict between a tag and a non-tag.
12834 if (!NonTag) return false;
12835
12836 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12837 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12838 Diag(Loc: NonTag->getLocation(), DiagID: diag::note_using_decl_conflict);
12839 BUD->setInvalidDecl();
12840 return true;
12841}
12842
12843/// Determine whether a direct base class is a virtual base class.
12844static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12845 if (!Derived->getNumVBases())
12846 return false;
12847 for (auto &B : Derived->bases())
12848 if (B.getType()->getAsCXXRecordDecl() == Base)
12849 return B.isVirtual();
12850 llvm_unreachable("not a direct base class");
12851}
12852
12853UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12854 NamedDecl *Orig,
12855 UsingShadowDecl *PrevDecl) {
12856 // If we resolved to another shadow declaration, just coalesce them.
12857 NamedDecl *Target = Orig;
12858 if (isa<UsingShadowDecl>(Val: Target)) {
12859 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12860 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12861 }
12862
12863 NamedDecl *NonTemplateTarget = Target;
12864 if (auto *TargetTD = dyn_cast<TemplateDecl>(Val: Target))
12865 NonTemplateTarget = TargetTD->getTemplatedDecl();
12866
12867 UsingShadowDecl *Shadow;
12868 if (NonTemplateTarget && isa<CXXConstructorDecl>(Val: NonTemplateTarget)) {
12869 UsingDecl *Using = cast<UsingDecl>(Val: BUD);
12870 bool IsVirtualBase =
12871 isVirtualDirectBase(Derived: cast<CXXRecordDecl>(Val: CurContext),
12872 Base: Using->getQualifier()->getAsRecordDecl());
12873 Shadow = ConstructorUsingShadowDecl::Create(
12874 C&: Context, DC: CurContext, Loc: Using->getLocation(), Using, Target: Orig, IsVirtual: IsVirtualBase);
12875 } else {
12876 Shadow = UsingShadowDecl::Create(C&: Context, DC: CurContext, Loc: BUD->getLocation(),
12877 Name: Target->getDeclName(), Introducer: BUD, Target);
12878 }
12879 BUD->addShadowDecl(S: Shadow);
12880
12881 Shadow->setAccess(BUD->getAccess());
12882 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12883 Shadow->setInvalidDecl();
12884
12885 Shadow->setPreviousDecl(PrevDecl);
12886
12887 if (S)
12888 PushOnScopeChains(D: Shadow, S);
12889 else
12890 CurContext->addDecl(D: Shadow);
12891
12892
12893 return Shadow;
12894}
12895
12896void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12897 if (Shadow->getDeclName().getNameKind() ==
12898 DeclarationName::CXXConversionFunctionName)
12899 cast<CXXRecordDecl>(Val: Shadow->getDeclContext())->removeConversion(Old: Shadow);
12900
12901 // Remove it from the DeclContext...
12902 Shadow->getDeclContext()->removeDecl(D: Shadow);
12903
12904 // ...and the scope, if applicable...
12905 if (S) {
12906 S->RemoveDecl(D: Shadow);
12907 IdResolver.RemoveDecl(D: Shadow);
12908 }
12909
12910 // ...and the using decl.
12911 Shadow->getIntroducer()->removeShadowDecl(S: Shadow);
12912
12913 // TODO: complain somehow if Shadow was used. It shouldn't
12914 // be possible for this to happen, because...?
12915}
12916
12917/// Find the base specifier for a base class with the given type.
12918static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12919 QualType DesiredBase,
12920 bool &AnyDependentBases) {
12921 // Check whether the named type is a direct base class.
12922 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12923 .getUnqualifiedType();
12924 for (auto &Base : Derived->bases()) {
12925 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12926 if (CanonicalDesiredBase == BaseType)
12927 return &Base;
12928 if (BaseType->isDependentType())
12929 AnyDependentBases = true;
12930 }
12931 return nullptr;
12932}
12933
12934namespace {
12935class UsingValidatorCCC final : public CorrectionCandidateCallback {
12936public:
12937 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12938 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12939 : HasTypenameKeyword(HasTypenameKeyword),
12940 IsInstantiation(IsInstantiation), OldNNS(NNS),
12941 RequireMemberOf(RequireMemberOf) {}
12942
12943 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12944 NamedDecl *ND = Candidate.getCorrectionDecl();
12945
12946 // Keywords are not valid here.
12947 if (!ND || isa<NamespaceDecl>(Val: ND))
12948 return false;
12949
12950 // Completely unqualified names are invalid for a 'using' declaration.
12951 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12952 return false;
12953
12954 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12955 // reject.
12956
12957 if (RequireMemberOf) {
12958 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
12959 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12960 // No-one ever wants a using-declaration to name an injected-class-name
12961 // of a base class, unless they're declaring an inheriting constructor.
12962 ASTContext &Ctx = ND->getASTContext();
12963 if (!Ctx.getLangOpts().CPlusPlus11)
12964 return false;
12965 QualType FoundType = Ctx.getRecordType(Decl: FoundRecord);
12966
12967 // Check that the injected-class-name is named as a member of its own
12968 // type; we don't want to suggest 'using Derived::Base;', since that
12969 // means something else.
12970 NestedNameSpecifier *Specifier =
12971 Candidate.WillReplaceSpecifier()
12972 ? Candidate.getCorrectionSpecifier()
12973 : OldNNS;
12974 if (!Specifier->getAsType() ||
12975 !Ctx.hasSameType(T1: QualType(Specifier->getAsType(), 0), T2: FoundType))
12976 return false;
12977
12978 // Check that this inheriting constructor declaration actually names a
12979 // direct base class of the current class.
12980 bool AnyDependentBases = false;
12981 if (!findDirectBaseWithType(Derived: RequireMemberOf,
12982 DesiredBase: Ctx.getRecordType(Decl: FoundRecord),
12983 AnyDependentBases) &&
12984 !AnyDependentBases)
12985 return false;
12986 } else {
12987 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND->getDeclContext());
12988 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(Base: RD))
12989 return false;
12990
12991 // FIXME: Check that the base class member is accessible?
12992 }
12993 } else {
12994 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
12995 if (FoundRecord && FoundRecord->isInjectedClassName())
12996 return false;
12997 }
12998
12999 if (isa<TypeDecl>(Val: ND))
13000 return HasTypenameKeyword || !IsInstantiation;
13001
13002 return !HasTypenameKeyword;
13003 }
13004
13005 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13006 return std::make_unique<UsingValidatorCCC>(args&: *this);
13007 }
13008
13009private:
13010 bool HasTypenameKeyword;
13011 bool IsInstantiation;
13012 NestedNameSpecifier *OldNNS;
13013 CXXRecordDecl *RequireMemberOf;
13014};
13015} // end anonymous namespace
13016
13017void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
13018 // It is really dumb that we have to do this.
13019 LookupResult::Filter F = Previous.makeFilter();
13020 while (F.hasNext()) {
13021 NamedDecl *D = F.next();
13022 if (!isDeclInScope(D, Ctx: CurContext, S))
13023 F.erase();
13024 // If we found a local extern declaration that's not ordinarily visible,
13025 // and this declaration is being added to a non-block scope, ignore it.
13026 // We're only checking for scope conflicts here, not also for violations
13027 // of the linkage rules.
13028 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13029 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
13030 F.erase();
13031 }
13032 F.done();
13033}
13034
13035NamedDecl *Sema::BuildUsingDeclaration(
13036 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13037 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13038 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13039 const ParsedAttributesView &AttrList, bool IsInstantiation,
13040 bool IsUsingIfExists) {
13041 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13042 SourceLocation IdentLoc = NameInfo.getLoc();
13043 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13044
13045 // FIXME: We ignore attributes for now.
13046
13047 // For an inheriting constructor declaration, the name of the using
13048 // declaration is the name of a constructor in this class, not in the
13049 // base class.
13050 DeclarationNameInfo UsingName = NameInfo;
13051 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
13052 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext))
13053 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13054 Ty: Context.getCanonicalType(T: Context.getRecordType(Decl: RD))));
13055
13056 // Do the redeclaration lookup in the current scope.
13057 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13058 RedeclarationKind::ForVisibleRedeclaration);
13059 Previous.setHideTags(false);
13060 if (S) {
13061 LookupName(R&: Previous, S);
13062
13063 FilterUsingLookup(S, Previous);
13064 } else {
13065 assert(IsInstantiation && "no scope in non-instantiation");
13066 if (CurContext->isRecord())
13067 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13068 else {
13069 // No redeclaration check is needed here; in non-member contexts we
13070 // diagnosed all possible conflicts with other using-declarations when
13071 // building the template:
13072 //
13073 // For a dependent non-type using declaration, the only valid case is
13074 // if we instantiate to a single enumerator. We check for conflicts
13075 // between shadow declarations we introduce, and we check in the template
13076 // definition for conflicts between a non-type using declaration and any
13077 // other declaration, which together covers all cases.
13078 //
13079 // A dependent typename using declaration will never successfully
13080 // instantiate, since it will always name a class member, so we reject
13081 // that in the template definition.
13082 }
13083 }
13084
13085 // Check for invalid redeclarations.
13086 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13087 SS, NameLoc: IdentLoc, Previous))
13088 return nullptr;
13089
13090 // 'using_if_exists' doesn't make sense on an inherited constructor.
13091 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13092 DeclarationName::CXXConstructorName) {
13093 Diag(Loc: UsingLoc, DiagID: diag::err_using_if_exists_on_ctor);
13094 return nullptr;
13095 }
13096
13097 DeclContext *LookupContext = computeDeclContext(SS);
13098 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13099 if (!LookupContext || EllipsisLoc.isValid()) {
13100 NamedDecl *D;
13101 // Dependent scope, or an unexpanded pack
13102 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword,
13103 SS, NameInfo, NameLoc: IdentLoc))
13104 return nullptr;
13105
13106 if (Previous.isSingleResult() &&
13107 Previous.getFoundDecl()->isTemplateParameter())
13108 DiagnoseTemplateParameterShadow(Loc: IdentLoc, PrevDecl: Previous.getFoundDecl());
13109
13110 if (HasTypenameKeyword) {
13111 // FIXME: not all declaration name kinds are legal here
13112 D = UnresolvedUsingTypenameDecl::Create(C&: Context, DC: CurContext,
13113 UsingLoc, TypenameLoc,
13114 QualifierLoc,
13115 TargetNameLoc: IdentLoc, TargetName: NameInfo.getName(),
13116 EllipsisLoc);
13117 } else {
13118 D = UnresolvedUsingValueDecl::Create(C&: Context, DC: CurContext, UsingLoc,
13119 QualifierLoc, NameInfo, EllipsisLoc);
13120 }
13121 D->setAccess(AS);
13122 CurContext->addDecl(D);
13123 ProcessDeclAttributeList(S, D, AttrList);
13124 return D;
13125 }
13126
13127 auto Build = [&](bool Invalid) {
13128 UsingDecl *UD =
13129 UsingDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, QualifierLoc,
13130 NameInfo: UsingName, HasTypenameKeyword);
13131 UD->setAccess(AS);
13132 CurContext->addDecl(D: UD);
13133 ProcessDeclAttributeList(S, D: UD, AttrList);
13134 UD->setInvalidDecl(Invalid);
13135 return UD;
13136 };
13137 auto BuildInvalid = [&]{ return Build(true); };
13138 auto BuildValid = [&]{ return Build(false); };
13139
13140 if (RequireCompleteDeclContext(SS, DC: LookupContext))
13141 return BuildInvalid();
13142
13143 // Look up the target name.
13144 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13145
13146 // Unlike most lookups, we don't always want to hide tag
13147 // declarations: tag names are visible through the using declaration
13148 // even if hidden by ordinary names, *except* in a dependent context
13149 // where they may be used by two-phase lookup.
13150 if (!IsInstantiation)
13151 R.setHideTags(false);
13152
13153 // For the purposes of this lookup, we have a base object type
13154 // equal to that of the current context.
13155 if (CurContext->isRecord()) {
13156 R.setBaseObjectType(
13157 Context.getTypeDeclType(Decl: cast<CXXRecordDecl>(Val: CurContext)));
13158 }
13159
13160 LookupQualifiedName(R, LookupCtx: LookupContext);
13161
13162 // Validate the context, now we have a lookup
13163 if (CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, SS, NameInfo,
13164 NameLoc: IdentLoc, R: &R))
13165 return nullptr;
13166
13167 if (R.empty() && IsUsingIfExists)
13168 R.addDecl(D: UnresolvedUsingIfExistsDecl::Create(Ctx&: Context, DC: CurContext, Loc: UsingLoc,
13169 Name: UsingName.getName()),
13170 AS: AS_public);
13171
13172 // Try to correct typos if possible. If constructor name lookup finds no
13173 // results, that means the named class has no explicit constructors, and we
13174 // suppressed declaring implicit ones (probably because it's dependent or
13175 // invalid).
13176 if (R.empty() &&
13177 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
13178 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13179 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13180 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13181 auto *II = NameInfo.getName().getAsIdentifierInfo();
13182 if (getLangOpts().CPlusPlus14 && II && II->isStr(Str: "gets") &&
13183 CurContext->isStdNamespace() &&
13184 isa<TranslationUnitDecl>(Val: LookupContext) &&
13185 PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2016'12'21) &&
13186 getSourceManager().isInSystemHeader(Loc: UsingLoc))
13187 return nullptr;
13188 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13189 dyn_cast<CXXRecordDecl>(Val: CurContext));
13190 if (TypoCorrection Corrected =
13191 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
13192 Mode: CorrectTypoKind::ErrorRecovery)) {
13193 // We reject candidates where DroppedSpecifier == true, hence the
13194 // literal '0' below.
13195 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
13196 << NameInfo.getName() << LookupContext << 0
13197 << SS.getRange());
13198
13199 // If we picked a correction with no attached Decl we can't do anything
13200 // useful with it, bail out.
13201 NamedDecl *ND = Corrected.getCorrectionDecl();
13202 if (!ND)
13203 return BuildInvalid();
13204
13205 // If we corrected to an inheriting constructor, handle it as one.
13206 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
13207 if (RD && RD->isInjectedClassName()) {
13208 // The parent of the injected class name is the class itself.
13209 RD = cast<CXXRecordDecl>(Val: RD->getParent());
13210
13211 // Fix up the information we'll use to build the using declaration.
13212 if (Corrected.WillReplaceSpecifier()) {
13213 NestedNameSpecifierLocBuilder Builder;
13214 Builder.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
13215 R: QualifierLoc.getSourceRange());
13216 QualifierLoc = Builder.getWithLocInContext(Context);
13217 }
13218
13219 // In this case, the name we introduce is the name of a derived class
13220 // constructor.
13221 auto *CurClass = cast<CXXRecordDecl>(Val: CurContext);
13222 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13223 Ty: Context.getCanonicalType(T: Context.getRecordType(Decl: CurClass))));
13224 UsingName.setNamedTypeInfo(nullptr);
13225 for (auto *Ctor : LookupConstructors(Class: RD))
13226 R.addDecl(D: Ctor);
13227 R.resolveKind();
13228 } else {
13229 // FIXME: Pick up all the declarations if we found an overloaded
13230 // function.
13231 UsingName.setName(ND->getDeclName());
13232 R.addDecl(D: ND);
13233 }
13234 } else {
13235 Diag(Loc: IdentLoc, DiagID: diag::err_no_member)
13236 << NameInfo.getName() << LookupContext << SS.getRange();
13237 return BuildInvalid();
13238 }
13239 }
13240
13241 if (R.isAmbiguous())
13242 return BuildInvalid();
13243
13244 if (HasTypenameKeyword) {
13245 // If we asked for a typename and got a non-type decl, error out.
13246 if (!R.getAsSingle<TypeDecl>() &&
13247 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13248 Diag(Loc: IdentLoc, DiagID: diag::err_using_typename_non_type);
13249 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13250 Diag(Loc: (*I)->getUnderlyingDecl()->getLocation(),
13251 DiagID: diag::note_using_decl_target);
13252 return BuildInvalid();
13253 }
13254 } else {
13255 // If we asked for a non-typename and we got a type, error out,
13256 // but only if this is an instantiation of an unresolved using
13257 // decl. Otherwise just silently find the type name.
13258 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13259 Diag(Loc: IdentLoc, DiagID: diag::err_using_dependent_value_is_type);
13260 Diag(Loc: R.getFoundDecl()->getLocation(), DiagID: diag::note_using_decl_target);
13261 return BuildInvalid();
13262 }
13263 }
13264
13265 // C++14 [namespace.udecl]p6:
13266 // A using-declaration shall not name a namespace.
13267 if (R.getAsSingle<NamespaceDecl>()) {
13268 Diag(Loc: IdentLoc, DiagID: diag::err_using_decl_can_not_refer_to_namespace)
13269 << SS.getRange();
13270 // Suggest using 'using namespace ...' instead.
13271 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_namespace_using_decl)
13272 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "namespace ");
13273 return BuildInvalid();
13274 }
13275
13276 UsingDecl *UD = BuildValid();
13277
13278 // Some additional rules apply to inheriting constructors.
13279 if (UsingName.getName().getNameKind() ==
13280 DeclarationName::CXXConstructorName) {
13281 // Suppress access diagnostics; the access check is instead performed at the
13282 // point of use for an inheriting constructor.
13283 R.suppressDiagnostics();
13284 if (CheckInheritingConstructorUsingDecl(UD))
13285 return UD;
13286 }
13287
13288 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
13289 UsingShadowDecl *PrevDecl = nullptr;
13290 if (!CheckUsingShadowDecl(BUD: UD, Orig: *I, Previous, PrevShadow&: PrevDecl))
13291 BuildUsingShadowDecl(S, BUD: UD, Orig: *I, PrevDecl);
13292 }
13293
13294 return UD;
13295}
13296
13297NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13298 SourceLocation UsingLoc,
13299 SourceLocation EnumLoc,
13300 SourceLocation NameLoc,
13301 TypeSourceInfo *EnumType,
13302 EnumDecl *ED) {
13303 bool Invalid = false;
13304
13305 if (CurContext->getRedeclContext()->isRecord()) {
13306 /// In class scope, check if this is a duplicate, for better a diagnostic.
13307 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13308 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13309 RedeclarationKind::ForVisibleRedeclaration);
13310
13311 LookupName(R&: Previous, S);
13312
13313 for (NamedDecl *D : Previous)
13314 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(Val: D))
13315 if (UED->getEnumDecl() == ED) {
13316 Diag(Loc: UsingLoc, DiagID: diag::err_using_enum_decl_redeclaration)
13317 << SourceRange(EnumLoc, NameLoc);
13318 Diag(Loc: D->getLocation(), DiagID: diag::note_using_enum_decl) << 1;
13319 Invalid = true;
13320 break;
13321 }
13322 }
13323
13324 if (RequireCompleteEnumDecl(D: ED, L: NameLoc))
13325 Invalid = true;
13326
13327 UsingEnumDecl *UD = UsingEnumDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc,
13328 EnumL: EnumLoc, NameL: NameLoc, EnumType);
13329 UD->setAccess(AS);
13330 CurContext->addDecl(D: UD);
13331
13332 if (Invalid) {
13333 UD->setInvalidDecl();
13334 return UD;
13335 }
13336
13337 // Create the shadow decls for each enumerator
13338 for (EnumConstantDecl *EC : ED->enumerators()) {
13339 UsingShadowDecl *PrevDecl = nullptr;
13340 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13341 LookupResult Previous(*this, DNI, LookupOrdinaryName,
13342 RedeclarationKind::ForVisibleRedeclaration);
13343 LookupName(R&: Previous, S);
13344 FilterUsingLookup(S, Previous);
13345
13346 if (!CheckUsingShadowDecl(BUD: UD, Orig: EC, Previous, PrevShadow&: PrevDecl))
13347 BuildUsingShadowDecl(S, BUD: UD, Orig: EC, PrevDecl);
13348 }
13349
13350 return UD;
13351}
13352
13353NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13354 ArrayRef<NamedDecl *> Expansions) {
13355 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13356 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13357 isa<UsingPackDecl>(InstantiatedFrom));
13358
13359 auto *UPD =
13360 UsingPackDecl::Create(C&: Context, DC: CurContext, InstantiatedFrom, UsingDecls: Expansions);
13361 UPD->setAccess(InstantiatedFrom->getAccess());
13362 CurContext->addDecl(D: UPD);
13363 return UPD;
13364}
13365
13366bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13367 assert(!UD->hasTypename() && "expecting a constructor name");
13368
13369 const Type *SourceType = UD->getQualifier()->getAsType();
13370 assert(SourceType &&
13371 "Using decl naming constructor doesn't have type in scope spec.");
13372 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(Val: CurContext);
13373
13374 // Check whether the named type is a direct base class.
13375 bool AnyDependentBases = false;
13376 auto *Base = findDirectBaseWithType(Derived: TargetClass, DesiredBase: QualType(SourceType, 0),
13377 AnyDependentBases);
13378 if (!Base && !AnyDependentBases) {
13379 Diag(Loc: UD->getUsingLoc(),
13380 DiagID: diag::err_using_decl_constructor_not_in_direct_base)
13381 << UD->getNameInfo().getSourceRange()
13382 << QualType(SourceType, 0) << TargetClass;
13383 UD->setInvalidDecl();
13384 return true;
13385 }
13386
13387 if (Base)
13388 Base->setInheritConstructors();
13389
13390 return false;
13391}
13392
13393bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13394 bool HasTypenameKeyword,
13395 const CXXScopeSpec &SS,
13396 SourceLocation NameLoc,
13397 const LookupResult &Prev) {
13398 NestedNameSpecifier *Qual = SS.getScopeRep();
13399
13400 // C++03 [namespace.udecl]p8:
13401 // C++0x [namespace.udecl]p10:
13402 // A using-declaration is a declaration and can therefore be used
13403 // repeatedly where (and only where) multiple declarations are
13404 // allowed.
13405 //
13406 // That's in non-member contexts.
13407 if (!CurContext->getRedeclContext()->isRecord()) {
13408 // A dependent qualifier outside a class can only ever resolve to an
13409 // enumeration type. Therefore it conflicts with any other non-type
13410 // declaration in the same scope.
13411 // FIXME: How should we check for dependent type-type conflicts at block
13412 // scope?
13413 if (Qual->isDependent() && !HasTypenameKeyword) {
13414 for (auto *D : Prev) {
13415 if (!isa<TypeDecl>(Val: D) && !isa<UsingDecl>(Val: D) && !isa<UsingPackDecl>(Val: D)) {
13416 bool OldCouldBeEnumerator =
13417 isa<UnresolvedUsingValueDecl>(Val: D) || isa<EnumConstantDecl>(Val: D);
13418 Diag(Loc: NameLoc,
13419 DiagID: OldCouldBeEnumerator ? diag::err_redefinition
13420 : diag::err_redefinition_different_kind)
13421 << Prev.getLookupName();
13422 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
13423 return true;
13424 }
13425 }
13426 }
13427 return false;
13428 }
13429
13430 const NestedNameSpecifier *CNNS =
13431 Context.getCanonicalNestedNameSpecifier(NNS: Qual);
13432 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13433 NamedDecl *D = *I;
13434
13435 bool DTypename;
13436 NestedNameSpecifier *DQual;
13437 if (UsingDecl *UD = dyn_cast<UsingDecl>(Val: D)) {
13438 DTypename = UD->hasTypename();
13439 DQual = UD->getQualifier();
13440 } else if (UnresolvedUsingValueDecl *UD
13441 = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) {
13442 DTypename = false;
13443 DQual = UD->getQualifier();
13444 } else if (UnresolvedUsingTypenameDecl *UD
13445 = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) {
13446 DTypename = true;
13447 DQual = UD->getQualifier();
13448 } else continue;
13449
13450 // using decls differ if one says 'typename' and the other doesn't.
13451 // FIXME: non-dependent using decls?
13452 if (HasTypenameKeyword != DTypename) continue;
13453
13454 // using decls differ if they name different scopes (but note that
13455 // template instantiation can cause this check to trigger when it
13456 // didn't before instantiation).
13457 if (CNNS != Context.getCanonicalNestedNameSpecifier(NNS: DQual))
13458 continue;
13459
13460 Diag(Loc: NameLoc, DiagID: diag::err_using_decl_redeclaration) << SS.getRange();
13461 Diag(Loc: D->getLocation(), DiagID: diag::note_using_decl) << 1;
13462 return true;
13463 }
13464
13465 return false;
13466}
13467
13468bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13469 const CXXScopeSpec &SS,
13470 const DeclarationNameInfo &NameInfo,
13471 SourceLocation NameLoc,
13472 const LookupResult *R, const UsingDecl *UD) {
13473 DeclContext *NamedContext = computeDeclContext(SS);
13474 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13475 "resolvable context must have exactly one set of decls");
13476
13477 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13478 // relationship.
13479 bool Cxx20Enumerator = false;
13480 if (NamedContext) {
13481 EnumConstantDecl *EC = nullptr;
13482 if (R)
13483 EC = R->getAsSingle<EnumConstantDecl>();
13484 else if (UD && UD->shadow_size() == 1)
13485 EC = dyn_cast<EnumConstantDecl>(Val: UD->shadow_begin()->getTargetDecl());
13486 if (EC)
13487 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13488
13489 if (auto *ED = dyn_cast<EnumDecl>(Val: NamedContext)) {
13490 // C++14 [namespace.udecl]p7:
13491 // A using-declaration shall not name a scoped enumerator.
13492 // C++20 p1099 permits enumerators.
13493 if (EC && R && ED->isScoped())
13494 Diag(Loc: SS.getBeginLoc(),
13495 DiagID: getLangOpts().CPlusPlus20
13496 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13497 : diag::ext_using_decl_scoped_enumerator)
13498 << SS.getRange();
13499
13500 // We want to consider the scope of the enumerator
13501 NamedContext = ED->getDeclContext();
13502 }
13503 }
13504
13505 if (!CurContext->isRecord()) {
13506 // C++03 [namespace.udecl]p3:
13507 // C++0x [namespace.udecl]p8:
13508 // A using-declaration for a class member shall be a member-declaration.
13509 // C++20 [namespace.udecl]p7
13510 // ... other than an enumerator ...
13511
13512 // If we weren't able to compute a valid scope, it might validly be a
13513 // dependent class or enumeration scope. If we have a 'typename' keyword,
13514 // the scope must resolve to a class type.
13515 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13516 : !HasTypename)
13517 return false; // OK
13518
13519 Diag(Loc: NameLoc,
13520 DiagID: Cxx20Enumerator
13521 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13522 : diag::err_using_decl_can_not_refer_to_class_member)
13523 << SS.getRange();
13524
13525 if (Cxx20Enumerator)
13526 return false; // OK
13527
13528 auto *RD = NamedContext
13529 ? cast<CXXRecordDecl>(Val: NamedContext->getRedeclContext())
13530 : nullptr;
13531 if (RD && !RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec &>(SS), DC: RD)) {
13532 // See if there's a helpful fixit
13533
13534 if (!R) {
13535 // We will have already diagnosed the problem on the template
13536 // definition, Maybe we should do so again?
13537 } else if (R->getAsSingle<TypeDecl>()) {
13538 if (getLangOpts().CPlusPlus11) {
13539 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13540 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_using_decl_class_member_workaround)
13541 << diag::MemClassWorkaround::AliasDecl
13542 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(),
13543 Code: NameInfo.getName().getAsString() +
13544 " = ");
13545 } else {
13546 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13547 SourceLocation InsertLoc = getLocForEndOfToken(Loc: NameInfo.getEndLoc());
13548 Diag(Loc: InsertLoc, DiagID: diag::note_using_decl_class_member_workaround)
13549 << diag::MemClassWorkaround::TypedefDecl
13550 << FixItHint::CreateReplacement(RemoveRange: UsingLoc, Code: "typedef")
13551 << FixItHint::CreateInsertion(
13552 InsertionLoc: InsertLoc, Code: " " + NameInfo.getName().getAsString());
13553 }
13554 } else if (R->getAsSingle<VarDecl>()) {
13555 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13556 // repeating the type of the static data member here.
13557 FixItHint FixIt;
13558 if (getLangOpts().CPlusPlus11) {
13559 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13560 FixIt = FixItHint::CreateReplacement(
13561 RemoveRange: UsingLoc, Code: "auto &" + NameInfo.getName().getAsString() + " = ");
13562 }
13563
13564 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13565 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13566 } else if (R->getAsSingle<EnumConstantDecl>()) {
13567 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13568 // repeating the type of the enumeration here, and we can't do so if
13569 // the type is anonymous.
13570 FixItHint FixIt;
13571 if (getLangOpts().CPlusPlus11) {
13572 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13573 FixIt = FixItHint::CreateReplacement(
13574 RemoveRange: UsingLoc,
13575 Code: "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13576 }
13577
13578 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13579 << (getLangOpts().CPlusPlus11
13580 ? diag::MemClassWorkaround::ConstexprVar
13581 : diag::MemClassWorkaround::ConstVar)
13582 << FixIt;
13583 }
13584 }
13585
13586 return true; // Fail
13587 }
13588
13589 // If the named context is dependent, we can't decide much.
13590 if (!NamedContext) {
13591 // FIXME: in C++0x, we can diagnose if we can prove that the
13592 // nested-name-specifier does not refer to a base class, which is
13593 // still possible in some cases.
13594
13595 // Otherwise we have to conservatively report that things might be
13596 // okay.
13597 return false;
13598 }
13599
13600 // The current scope is a record.
13601 if (!NamedContext->isRecord()) {
13602 // Ideally this would point at the last name in the specifier,
13603 // but we don't have that level of source info.
13604 Diag(Loc: SS.getBeginLoc(),
13605 DiagID: Cxx20Enumerator
13606 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13607 : diag::err_using_decl_nested_name_specifier_is_not_class)
13608 << SS.getScopeRep() << SS.getRange();
13609
13610 if (Cxx20Enumerator)
13611 return false; // OK
13612
13613 return true;
13614 }
13615
13616 if (!NamedContext->isDependentContext() &&
13617 RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec&>(SS), DC: NamedContext))
13618 return true;
13619
13620 // C++26 [namespace.udecl]p3:
13621 // In a using-declaration used as a member-declaration, each
13622 // using-declarator shall either name an enumerator or have a
13623 // nested-name-specifier naming a base class of the current class
13624 // ([expr.prim.this]). ...
13625 // "have a nested-name-specifier naming a base class of the current class"
13626 // was introduced by CWG400.
13627
13628 if (cast<CXXRecordDecl>(Val: CurContext)
13629 ->isProvablyNotDerivedFrom(Base: cast<CXXRecordDecl>(Val: NamedContext))) {
13630
13631 if (Cxx20Enumerator) {
13632 Diag(Loc: NameLoc, DiagID: diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13633 << SS.getRange();
13634 return false;
13635 }
13636
13637 if (CurContext == NamedContext) {
13638 Diag(Loc: SS.getBeginLoc(),
13639 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
13640 << SS.getRange();
13641 return !getLangOpts().CPlusPlus20;
13642 }
13643
13644 if (!cast<CXXRecordDecl>(Val: NamedContext)->isInvalidDecl()) {
13645 Diag(Loc: SS.getBeginLoc(),
13646 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
13647 << SS.getScopeRep() << cast<CXXRecordDecl>(Val: CurContext)
13648 << SS.getRange();
13649 }
13650 return true;
13651 }
13652
13653 return false;
13654}
13655
13656Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13657 MultiTemplateParamsArg TemplateParamLists,
13658 SourceLocation UsingLoc, UnqualifiedId &Name,
13659 const ParsedAttributesView &AttrList,
13660 TypeResult Type, Decl *DeclFromDeclSpec) {
13661
13662 if (Type.isInvalid())
13663 return nullptr;
13664
13665 bool Invalid = false;
13666 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13667 TypeSourceInfo *TInfo = nullptr;
13668 GetTypeFromParser(Ty: Type.get(), TInfo: &TInfo);
13669
13670 if (DiagnoseClassNameShadow(DC: CurContext, Info: NameInfo))
13671 return nullptr;
13672
13673 if (DiagnoseUnexpandedParameterPack(Loc: Name.StartLocation, T: TInfo,
13674 UPPC: UPPC_DeclarationType)) {
13675 Invalid = true;
13676 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
13677 Loc: TInfo->getTypeLoc().getBeginLoc());
13678 }
13679
13680 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13681 TemplateParamLists.size()
13682 ? forRedeclarationInCurContext()
13683 : RedeclarationKind::ForVisibleRedeclaration);
13684 LookupName(R&: Previous, S);
13685
13686 // Warn about shadowing the name of a template parameter.
13687 if (Previous.isSingleResult() &&
13688 Previous.getFoundDecl()->isTemplateParameter()) {
13689 DiagnoseTemplateParameterShadow(Loc: Name.StartLocation,PrevDecl: Previous.getFoundDecl());
13690 Previous.clear();
13691 }
13692
13693 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13694 "name in alias declaration must be an identifier");
13695 TypeAliasDecl *NewTD = TypeAliasDecl::Create(C&: Context, DC: CurContext, StartLoc: UsingLoc,
13696 IdLoc: Name.StartLocation,
13697 Id: Name.Identifier, TInfo);
13698
13699 NewTD->setAccess(AS);
13700
13701 if (Invalid)
13702 NewTD->setInvalidDecl();
13703
13704 ProcessDeclAttributeList(S, D: NewTD, AttrList);
13705 AddPragmaAttributes(S, D: NewTD);
13706 ProcessAPINotes(D: NewTD);
13707
13708 CheckTypedefForVariablyModifiedType(S, D: NewTD);
13709 Invalid |= NewTD->isInvalidDecl();
13710
13711 // Get the innermost enclosing declaration scope.
13712 S = S->getDeclParent();
13713
13714 bool Redeclaration = false;
13715
13716 NamedDecl *NewND;
13717 if (TemplateParamLists.size()) {
13718 TypeAliasTemplateDecl *OldDecl = nullptr;
13719 TemplateParameterList *OldTemplateParams = nullptr;
13720
13721 if (TemplateParamLists.size() != 1) {
13722 Diag(Loc: UsingLoc, DiagID: diag::err_alias_template_extra_headers)
13723 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13724 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13725 Invalid = true;
13726 }
13727 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13728
13729 // Check that we can declare a template here.
13730 if (CheckTemplateDeclScope(S, TemplateParams))
13731 return nullptr;
13732
13733 // Only consider previous declarations in the same scope.
13734 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13735 /*ExplicitInstantiationOrSpecialization*/AllowInlineNamespace: false);
13736 if (!Previous.empty()) {
13737 Redeclaration = true;
13738
13739 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13740 if (!OldDecl && !Invalid) {
13741 Diag(Loc: UsingLoc, DiagID: diag::err_redefinition_different_kind)
13742 << Name.Identifier;
13743
13744 NamedDecl *OldD = Previous.getRepresentativeDecl();
13745 if (OldD->getLocation().isValid())
13746 Diag(Loc: OldD->getLocation(), DiagID: diag::note_previous_definition);
13747
13748 Invalid = true;
13749 }
13750
13751 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13752 if (TemplateParameterListsAreEqual(New: TemplateParams,
13753 Old: OldDecl->getTemplateParameters(),
13754 /*Complain=*/true,
13755 Kind: TPL_TemplateMatch))
13756 OldTemplateParams =
13757 OldDecl->getMostRecentDecl()->getTemplateParameters();
13758 else
13759 Invalid = true;
13760
13761 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13762 if (!Invalid &&
13763 !Context.hasSameType(T1: OldTD->getUnderlyingType(),
13764 T2: NewTD->getUnderlyingType())) {
13765 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13766 // but we can't reasonably accept it.
13767 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_redefinition_different_typedef)
13768 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13769 if (OldTD->getLocation().isValid())
13770 Diag(Loc: OldTD->getLocation(), DiagID: diag::note_previous_definition);
13771 Invalid = true;
13772 }
13773 }
13774 }
13775
13776 // Merge any previous default template arguments into our parameters,
13777 // and check the parameter list.
13778 if (CheckTemplateParameterList(NewParams: TemplateParams, OldParams: OldTemplateParams,
13779 TPC: TPC_Other))
13780 return nullptr;
13781
13782 TypeAliasTemplateDecl *NewDecl =
13783 TypeAliasTemplateDecl::Create(C&: Context, DC: CurContext, L: UsingLoc,
13784 Name: Name.Identifier, Params: TemplateParams,
13785 Decl: NewTD);
13786 NewTD->setDescribedAliasTemplate(NewDecl);
13787
13788 NewDecl->setAccess(AS);
13789
13790 if (Invalid)
13791 NewDecl->setInvalidDecl();
13792 else if (OldDecl) {
13793 NewDecl->setPreviousDecl(OldDecl);
13794 CheckRedeclarationInModule(New: NewDecl, Old: OldDecl);
13795 }
13796
13797 NewND = NewDecl;
13798 } else {
13799 if (auto *TD = dyn_cast_or_null<TagDecl>(Val: DeclFromDeclSpec)) {
13800 setTagNameForLinkagePurposes(TagFromDeclSpec: TD, NewTD);
13801 handleTagNumbering(Tag: TD, TagScope: S);
13802 }
13803 ActOnTypedefNameDecl(S, DC: CurContext, D: NewTD, Previous, Redeclaration);
13804 NewND = NewTD;
13805 }
13806
13807 PushOnScopeChains(D: NewND, S);
13808 ActOnDocumentableDecl(D: NewND);
13809 return NewND;
13810}
13811
13812Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13813 SourceLocation AliasLoc,
13814 IdentifierInfo *Alias, CXXScopeSpec &SS,
13815 SourceLocation IdentLoc,
13816 IdentifierInfo *Ident) {
13817
13818 // Lookup the namespace name.
13819 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13820 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
13821
13822 if (R.isAmbiguous())
13823 return nullptr;
13824
13825 if (R.empty()) {
13826 if (!TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident)) {
13827 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
13828 return nullptr;
13829 }
13830 }
13831 assert(!R.isAmbiguous() && !R.empty());
13832 NamedDecl *ND = R.getRepresentativeDecl();
13833
13834 // Check if we have a previous declaration with the same name.
13835 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13836 RedeclarationKind::ForVisibleRedeclaration);
13837 LookupName(R&: PrevR, S);
13838
13839 // Check we're not shadowing a template parameter.
13840 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13841 DiagnoseTemplateParameterShadow(Loc: AliasLoc, PrevDecl: PrevR.getFoundDecl());
13842 PrevR.clear();
13843 }
13844
13845 // Filter out any other lookup result from an enclosing scope.
13846 FilterLookupForScope(R&: PrevR, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13847 /*AllowInlineNamespace*/false);
13848
13849 // Find the previous declaration and check that we can redeclare it.
13850 NamespaceAliasDecl *Prev = nullptr;
13851 if (PrevR.isSingleResult()) {
13852 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13853 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Val: PrevDecl)) {
13854 // We already have an alias with the same name that points to the same
13855 // namespace; check that it matches.
13856 if (AD->getNamespace()->Equals(DC: getNamespaceDecl(D: ND))) {
13857 Prev = AD;
13858 } else if (isVisible(D: PrevDecl)) {
13859 Diag(Loc: AliasLoc, DiagID: diag::err_redefinition_different_namespace_alias)
13860 << Alias;
13861 Diag(Loc: AD->getLocation(), DiagID: diag::note_previous_namespace_alias)
13862 << AD->getNamespace();
13863 return nullptr;
13864 }
13865 } else if (isVisible(D: PrevDecl)) {
13866 unsigned DiagID = isa<NamespaceDecl>(Val: PrevDecl->getUnderlyingDecl())
13867 ? diag::err_redefinition
13868 : diag::err_redefinition_different_kind;
13869 Diag(Loc: AliasLoc, DiagID) << Alias;
13870 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
13871 return nullptr;
13872 }
13873 }
13874
13875 // The use of a nested name specifier may trigger deprecation warnings.
13876 DiagnoseUseOfDecl(D: ND, Locs: IdentLoc);
13877
13878 NamespaceAliasDecl *AliasDecl =
13879 NamespaceAliasDecl::Create(C&: Context, DC: CurContext, NamespaceLoc, AliasLoc,
13880 Alias, QualifierLoc: SS.getWithLocInContext(Context),
13881 IdentLoc, Namespace: ND);
13882 if (Prev)
13883 AliasDecl->setPreviousDecl(Prev);
13884
13885 PushOnScopeChains(D: AliasDecl, S);
13886 return AliasDecl;
13887}
13888
13889namespace {
13890struct SpecialMemberExceptionSpecInfo
13891 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13892 SourceLocation Loc;
13893 Sema::ImplicitExceptionSpecification ExceptSpec;
13894
13895 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13896 CXXSpecialMemberKind CSM,
13897 Sema::InheritedConstructorInfo *ICI,
13898 SourceLocation Loc)
13899 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13900
13901 bool visitBase(CXXBaseSpecifier *Base);
13902 bool visitField(FieldDecl *FD);
13903
13904 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13905 unsigned Quals);
13906
13907 void visitSubobjectCall(Subobject Subobj,
13908 Sema::SpecialMemberOverloadResult SMOR);
13909};
13910}
13911
13912bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13913 auto *RT = Base->getType()->getAs<RecordType>();
13914 if (!RT)
13915 return false;
13916
13917 auto *BaseClass = cast<CXXRecordDecl>(Val: RT->getDecl());
13918 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
13919 if (auto *BaseCtor = SMOR.getMethod()) {
13920 visitSubobjectCall(Subobj: Base, SMOR: BaseCtor);
13921 return false;
13922 }
13923
13924 visitClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
13925 return false;
13926}
13927
13928bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13929 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
13930 FD->hasInClassInitializer()) {
13931 Expr *E = FD->getInClassInitializer();
13932 if (!E)
13933 // FIXME: It's a little wasteful to build and throw away a
13934 // CXXDefaultInitExpr here.
13935 // FIXME: We should have a single context note pointing at Loc, and
13936 // this location should be MD->getLocation() instead, since that's
13937 // the location where we actually use the default init expression.
13938 E = S.BuildCXXDefaultInitExpr(Loc, Field: FD).get();
13939 if (E)
13940 ExceptSpec.CalledExpr(E);
13941 } else if (auto *RT = S.Context.getBaseElementType(QT: FD->getType())
13942 ->getAs<RecordType>()) {
13943 visitClassSubobject(Class: cast<CXXRecordDecl>(Val: RT->getDecl()), Subobj: FD,
13944 Quals: FD->getType().getCVRQualifiers());
13945 }
13946 return false;
13947}
13948
13949void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13950 Subobject Subobj,
13951 unsigned Quals) {
13952 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13953 bool IsMutable = Field && Field->isMutable();
13954 visitSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable));
13955}
13956
13957void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13958 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13959 // Note, if lookup fails, it doesn't matter what exception specification we
13960 // choose because the special member will be deleted.
13961 if (CXXMethodDecl *MD = SMOR.getMethod())
13962 ExceptSpec.CalledDecl(CallLoc: getSubobjectLoc(Subobj), Method: MD);
13963}
13964
13965bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13966 llvm::APSInt Result;
13967 ExprResult Converted = CheckConvertedConstantExpression(
13968 From: ExplicitSpec.getExpr(), T: Context.BoolTy, Value&: Result, CCE: CCEKind::ExplicitBool);
13969 ExplicitSpec.setExpr(Converted.get());
13970 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13971 ExplicitSpec.setKind(Result.getBoolValue()
13972 ? ExplicitSpecKind::ResolvedTrue
13973 : ExplicitSpecKind::ResolvedFalse);
13974 return true;
13975 }
13976 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13977 return false;
13978}
13979
13980ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13981 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13982 if (!ExplicitExpr->isTypeDependent())
13983 tryResolveExplicitSpecifier(ExplicitSpec&: ES);
13984 return ES;
13985}
13986
13987static Sema::ImplicitExceptionSpecification
13988ComputeDefaultedSpecialMemberExceptionSpec(
13989 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
13990 Sema::InheritedConstructorInfo *ICI) {
13991 ComputingExceptionSpec CES(S, MD, Loc);
13992
13993 CXXRecordDecl *ClassDecl = MD->getParent();
13994
13995 // C++ [except.spec]p14:
13996 // An implicitly declared special member function (Clause 12) shall have an
13997 // exception-specification. [...]
13998 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13999 if (ClassDecl->isInvalidDecl())
14000 return Info.ExceptSpec;
14001
14002 // FIXME: If this diagnostic fires, we're probably missing a check for
14003 // attempting to resolve an exception specification before it's known
14004 // at a higher level.
14005 if (S.RequireCompleteType(Loc: MD->getLocation(),
14006 T: S.Context.getRecordType(Decl: ClassDecl),
14007 DiagID: diag::err_exception_spec_incomplete_type))
14008 return Info.ExceptSpec;
14009
14010 // C++1z [except.spec]p7:
14011 // [Look for exceptions thrown by] a constructor selected [...] to
14012 // initialize a potentially constructed subobject,
14013 // C++1z [except.spec]p8:
14014 // The exception specification for an implicitly-declared destructor, or a
14015 // destructor without a noexcept-specifier, is potentially-throwing if and
14016 // only if any of the destructors for any of its potentially constructed
14017 // subojects is potentially throwing.
14018 // FIXME: We respect the first rule but ignore the "potentially constructed"
14019 // in the second rule to resolve a core issue (no number yet) that would have
14020 // us reject:
14021 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14022 // struct B : A {};
14023 // struct C : B { void f(); };
14024 // ... due to giving B::~B() a non-throwing exception specification.
14025 Info.visit(Bases: Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14026 : Info.VisitAllBases);
14027
14028 return Info.ExceptSpec;
14029}
14030
14031namespace {
14032/// RAII object to register a special member as being currently declared.
14033struct DeclaringSpecialMember {
14034 Sema &S;
14035 Sema::SpecialMemberDecl D;
14036 Sema::ContextRAII SavedContext;
14037 bool WasAlreadyBeingDeclared;
14038
14039 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14040 : S(S), D(RD, CSM), SavedContext(S, RD) {
14041 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(Ptr: D).second;
14042 if (WasAlreadyBeingDeclared)
14043 // This almost never happens, but if it does, ensure that our cache
14044 // doesn't contain a stale result.
14045 S.SpecialMemberCache.clear();
14046 else {
14047 // Register a note to be produced if we encounter an error while
14048 // declaring the special member.
14049 Sema::CodeSynthesisContext Ctx;
14050 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14051 // FIXME: We don't have a location to use here. Using the class's
14052 // location maintains the fiction that we declare all special members
14053 // with the class, but (1) it's not clear that lying about that helps our
14054 // users understand what's going on, and (2) there may be outer contexts
14055 // on the stack (some of which are relevant) and printing them exposes
14056 // our lies.
14057 Ctx.PointOfInstantiation = RD->getLocation();
14058 Ctx.Entity = RD;
14059 Ctx.SpecialMember = CSM;
14060 S.pushCodeSynthesisContext(Ctx);
14061 }
14062 }
14063 ~DeclaringSpecialMember() {
14064 if (!WasAlreadyBeingDeclared) {
14065 S.SpecialMembersBeingDeclared.erase(Ptr: D);
14066 S.popCodeSynthesisContext();
14067 }
14068 }
14069
14070 /// Are we already trying to declare this special member?
14071 bool isAlreadyBeingDeclared() const {
14072 return WasAlreadyBeingDeclared;
14073 }
14074};
14075}
14076
14077void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
14078 // Look up any existing declarations, but don't trigger declaration of all
14079 // implicit special members with this name.
14080 DeclarationName Name = FD->getDeclName();
14081 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
14082 RedeclarationKind::ForExternalRedeclaration);
14083 for (auto *D : FD->getParent()->lookup(Name))
14084 if (auto *Acceptable = R.getAcceptableDecl(D))
14085 R.addDecl(D: Acceptable);
14086 R.resolveKind();
14087 R.suppressDiagnostics();
14088
14089 CheckFunctionDeclaration(S, NewFD: FD, Previous&: R, /*IsMemberSpecialization*/ false,
14090 DeclIsDefn: FD->isThisDeclarationADefinition());
14091}
14092
14093void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14094 QualType ResultTy,
14095 ArrayRef<QualType> Args) {
14096 // Build an exception specification pointing back at this constructor.
14097 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(S&: *this, MD: SpecialMem);
14098
14099 LangAS AS = getDefaultCXXMethodAddrSpace();
14100 if (AS != LangAS::Default) {
14101 EPI.TypeQuals.addAddressSpace(space: AS);
14102 }
14103
14104 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14105 SpecialMem->setType(QT);
14106
14107 // During template instantiation of implicit special member functions we need
14108 // a reliable TypeSourceInfo for the function prototype in order to allow
14109 // functions to be substituted.
14110 if (inTemplateInstantiation() && isLambdaMethod(DC: SpecialMem)) {
14111 TypeSourceInfo *TSI =
14112 Context.getTrivialTypeSourceInfo(T: SpecialMem->getType());
14113 SpecialMem->setTypeSourceInfo(TSI);
14114 }
14115}
14116
14117CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
14118 CXXRecordDecl *ClassDecl) {
14119 // C++ [class.ctor]p5:
14120 // A default constructor for a class X is a constructor of class X
14121 // that can be called without an argument. If there is no
14122 // user-declared constructor for class X, a default constructor is
14123 // implicitly declared. An implicitly-declared default constructor
14124 // is an inline public member of its class.
14125 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14126 "Should not build implicit default constructor!");
14127
14128 DeclaringSpecialMember DSM(*this, ClassDecl,
14129 CXXSpecialMemberKind::DefaultConstructor);
14130 if (DSM.isAlreadyBeingDeclared())
14131 return nullptr;
14132
14133 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14134 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, ConstArg: false);
14135
14136 // Create the actual constructor declaration.
14137 CanQualType ClassType
14138 = Context.getCanonicalType(T: Context.getTypeDeclType(Decl: ClassDecl));
14139 SourceLocation ClassLoc = ClassDecl->getLocation();
14140 DeclarationName Name
14141 = Context.DeclarationNames.getCXXConstructorName(Ty: ClassType);
14142 DeclarationNameInfo NameInfo(Name, ClassLoc);
14143 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
14144 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, /*Type*/ T: QualType(),
14145 /*TInfo=*/nullptr, ES: ExplicitSpecifier(),
14146 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14147 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14148 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14149 : ConstexprSpecKind::Unspecified);
14150 DefaultCon->setAccess(AS_public);
14151 DefaultCon->setDefaulted();
14152
14153 setupImplicitSpecialMemberType(SpecialMem: DefaultCon, ResultTy: Context.VoidTy, Args: {});
14154
14155 if (getLangOpts().CUDA)
14156 CUDA().inferTargetForImplicitSpecialMember(
14157 ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, MemberDecl: DefaultCon,
14158 /* ConstRHS */ false,
14159 /* Diagnose */ false);
14160
14161 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14162 // constructors is easy to compute.
14163 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14164
14165 // Note that we have declared this constructor.
14166 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14167
14168 Scope *S = getScopeForContext(Ctx: ClassDecl);
14169 CheckImplicitSpecialMemberDeclaration(S, FD: DefaultCon);
14170
14171 if (ShouldDeleteSpecialMember(MD: DefaultCon,
14172 CSM: CXXSpecialMemberKind::DefaultConstructor))
14173 SetDeclDeleted(dcl: DefaultCon, DelLoc: ClassLoc);
14174
14175 if (S)
14176 PushOnScopeChains(D: DefaultCon, S, AddToContext: false);
14177 ClassDecl->addDecl(D: DefaultCon);
14178
14179 return DefaultCon;
14180}
14181
14182void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14183 CXXConstructorDecl *Constructor) {
14184 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14185 !Constructor->doesThisDeclarationHaveABody() &&
14186 !Constructor->isDeleted()) &&
14187 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14188 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14189 return;
14190
14191 CXXRecordDecl *ClassDecl = Constructor->getParent();
14192 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14193 if (ClassDecl->isInvalidDecl()) {
14194 return;
14195 }
14196
14197 SynthesizedFunctionScope Scope(*this, Constructor);
14198
14199 // The exception specification is needed because we are defining the
14200 // function.
14201 ResolveExceptionSpec(Loc: CurrentLocation,
14202 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14203 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14204
14205 // Add a context note for diagnostics produced after this point.
14206 Scope.addContextNote(UseLoc: CurrentLocation);
14207
14208 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14209 Constructor->setInvalidDecl();
14210 return;
14211 }
14212
14213 SourceLocation Loc = Constructor->getEndLoc().isValid()
14214 ? Constructor->getEndLoc()
14215 : Constructor->getLocation();
14216 Constructor->setBody(new (Context) CompoundStmt(Loc));
14217 Constructor->markUsed(C&: Context);
14218
14219 if (ASTMutationListener *L = getASTMutationListener()) {
14220 L->CompletedImplicitDefinition(D: Constructor);
14221 }
14222
14223 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14224}
14225
14226void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14227 // Perform any delayed checks on exception specifications.
14228 CheckDelayedMemberExceptionSpecs();
14229}
14230
14231/// Find or create the fake constructor we synthesize to model constructing an
14232/// object of a derived class via a constructor of a base class.
14233CXXConstructorDecl *
14234Sema::findInheritingConstructor(SourceLocation Loc,
14235 CXXConstructorDecl *BaseCtor,
14236 ConstructorUsingShadowDecl *Shadow) {
14237 CXXRecordDecl *Derived = Shadow->getParent();
14238 SourceLocation UsingLoc = Shadow->getLocation();
14239
14240 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14241 // For now we use the name of the base class constructor as a member of the
14242 // derived class to indicate a (fake) inherited constructor name.
14243 DeclarationName Name = BaseCtor->getDeclName();
14244
14245 // Check to see if we already have a fake constructor for this inherited
14246 // constructor call.
14247 for (NamedDecl *Ctor : Derived->lookup(Name))
14248 if (declaresSameEntity(D1: cast<CXXConstructorDecl>(Val: Ctor)
14249 ->getInheritedConstructor()
14250 .getConstructor(),
14251 D2: BaseCtor))
14252 return cast<CXXConstructorDecl>(Val: Ctor);
14253
14254 DeclarationNameInfo NameInfo(Name, UsingLoc);
14255 TypeSourceInfo *TInfo =
14256 Context.getTrivialTypeSourceInfo(T: BaseCtor->getType(), Loc: UsingLoc);
14257 FunctionProtoTypeLoc ProtoLoc =
14258 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14259
14260 // Check the inherited constructor is valid and find the list of base classes
14261 // from which it was inherited.
14262 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14263
14264 bool Constexpr = BaseCtor->isConstexpr() &&
14265 defaultedSpecialMemberIsConstexpr(
14266 S&: *this, ClassDecl: Derived, CSM: CXXSpecialMemberKind::DefaultConstructor,
14267 ConstArg: false, InheritedCtor: BaseCtor, Inherited: &ICI);
14268
14269 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14270 C&: Context, RD: Derived, StartLoc: UsingLoc, NameInfo, T: TInfo->getType(), TInfo,
14271 ES: BaseCtor->getExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14272 /*isInline=*/true,
14273 /*isImplicitlyDeclared=*/true,
14274 ConstexprKind: Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14275 Inherited: InheritedConstructor(Shadow, BaseCtor),
14276 TrailingRequiresClause: BaseCtor->getTrailingRequiresClause());
14277 if (Shadow->isInvalidDecl())
14278 DerivedCtor->setInvalidDecl();
14279
14280 // Build an unevaluated exception specification for this fake constructor.
14281 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14282 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14283 EPI.ExceptionSpec.Type = EST_Unevaluated;
14284 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14285 DerivedCtor->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
14286 Args: FPT->getParamTypes(), EPI));
14287
14288 // Build the parameter declarations.
14289 SmallVector<ParmVarDecl *, 16> ParamDecls;
14290 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14291 TypeSourceInfo *TInfo =
14292 Context.getTrivialTypeSourceInfo(T: FPT->getParamType(i: I), Loc: UsingLoc);
14293 ParmVarDecl *PD = ParmVarDecl::Create(
14294 C&: Context, DC: DerivedCtor, StartLoc: UsingLoc, IdLoc: UsingLoc, /*IdentifierInfo=*/Id: nullptr,
14295 T: FPT->getParamType(i: I), TInfo, S: SC_None, /*DefArg=*/nullptr);
14296 PD->setScopeInfo(scopeDepth: 0, parameterIndex: I);
14297 PD->setImplicit();
14298 // Ensure attributes are propagated onto parameters (this matters for
14299 // format, pass_object_size, ...).
14300 mergeDeclAttributes(New: PD, Old: BaseCtor->getParamDecl(i: I));
14301 ParamDecls.push_back(Elt: PD);
14302 ProtoLoc.setParam(i: I, VD: PD);
14303 }
14304
14305 // Set up the new constructor.
14306 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14307 DerivedCtor->setAccess(BaseCtor->getAccess());
14308 DerivedCtor->setParams(ParamDecls);
14309 Derived->addDecl(D: DerivedCtor);
14310
14311 if (ShouldDeleteSpecialMember(MD: DerivedCtor,
14312 CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI))
14313 SetDeclDeleted(dcl: DerivedCtor, DelLoc: UsingLoc);
14314
14315 return DerivedCtor;
14316}
14317
14318void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14319 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14320 Ctor->getInheritedConstructor().getShadowDecl());
14321 ShouldDeleteSpecialMember(MD: Ctor, CSM: CXXSpecialMemberKind::DefaultConstructor,
14322 ICI: &ICI,
14323 /*Diagnose*/ true);
14324}
14325
14326void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14327 CXXConstructorDecl *Constructor) {
14328 CXXRecordDecl *ClassDecl = Constructor->getParent();
14329 assert(Constructor->getInheritedConstructor() &&
14330 !Constructor->doesThisDeclarationHaveABody() &&
14331 !Constructor->isDeleted());
14332 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14333 return;
14334
14335 // Initializations are performed "as if by a defaulted default constructor",
14336 // so enter the appropriate scope.
14337 SynthesizedFunctionScope Scope(*this, Constructor);
14338
14339 // The exception specification is needed because we are defining the
14340 // function.
14341 ResolveExceptionSpec(Loc: CurrentLocation,
14342 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14343 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14344
14345 // Add a context note for diagnostics produced after this point.
14346 Scope.addContextNote(UseLoc: CurrentLocation);
14347
14348 ConstructorUsingShadowDecl *Shadow =
14349 Constructor->getInheritedConstructor().getShadowDecl();
14350 CXXConstructorDecl *InheritedCtor =
14351 Constructor->getInheritedConstructor().getConstructor();
14352
14353 // [class.inhctor.init]p1:
14354 // initialization proceeds as if a defaulted default constructor is used to
14355 // initialize the D object and each base class subobject from which the
14356 // constructor was inherited
14357
14358 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14359 CXXRecordDecl *RD = Shadow->getParent();
14360 SourceLocation InitLoc = Shadow->getLocation();
14361
14362 // Build explicit initializers for all base classes from which the
14363 // constructor was inherited.
14364 SmallVector<CXXCtorInitializer*, 8> Inits;
14365 for (bool VBase : {false, true}) {
14366 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14367 if (B.isVirtual() != VBase)
14368 continue;
14369
14370 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14371 if (!BaseRD)
14372 continue;
14373
14374 auto BaseCtor = ICI.findConstructorForBase(Base: BaseRD, Ctor: InheritedCtor);
14375 if (!BaseCtor.first)
14376 continue;
14377
14378 MarkFunctionReferenced(Loc: CurrentLocation, Func: BaseCtor.first);
14379 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14380 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14381
14382 auto *TInfo = Context.getTrivialTypeSourceInfo(T: B.getType(), Loc: InitLoc);
14383 Inits.push_back(Elt: new (Context) CXXCtorInitializer(
14384 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14385 SourceLocation()));
14386 }
14387 }
14388
14389 // We now proceed as if for a defaulted default constructor, with the relevant
14390 // initializers replaced.
14391
14392 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Initializers: Inits)) {
14393 Constructor->setInvalidDecl();
14394 return;
14395 }
14396
14397 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14398 Constructor->markUsed(C&: Context);
14399
14400 if (ASTMutationListener *L = getASTMutationListener()) {
14401 L->CompletedImplicitDefinition(D: Constructor);
14402 }
14403
14404 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14405}
14406
14407CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14408 // C++ [class.dtor]p2:
14409 // If a class has no user-declared destructor, a destructor is
14410 // declared implicitly. An implicitly-declared destructor is an
14411 // inline public member of its class.
14412 assert(ClassDecl->needsImplicitDestructor());
14413
14414 DeclaringSpecialMember DSM(*this, ClassDecl,
14415 CXXSpecialMemberKind::Destructor);
14416 if (DSM.isAlreadyBeingDeclared())
14417 return nullptr;
14418
14419 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14420 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::Destructor, ConstArg: false);
14421
14422 // Create the actual destructor declaration.
14423 CanQualType ClassType
14424 = Context.getCanonicalType(T: Context.getTypeDeclType(Decl: ClassDecl));
14425 SourceLocation ClassLoc = ClassDecl->getLocation();
14426 DeclarationName Name
14427 = Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
14428 DeclarationNameInfo NameInfo(Name, ClassLoc);
14429 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14430 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), TInfo: nullptr,
14431 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14432 /*isInline=*/true,
14433 /*isImplicitlyDeclared=*/true,
14434 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14435 : ConstexprSpecKind::Unspecified);
14436 Destructor->setAccess(AS_public);
14437 Destructor->setDefaulted();
14438
14439 setupImplicitSpecialMemberType(SpecialMem: Destructor, ResultTy: Context.VoidTy, Args: {});
14440
14441 if (getLangOpts().CUDA)
14442 CUDA().inferTargetForImplicitSpecialMember(
14443 ClassDecl, CSM: CXXSpecialMemberKind::Destructor, MemberDecl: Destructor,
14444 /* ConstRHS */ false,
14445 /* Diagnose */ false);
14446
14447 // We don't need to use SpecialMemberIsTrivial here; triviality for
14448 // destructors is easy to compute.
14449 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14450 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14451 ClassDecl->hasTrivialDestructorForCall());
14452
14453 // Note that we have declared this destructor.
14454 ++getASTContext().NumImplicitDestructorsDeclared;
14455
14456 Scope *S = getScopeForContext(Ctx: ClassDecl);
14457 CheckImplicitSpecialMemberDeclaration(S, FD: Destructor);
14458
14459 // We can't check whether an implicit destructor is deleted before we complete
14460 // the definition of the class, because its validity depends on the alignment
14461 // of the class. We'll check this from ActOnFields once the class is complete.
14462 if (ClassDecl->isCompleteDefinition() &&
14463 ShouldDeleteSpecialMember(MD: Destructor, CSM: CXXSpecialMemberKind::Destructor))
14464 SetDeclDeleted(dcl: Destructor, DelLoc: ClassLoc);
14465
14466 // Introduce this destructor into its scope.
14467 if (S)
14468 PushOnScopeChains(D: Destructor, S, AddToContext: false);
14469 ClassDecl->addDecl(D: Destructor);
14470
14471 return Destructor;
14472}
14473
14474void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14475 CXXDestructorDecl *Destructor) {
14476 assert((Destructor->isDefaulted() &&
14477 !Destructor->doesThisDeclarationHaveABody() &&
14478 !Destructor->isDeleted()) &&
14479 "DefineImplicitDestructor - call it for implicit default dtor");
14480 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14481 return;
14482
14483 CXXRecordDecl *ClassDecl = Destructor->getParent();
14484 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14485
14486 SynthesizedFunctionScope Scope(*this, Destructor);
14487
14488 // The exception specification is needed because we are defining the
14489 // function.
14490 ResolveExceptionSpec(Loc: CurrentLocation,
14491 FPT: Destructor->getType()->castAs<FunctionProtoType>());
14492 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14493
14494 // Add a context note for diagnostics produced after this point.
14495 Scope.addContextNote(UseLoc: CurrentLocation);
14496
14497 MarkBaseAndMemberDestructorsReferenced(Location: Destructor->getLocation(),
14498 ClassDecl: Destructor->getParent());
14499
14500 if (CheckDestructor(Destructor)) {
14501 Destructor->setInvalidDecl();
14502 return;
14503 }
14504
14505 SourceLocation Loc = Destructor->getEndLoc().isValid()
14506 ? Destructor->getEndLoc()
14507 : Destructor->getLocation();
14508 Destructor->setBody(new (Context) CompoundStmt(Loc));
14509 Destructor->markUsed(C&: Context);
14510
14511 if (ASTMutationListener *L = getASTMutationListener()) {
14512 L->CompletedImplicitDefinition(D: Destructor);
14513 }
14514}
14515
14516void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14517 CXXDestructorDecl *Destructor) {
14518 if (Destructor->isInvalidDecl())
14519 return;
14520
14521 CXXRecordDecl *ClassDecl = Destructor->getParent();
14522 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14523 "implicit complete dtors unneeded outside MS ABI");
14524 assert(ClassDecl->getNumVBases() > 0 &&
14525 "complete dtor only exists for classes with vbases");
14526
14527 SynthesizedFunctionScope Scope(*this, Destructor);
14528
14529 // Add a context note for diagnostics produced after this point.
14530 Scope.addContextNote(UseLoc: CurrentLocation);
14531
14532 MarkVirtualBaseDestructorsReferenced(Location: Destructor->getLocation(), ClassDecl);
14533}
14534
14535void Sema::ActOnFinishCXXMemberDecls() {
14536 // If the context is an invalid C++ class, just suppress these checks.
14537 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
14538 if (Record->isInvalidDecl()) {
14539 DelayedOverridingExceptionSpecChecks.clear();
14540 DelayedEquivalentExceptionSpecChecks.clear();
14541 return;
14542 }
14543 checkForMultipleExportedDefaultConstructors(S&: *this, Class: Record);
14544 }
14545}
14546
14547void Sema::ActOnFinishCXXNonNestedClass() {
14548 referenceDLLExportedClassMethods();
14549
14550 if (!DelayedDllExportMemberFunctions.empty()) {
14551 SmallVector<CXXMethodDecl*, 4> WorkList;
14552 std::swap(LHS&: DelayedDllExportMemberFunctions, RHS&: WorkList);
14553 for (CXXMethodDecl *M : WorkList) {
14554 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
14555
14556 // Pass the method to the consumer to get emitted. This is not necessary
14557 // for explicit instantiation definitions, as they will get emitted
14558 // anyway.
14559 if (M->getParent()->getTemplateSpecializationKind() !=
14560 TSK_ExplicitInstantiationDefinition)
14561 ActOnFinishInlineFunctionDef(D: M);
14562 }
14563 }
14564}
14565
14566void Sema::referenceDLLExportedClassMethods() {
14567 if (!DelayedDllExportClasses.empty()) {
14568 // Calling ReferenceDllExportedMembers might cause the current function to
14569 // be called again, so use a local copy of DelayedDllExportClasses.
14570 SmallVector<CXXRecordDecl *, 4> WorkList;
14571 std::swap(LHS&: DelayedDllExportClasses, RHS&: WorkList);
14572 for (CXXRecordDecl *Class : WorkList)
14573 ReferenceDllExportedMembers(S&: *this, Class);
14574 }
14575}
14576
14577void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14578 assert(getLangOpts().CPlusPlus11 &&
14579 "adjusting dtor exception specs was introduced in c++11");
14580
14581 if (Destructor->isDependentContext())
14582 return;
14583
14584 // C++11 [class.dtor]p3:
14585 // A declaration of a destructor that does not have an exception-
14586 // specification is implicitly considered to have the same exception-
14587 // specification as an implicit declaration.
14588 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14589 if (DtorType->hasExceptionSpec())
14590 return;
14591
14592 // Replace the destructor's type, building off the existing one. Fortunately,
14593 // the only thing of interest in the destructor type is its extended info.
14594 // The return and arguments are fixed.
14595 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14596 EPI.ExceptionSpec.Type = EST_Unevaluated;
14597 EPI.ExceptionSpec.SourceDecl = Destructor;
14598 Destructor->setType(Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI));
14599
14600 // FIXME: If the destructor has a body that could throw, and the newly created
14601 // spec doesn't allow exceptions, we should emit a warning, because this
14602 // change in behavior can break conforming C++03 programs at runtime.
14603 // However, we don't have a body or an exception specification yet, so it
14604 // needs to be done somewhere else.
14605}
14606
14607namespace {
14608/// An abstract base class for all helper classes used in building the
14609// copy/move operators. These classes serve as factory functions and help us
14610// avoid using the same Expr* in the AST twice.
14611class ExprBuilder {
14612 ExprBuilder(const ExprBuilder&) = delete;
14613 ExprBuilder &operator=(const ExprBuilder&) = delete;
14614
14615protected:
14616 static Expr *assertNotNull(Expr *E) {
14617 assert(E && "Expression construction must not fail.");
14618 return E;
14619 }
14620
14621public:
14622 ExprBuilder() {}
14623 virtual ~ExprBuilder() {}
14624
14625 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14626};
14627
14628class RefBuilder: public ExprBuilder {
14629 VarDecl *Var;
14630 QualType VarType;
14631
14632public:
14633 Expr *build(Sema &S, SourceLocation Loc) const override {
14634 return assertNotNull(E: S.BuildDeclRefExpr(D: Var, Ty: VarType, VK: VK_LValue, Loc));
14635 }
14636
14637 RefBuilder(VarDecl *Var, QualType VarType)
14638 : Var(Var), VarType(VarType) {}
14639};
14640
14641class ThisBuilder: public ExprBuilder {
14642public:
14643 Expr *build(Sema &S, SourceLocation Loc) const override {
14644 return assertNotNull(E: S.ActOnCXXThis(Loc).getAs<Expr>());
14645 }
14646};
14647
14648class CastBuilder: public ExprBuilder {
14649 const ExprBuilder &Builder;
14650 QualType Type;
14651 ExprValueKind Kind;
14652 const CXXCastPath &Path;
14653
14654public:
14655 Expr *build(Sema &S, SourceLocation Loc) const override {
14656 return assertNotNull(E: S.ImpCastExprToType(E: Builder.build(S, Loc), Type,
14657 CK: CK_UncheckedDerivedToBase, VK: Kind,
14658 BasePath: &Path).get());
14659 }
14660
14661 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14662 const CXXCastPath &Path)
14663 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14664};
14665
14666class DerefBuilder: public ExprBuilder {
14667 const ExprBuilder &Builder;
14668
14669public:
14670 Expr *build(Sema &S, SourceLocation Loc) const override {
14671 return assertNotNull(
14672 E: S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: Builder.build(S, Loc)).get());
14673 }
14674
14675 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14676};
14677
14678class MemberBuilder: public ExprBuilder {
14679 const ExprBuilder &Builder;
14680 QualType Type;
14681 CXXScopeSpec SS;
14682 bool IsArrow;
14683 LookupResult &MemberLookup;
14684
14685public:
14686 Expr *build(Sema &S, SourceLocation Loc) const override {
14687 return assertNotNull(E: S.BuildMemberReferenceExpr(
14688 Base: Builder.build(S, Loc), BaseType: Type, OpLoc: Loc, IsArrow, SS, TemplateKWLoc: SourceLocation(),
14689 FirstQualifierInScope: nullptr, R&: MemberLookup, TemplateArgs: nullptr, S: nullptr).get());
14690 }
14691
14692 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14693 LookupResult &MemberLookup)
14694 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14695 MemberLookup(MemberLookup) {}
14696};
14697
14698class MoveCastBuilder: public ExprBuilder {
14699 const ExprBuilder &Builder;
14700
14701public:
14702 Expr *build(Sema &S, SourceLocation Loc) const override {
14703 return assertNotNull(E: CastForMoving(SemaRef&: S, E: Builder.build(S, Loc)));
14704 }
14705
14706 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14707};
14708
14709class LvalueConvBuilder: public ExprBuilder {
14710 const ExprBuilder &Builder;
14711
14712public:
14713 Expr *build(Sema &S, SourceLocation Loc) const override {
14714 return assertNotNull(
14715 E: S.DefaultLvalueConversion(E: Builder.build(S, Loc)).get());
14716 }
14717
14718 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14719};
14720
14721class SubscriptBuilder: public ExprBuilder {
14722 const ExprBuilder &Base;
14723 const ExprBuilder &Index;
14724
14725public:
14726 Expr *build(Sema &S, SourceLocation Loc) const override {
14727 return assertNotNull(E: S.CreateBuiltinArraySubscriptExpr(
14728 Base: Base.build(S, Loc), LLoc: Loc, Idx: Index.build(S, Loc), RLoc: Loc).get());
14729 }
14730
14731 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14732 : Base(Base), Index(Index) {}
14733};
14734
14735} // end anonymous namespace
14736
14737/// When generating a defaulted copy or move assignment operator, if a field
14738/// should be copied with __builtin_memcpy rather than via explicit assignments,
14739/// do so. This optimization only applies for arrays of scalars, and for arrays
14740/// of class type where the selected copy/move-assignment operator is trivial.
14741static StmtResult
14742buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14743 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14744 // Compute the size of the memory buffer to be copied.
14745 QualType SizeType = S.Context.getSizeType();
14746 llvm::APInt Size(S.Context.getTypeSize(T: SizeType),
14747 S.Context.getTypeSizeInChars(T).getQuantity());
14748
14749 // Take the address of the field references for "from" and "to". We
14750 // directly construct UnaryOperators here because semantic analysis
14751 // does not permit us to take the address of an xvalue.
14752 Expr *From = FromB.build(S, Loc);
14753 From = UnaryOperator::Create(
14754 C: S.Context, input: From, opc: UO_AddrOf, type: S.Context.getPointerType(T: From->getType()),
14755 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14756 Expr *To = ToB.build(S, Loc);
14757 To = UnaryOperator::Create(
14758 C: S.Context, input: To, opc: UO_AddrOf, type: S.Context.getPointerType(T: To->getType()),
14759 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14760
14761 const Type *E = T->getBaseElementTypeUnsafe();
14762 bool NeedsCollectableMemCpy =
14763 E->isRecordType() &&
14764 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14765
14766 // Create a reference to the __builtin_objc_memmove_collectable function
14767 StringRef MemCpyName = NeedsCollectableMemCpy ?
14768 "__builtin_objc_memmove_collectable" :
14769 "__builtin_memcpy";
14770 LookupResult R(S, &S.Context.Idents.get(Name: MemCpyName), Loc,
14771 Sema::LookupOrdinaryName);
14772 S.LookupName(R, S: S.TUScope, AllowBuiltinCreation: true);
14773
14774 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14775 if (!MemCpy)
14776 // Something went horribly wrong earlier, and we will have complained
14777 // about it.
14778 return StmtError();
14779
14780 ExprResult MemCpyRef = S.BuildDeclRefExpr(D: MemCpy, Ty: S.Context.BuiltinFnTy,
14781 VK: VK_PRValue, Loc, SS: nullptr);
14782 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14783
14784 Expr *CallArgs[] = {
14785 To, From, IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc)
14786 };
14787 ExprResult Call = S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: MemCpyRef.get(),
14788 LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
14789
14790 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14791 return Call.getAs<Stmt>();
14792}
14793
14794/// Builds a statement that copies/moves the given entity from \p From to
14795/// \c To.
14796///
14797/// This routine is used to copy/move the members of a class with an
14798/// implicitly-declared copy/move assignment operator. When the entities being
14799/// copied are arrays, this routine builds for loops to copy them.
14800///
14801/// \param S The Sema object used for type-checking.
14802///
14803/// \param Loc The location where the implicit copy/move is being generated.
14804///
14805/// \param T The type of the expressions being copied/moved. Both expressions
14806/// must have this type.
14807///
14808/// \param To The expression we are copying/moving to.
14809///
14810/// \param From The expression we are copying/moving from.
14811///
14812/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14813/// Otherwise, it's a non-static member subobject.
14814///
14815/// \param Copying Whether we're copying or moving.
14816///
14817/// \param Depth Internal parameter recording the depth of the recursion.
14818///
14819/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14820/// if a memcpy should be used instead.
14821static StmtResult
14822buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14823 const ExprBuilder &To, const ExprBuilder &From,
14824 bool CopyingBaseSubobject, bool Copying,
14825 unsigned Depth = 0) {
14826 // C++11 [class.copy]p28:
14827 // Each subobject is assigned in the manner appropriate to its type:
14828 //
14829 // - if the subobject is of class type, as if by a call to operator= with
14830 // the subobject as the object expression and the corresponding
14831 // subobject of x as a single function argument (as if by explicit
14832 // qualification; that is, ignoring any possible virtual overriding
14833 // functions in more derived classes);
14834 //
14835 // C++03 [class.copy]p13:
14836 // - if the subobject is of class type, the copy assignment operator for
14837 // the class is used (as if by explicit qualification; that is,
14838 // ignoring any possible virtual overriding functions in more derived
14839 // classes);
14840 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14841 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: RecordTy->getDecl());
14842
14843 // Look for operator=.
14844 DeclarationName Name
14845 = S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
14846 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14847 S.LookupQualifiedName(R&: OpLookup, LookupCtx: ClassDecl, InUnqualifiedLookup: false);
14848
14849 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14850 // operator.
14851 if (!S.getLangOpts().CPlusPlus11) {
14852 LookupResult::Filter F = OpLookup.makeFilter();
14853 while (F.hasNext()) {
14854 NamedDecl *D = F.next();
14855 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D))
14856 if (Method->isCopyAssignmentOperator() ||
14857 (!Copying && Method->isMoveAssignmentOperator()))
14858 continue;
14859
14860 F.erase();
14861 }
14862 F.done();
14863 }
14864
14865 // Suppress the protected check (C++ [class.protected]) for each of the
14866 // assignment operators we found. This strange dance is required when
14867 // we're assigning via a base classes's copy-assignment operator. To
14868 // ensure that we're getting the right base class subobject (without
14869 // ambiguities), we need to cast "this" to that subobject type; to
14870 // ensure that we don't go through the virtual call mechanism, we need
14871 // to qualify the operator= name with the base class (see below). However,
14872 // this means that if the base class has a protected copy assignment
14873 // operator, the protected member access check will fail. So, we
14874 // rewrite "protected" access to "public" access in this case, since we
14875 // know by construction that we're calling from a derived class.
14876 if (CopyingBaseSubobject) {
14877 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14878 L != LEnd; ++L) {
14879 if (L.getAccess() == AS_protected)
14880 L.setAccess(AS_public);
14881 }
14882 }
14883
14884 // Create the nested-name-specifier that will be used to qualify the
14885 // reference to operator=; this is required to suppress the virtual
14886 // call mechanism.
14887 CXXScopeSpec SS;
14888 const Type *CanonicalT = S.Context.getCanonicalType(T: T.getTypePtr());
14889 SS.MakeTrivial(Context&: S.Context,
14890 Qualifier: NestedNameSpecifier::Create(Context: S.Context, Prefix: nullptr, T: CanonicalT),
14891 R: Loc);
14892
14893 // Create the reference to operator=.
14894 ExprResult OpEqualRef
14895 = S.BuildMemberReferenceExpr(Base: To.build(S, Loc), BaseType: T, OpLoc: Loc, /*IsArrow=*/false,
14896 SS, /*TemplateKWLoc=*/SourceLocation(),
14897 /*FirstQualifierInScope=*/nullptr,
14898 R&: OpLookup,
14899 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14900 /*SuppressQualifierCheck=*/true);
14901 if (OpEqualRef.isInvalid())
14902 return StmtError();
14903
14904 // Build the call to the assignment operator.
14905
14906 Expr *FromInst = From.build(S, Loc);
14907 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/S: nullptr,
14908 MemExpr: OpEqualRef.getAs<Expr>(),
14909 LParenLoc: Loc, Args: FromInst, RParenLoc: Loc);
14910 if (Call.isInvalid())
14911 return StmtError();
14912
14913 // If we built a call to a trivial 'operator=' while copying an array,
14914 // bail out. We'll replace the whole shebang with a memcpy.
14915 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Val: Call.get());
14916 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14917 return StmtResult((Stmt*)nullptr);
14918
14919 // Convert to an expression-statement, and clean up any produced
14920 // temporaries.
14921 return S.ActOnExprStmt(Arg: Call);
14922 }
14923
14924 // - if the subobject is of scalar type, the built-in assignment
14925 // operator is used.
14926 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14927 if (!ArrayTy) {
14928 ExprResult Assignment = S.CreateBuiltinBinOp(
14929 OpLoc: Loc, Opc: BO_Assign, LHSExpr: To.build(S, Loc), RHSExpr: From.build(S, Loc));
14930 if (Assignment.isInvalid())
14931 return StmtError();
14932 return S.ActOnExprStmt(Arg: Assignment);
14933 }
14934
14935 // - if the subobject is an array, each element is assigned, in the
14936 // manner appropriate to the element type;
14937
14938 // Construct a loop over the array bounds, e.g.,
14939 //
14940 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14941 //
14942 // that will copy each of the array elements.
14943 QualType SizeType = S.Context.getSizeType();
14944
14945 // Create the iteration variable.
14946 IdentifierInfo *IterationVarName = nullptr;
14947 {
14948 SmallString<8> Str;
14949 llvm::raw_svector_ostream OS(Str);
14950 OS << "__i" << Depth;
14951 IterationVarName = &S.Context.Idents.get(Name: OS.str());
14952 }
14953 VarDecl *IterationVar = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc,
14954 Id: IterationVarName, T: SizeType,
14955 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc),
14956 S: SC_None);
14957
14958 // Initialize the iteration variable to zero.
14959 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
14960 IterationVar->setInit(IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
14961
14962 // Creates a reference to the iteration variable.
14963 RefBuilder IterationVarRef(IterationVar, SizeType);
14964 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14965
14966 // Create the DeclStmt that holds the iteration variable.
14967 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14968
14969 // Subscript the "from" and "to" expressions with the iteration variable.
14970 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14971 MoveCastBuilder FromIndexMove(FromIndexCopy);
14972 const ExprBuilder *FromIndex;
14973 if (Copying)
14974 FromIndex = &FromIndexCopy;
14975 else
14976 FromIndex = &FromIndexMove;
14977
14978 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14979
14980 // Build the copy/move for an individual element of the array.
14981 StmtResult Copy =
14982 buildSingleCopyAssignRecursively(S, Loc, T: ArrayTy->getElementType(),
14983 To: ToIndex, From: *FromIndex, CopyingBaseSubobject,
14984 Copying, Depth: Depth + 1);
14985 // Bail out if copying fails or if we determined that we should use memcpy.
14986 if (Copy.isInvalid() || !Copy.get())
14987 return Copy;
14988
14989 // Create the comparison against the array bound.
14990 llvm::APInt Upper
14991 = ArrayTy->getSize().zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
14992 Expr *Comparison = BinaryOperator::Create(
14993 C: S.Context, lhs: IterationVarRefRVal.build(S, Loc),
14994 rhs: IntegerLiteral::Create(C: S.Context, V: Upper, type: SizeType, l: Loc), opc: BO_NE,
14995 ResTy: S.Context.BoolTy, VK: VK_PRValue, OK: OK_Ordinary, opLoc: Loc,
14996 FPFeatures: S.CurFPFeatureOverrides());
14997
14998 // Create the pre-increment of the iteration variable. We can determine
14999 // whether the increment will overflow based on the value of the array
15000 // bound.
15001 Expr *Increment = UnaryOperator::Create(
15002 C: S.Context, input: IterationVarRef.build(S, Loc), opc: UO_PreInc, type: SizeType, VK: VK_LValue,
15003 OK: OK_Ordinary, l: Loc, CanOverflow: Upper.isMaxValue(), FPFeatures: S.CurFPFeatureOverrides());
15004
15005 // Construct the loop that copies all elements of this array.
15006 return S.ActOnForStmt(
15007 ForLoc: Loc, LParenLoc: Loc, First: InitStmt,
15008 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Comparison, CK: Sema::ConditionKind::Boolean),
15009 Third: S.MakeFullDiscardedValueExpr(Arg: Increment), RParenLoc: Loc, Body: Copy.get());
15010}
15011
15012static StmtResult
15013buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
15014 const ExprBuilder &To, const ExprBuilder &From,
15015 bool CopyingBaseSubobject, bool Copying) {
15016 // Maybe we should use a memcpy?
15017 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
15018 T.isTriviallyCopyableType(Context: S.Context))
15019 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15020
15021 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15022 CopyingBaseSubobject,
15023 Copying, Depth: 0));
15024
15025 // If we ended up picking a trivial assignment operator for an array of a
15026 // non-trivially-copyable class type, just emit a memcpy.
15027 if (!Result.isInvalid() && !Result.get())
15028 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15029
15030 return Result;
15031}
15032
15033CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
15034 // Note: The following rules are largely analoguous to the copy
15035 // constructor rules. Note that virtual bases are not taken into account
15036 // for determining the argument type of the operator. Note also that
15037 // operators taking an object instead of a reference are allowed.
15038 assert(ClassDecl->needsImplicitCopyAssignment());
15039
15040 DeclaringSpecialMember DSM(*this, ClassDecl,
15041 CXXSpecialMemberKind::CopyAssignment);
15042 if (DSM.isAlreadyBeingDeclared())
15043 return nullptr;
15044
15045 QualType ArgType = Context.getTypeDeclType(Decl: ClassDecl);
15046 ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
15047 NamedType: ArgType, OwnedTagDecl: nullptr);
15048 LangAS AS = getDefaultCXXMethodAddrSpace();
15049 if (AS != LangAS::Default)
15050 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15051 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15052 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15053 if (Const)
15054 ArgType = ArgType.withConst();
15055
15056 ArgType = Context.getLValueReferenceType(T: ArgType);
15057
15058 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15059 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Const);
15060
15061 // An implicitly-declared copy assignment operator is an inline public
15062 // member of its class.
15063 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15064 SourceLocation ClassLoc = ClassDecl->getLocation();
15065 DeclarationNameInfo NameInfo(Name, ClassLoc);
15066 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
15067 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15068 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15069 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15070 /*isInline=*/true,
15071 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15072 EndLocation: SourceLocation());
15073 CopyAssignment->setAccess(AS_public);
15074 CopyAssignment->setDefaulted();
15075 CopyAssignment->setImplicit();
15076
15077 setupImplicitSpecialMemberType(SpecialMem: CopyAssignment, ResultTy: RetType, Args: ArgType);
15078
15079 if (getLangOpts().CUDA)
15080 CUDA().inferTargetForImplicitSpecialMember(
15081 ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, MemberDecl: CopyAssignment,
15082 /* ConstRHS */ Const,
15083 /* Diagnose */ false);
15084
15085 // Add the parameter to the operator.
15086 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: CopyAssignment,
15087 StartLoc: ClassLoc, IdLoc: ClassLoc,
15088 /*Id=*/nullptr, T: ArgType,
15089 /*TInfo=*/nullptr, S: SC_None,
15090 DefArg: nullptr);
15091 CopyAssignment->setParams(FromParam);
15092
15093 CopyAssignment->setTrivial(
15094 ClassDecl->needsOverloadResolutionForCopyAssignment()
15095 ? SpecialMemberIsTrivial(MD: CopyAssignment,
15096 CSM: CXXSpecialMemberKind::CopyAssignment)
15097 : ClassDecl->hasTrivialCopyAssignment());
15098
15099 // Note that we have added this copy-assignment operator.
15100 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15101
15102 Scope *S = getScopeForContext(Ctx: ClassDecl);
15103 CheckImplicitSpecialMemberDeclaration(S, FD: CopyAssignment);
15104
15105 if (ShouldDeleteSpecialMember(MD: CopyAssignment,
15106 CSM: CXXSpecialMemberKind::CopyAssignment)) {
15107 ClassDecl->setImplicitCopyAssignmentIsDeleted();
15108 SetDeclDeleted(dcl: CopyAssignment, DelLoc: ClassLoc);
15109 }
15110
15111 if (S)
15112 PushOnScopeChains(D: CopyAssignment, S, AddToContext: false);
15113 ClassDecl->addDecl(D: CopyAssignment);
15114
15115 return CopyAssignment;
15116}
15117
15118/// Diagnose an implicit copy operation for a class which is odr-used, but
15119/// which is deprecated because the class has a user-declared copy constructor,
15120/// copy assignment operator, or destructor.
15121static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
15122 assert(CopyOp->isImplicit());
15123
15124 CXXRecordDecl *RD = CopyOp->getParent();
15125 CXXMethodDecl *UserDeclaredOperation = nullptr;
15126
15127 if (RD->hasUserDeclaredDestructor()) {
15128 UserDeclaredOperation = RD->getDestructor();
15129 } else if (!isa<CXXConstructorDecl>(Val: CopyOp) &&
15130 RD->hasUserDeclaredCopyConstructor()) {
15131 // Find any user-declared copy constructor.
15132 for (auto *I : RD->ctors()) {
15133 if (I->isCopyConstructor()) {
15134 UserDeclaredOperation = I;
15135 break;
15136 }
15137 }
15138 assert(UserDeclaredOperation);
15139 } else if (isa<CXXConstructorDecl>(Val: CopyOp) &&
15140 RD->hasUserDeclaredCopyAssignment()) {
15141 // Find any user-declared move assignment operator.
15142 for (auto *I : RD->methods()) {
15143 if (I->isCopyAssignmentOperator()) {
15144 UserDeclaredOperation = I;
15145 break;
15146 }
15147 }
15148 assert(UserDeclaredOperation);
15149 }
15150
15151 if (UserDeclaredOperation) {
15152 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15153 bool UDOIsDestructor = isa<CXXDestructorDecl>(Val: UserDeclaredOperation);
15154 bool IsCopyAssignment = !isa<CXXConstructorDecl>(Val: CopyOp);
15155 unsigned DiagID =
15156 (UDOIsUserProvided && UDOIsDestructor)
15157 ? diag::warn_deprecated_copy_with_user_provided_dtor
15158 : (UDOIsUserProvided && !UDOIsDestructor)
15159 ? diag::warn_deprecated_copy_with_user_provided_copy
15160 : (!UDOIsUserProvided && UDOIsDestructor)
15161 ? diag::warn_deprecated_copy_with_dtor
15162 : diag::warn_deprecated_copy;
15163 S.Diag(Loc: UserDeclaredOperation->getLocation(), DiagID)
15164 << RD << IsCopyAssignment;
15165 }
15166}
15167
15168void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15169 CXXMethodDecl *CopyAssignOperator) {
15170 assert((CopyAssignOperator->isDefaulted() &&
15171 CopyAssignOperator->isOverloadedOperator() &&
15172 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15173 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15174 !CopyAssignOperator->isDeleted()) &&
15175 "DefineImplicitCopyAssignment called for wrong function");
15176 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15177 return;
15178
15179 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15180 if (ClassDecl->isInvalidDecl()) {
15181 CopyAssignOperator->setInvalidDecl();
15182 return;
15183 }
15184
15185 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15186
15187 // The exception specification is needed because we are defining the
15188 // function.
15189 ResolveExceptionSpec(Loc: CurrentLocation,
15190 FPT: CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15191
15192 // Add a context note for diagnostics produced after this point.
15193 Scope.addContextNote(UseLoc: CurrentLocation);
15194
15195 // C++11 [class.copy]p18:
15196 // The [definition of an implicitly declared copy assignment operator] is
15197 // deprecated if the class has a user-declared copy constructor or a
15198 // user-declared destructor.
15199 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15200 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyAssignOperator);
15201
15202 // C++0x [class.copy]p30:
15203 // The implicitly-defined or explicitly-defaulted copy assignment operator
15204 // for a non-union class X performs memberwise copy assignment of its
15205 // subobjects. The direct base classes of X are assigned first, in the
15206 // order of their declaration in the base-specifier-list, and then the
15207 // immediate non-static data members of X are assigned, in the order in
15208 // which they were declared in the class definition.
15209
15210 // The statements that form the synthesized function body.
15211 SmallVector<Stmt*, 8> Statements;
15212
15213 // The parameter for the "other" object, which we are copying from.
15214 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(I: 0);
15215 Qualifiers OtherQuals = Other->getType().getQualifiers();
15216 QualType OtherRefType = Other->getType();
15217 if (OtherRefType->isLValueReferenceType()) {
15218 OtherRefType = OtherRefType->getPointeeType();
15219 OtherQuals = OtherRefType.getQualifiers();
15220 }
15221
15222 // Our location for everything implicitly-generated.
15223 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15224 ? CopyAssignOperator->getEndLoc()
15225 : CopyAssignOperator->getLocation();
15226
15227 // Builds a DeclRefExpr for the "other" object.
15228 RefBuilder OtherRef(Other, OtherRefType);
15229
15230 // Builds the function object parameter.
15231 std::optional<ThisBuilder> This;
15232 std::optional<DerefBuilder> DerefThis;
15233 std::optional<RefBuilder> ExplicitObject;
15234 bool IsArrow = false;
15235 QualType ObjectType;
15236 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15237 ObjectType = CopyAssignOperator->getParamDecl(i: 0)->getType();
15238 if (ObjectType->isReferenceType())
15239 ObjectType = ObjectType->getPointeeType();
15240 ExplicitObject.emplace(args: CopyAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15241 } else {
15242 ObjectType = getCurrentThisType();
15243 This.emplace();
15244 DerefThis.emplace(args&: *This);
15245 IsArrow = !LangOpts.HLSL;
15246 }
15247 ExprBuilder &ObjectParameter =
15248 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15249 : static_cast<ExprBuilder &>(*This);
15250
15251 // Assign base classes.
15252 bool Invalid = false;
15253 for (auto &Base : ClassDecl->bases()) {
15254 // Form the assignment:
15255 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15256 QualType BaseType = Base.getType().getUnqualifiedType();
15257 if (!BaseType->isRecordType()) {
15258 Invalid = true;
15259 continue;
15260 }
15261
15262 CXXCastPath BasePath;
15263 BasePath.push_back(Elt: &Base);
15264
15265 // Construct the "from" expression, which is an implicit cast to the
15266 // appropriately-qualified base type.
15267 CastBuilder From(OtherRef, Context.getQualifiedType(T: BaseType, Qs: OtherQuals),
15268 VK_LValue, BasePath);
15269
15270 // Dereference "this".
15271 CastBuilder To(
15272 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15273 : static_cast<ExprBuilder &>(*DerefThis),
15274 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15275 VK_LValue, BasePath);
15276
15277 // Build the copy.
15278 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15279 To, From,
15280 /*CopyingBaseSubobject=*/true,
15281 /*Copying=*/true);
15282 if (Copy.isInvalid()) {
15283 CopyAssignOperator->setInvalidDecl();
15284 return;
15285 }
15286
15287 // Success! Record the copy.
15288 Statements.push_back(Elt: Copy.getAs<Expr>());
15289 }
15290
15291 // Assign non-static members.
15292 for (auto *Field : ClassDecl->fields()) {
15293 // FIXME: We should form some kind of AST representation for the implied
15294 // memcpy in a union copy operation.
15295 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15296 continue;
15297
15298 if (Field->isInvalidDecl()) {
15299 Invalid = true;
15300 continue;
15301 }
15302
15303 // Check for members of reference type; we can't copy those.
15304 if (Field->getType()->isReferenceType()) {
15305 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15306 << Context.getTagDeclType(Decl: ClassDecl) << 0 << Field->getDeclName();
15307 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15308 Invalid = true;
15309 continue;
15310 }
15311
15312 // Check for members of const-qualified, non-class type.
15313 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15314 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15315 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15316 << Context.getTagDeclType(Decl: ClassDecl) << 1 << Field->getDeclName();
15317 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15318 Invalid = true;
15319 continue;
15320 }
15321
15322 // Suppress assigning zero-width bitfields.
15323 if (Field->isZeroLengthBitField())
15324 continue;
15325
15326 QualType FieldType = Field->getType().getNonReferenceType();
15327 if (FieldType->isIncompleteArrayType()) {
15328 assert(ClassDecl->hasFlexibleArrayMember() &&
15329 "Incomplete array type is not valid");
15330 continue;
15331 }
15332
15333 // Build references to the field in the object we're copying from and to.
15334 CXXScopeSpec SS; // Intentionally empty
15335 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15336 LookupMemberName);
15337 MemberLookup.addDecl(D: Field);
15338 MemberLookup.resolveKind();
15339
15340 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15341 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15342 // Build the copy of this field.
15343 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15344 To, From,
15345 /*CopyingBaseSubobject=*/false,
15346 /*Copying=*/true);
15347 if (Copy.isInvalid()) {
15348 CopyAssignOperator->setInvalidDecl();
15349 return;
15350 }
15351
15352 // Success! Record the copy.
15353 Statements.push_back(Elt: Copy.getAs<Stmt>());
15354 }
15355
15356 if (!Invalid) {
15357 // Add a "return *this;"
15358 Expr *ThisExpr =
15359 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15360 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15361 : static_cast<ExprBuilder &>(*DerefThis))
15362 .build(S&: *this, Loc);
15363 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15364 if (Return.isInvalid())
15365 Invalid = true;
15366 else
15367 Statements.push_back(Elt: Return.getAs<Stmt>());
15368 }
15369
15370 if (Invalid) {
15371 CopyAssignOperator->setInvalidDecl();
15372 return;
15373 }
15374
15375 StmtResult Body;
15376 {
15377 CompoundScopeRAII CompoundScope(*this);
15378 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15379 /*isStmtExpr=*/false);
15380 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15381 }
15382 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15383 CopyAssignOperator->markUsed(C&: Context);
15384
15385 if (ASTMutationListener *L = getASTMutationListener()) {
15386 L->CompletedImplicitDefinition(D: CopyAssignOperator);
15387 }
15388}
15389
15390CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15391 assert(ClassDecl->needsImplicitMoveAssignment());
15392
15393 DeclaringSpecialMember DSM(*this, ClassDecl,
15394 CXXSpecialMemberKind::MoveAssignment);
15395 if (DSM.isAlreadyBeingDeclared())
15396 return nullptr;
15397
15398 // Note: The following rules are largely analoguous to the move
15399 // constructor rules.
15400
15401 QualType ArgType = Context.getTypeDeclType(Decl: ClassDecl);
15402 ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
15403 NamedType: ArgType, OwnedTagDecl: nullptr);
15404 LangAS AS = getDefaultCXXMethodAddrSpace();
15405 if (AS != LangAS::Default)
15406 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15407 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15408 ArgType = Context.getRValueReferenceType(T: ArgType);
15409
15410 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15411 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, ConstArg: false);
15412
15413 // An implicitly-declared move assignment operator is an inline public
15414 // member of its class.
15415 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15416 SourceLocation ClassLoc = ClassDecl->getLocation();
15417 DeclarationNameInfo NameInfo(Name, ClassLoc);
15418 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15419 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15420 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15421 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15422 /*isInline=*/true,
15423 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15424 EndLocation: SourceLocation());
15425 MoveAssignment->setAccess(AS_public);
15426 MoveAssignment->setDefaulted();
15427 MoveAssignment->setImplicit();
15428
15429 setupImplicitSpecialMemberType(SpecialMem: MoveAssignment, ResultTy: RetType, Args: ArgType);
15430
15431 if (getLangOpts().CUDA)
15432 CUDA().inferTargetForImplicitSpecialMember(
15433 ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, MemberDecl: MoveAssignment,
15434 /* ConstRHS */ false,
15435 /* Diagnose */ false);
15436
15437 // Add the parameter to the operator.
15438 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveAssignment,
15439 StartLoc: ClassLoc, IdLoc: ClassLoc,
15440 /*Id=*/nullptr, T: ArgType,
15441 /*TInfo=*/nullptr, S: SC_None,
15442 DefArg: nullptr);
15443 MoveAssignment->setParams(FromParam);
15444
15445 MoveAssignment->setTrivial(
15446 ClassDecl->needsOverloadResolutionForMoveAssignment()
15447 ? SpecialMemberIsTrivial(MD: MoveAssignment,
15448 CSM: CXXSpecialMemberKind::MoveAssignment)
15449 : ClassDecl->hasTrivialMoveAssignment());
15450
15451 // Note that we have added this copy-assignment operator.
15452 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15453
15454 Scope *S = getScopeForContext(Ctx: ClassDecl);
15455 CheckImplicitSpecialMemberDeclaration(S, FD: MoveAssignment);
15456
15457 if (ShouldDeleteSpecialMember(MD: MoveAssignment,
15458 CSM: CXXSpecialMemberKind::MoveAssignment)) {
15459 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15460 SetDeclDeleted(dcl: MoveAssignment, DelLoc: ClassLoc);
15461 }
15462
15463 if (S)
15464 PushOnScopeChains(D: MoveAssignment, S, AddToContext: false);
15465 ClassDecl->addDecl(D: MoveAssignment);
15466
15467 return MoveAssignment;
15468}
15469
15470/// Check if we're implicitly defining a move assignment operator for a class
15471/// with virtual bases. Such a move assignment might move-assign the virtual
15472/// base multiple times.
15473static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15474 SourceLocation CurrentLocation) {
15475 assert(!Class->isDependentContext() && "should not define dependent move");
15476
15477 // Only a virtual base could get implicitly move-assigned multiple times.
15478 // Only a non-trivial move assignment can observe this. We only want to
15479 // diagnose if we implicitly define an assignment operator that assigns
15480 // two base classes, both of which move-assign the same virtual base.
15481 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15482 Class->getNumBases() < 2)
15483 return;
15484
15485 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15486 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15487 VBaseMap VBases;
15488
15489 for (auto &BI : Class->bases()) {
15490 Worklist.push_back(Elt: &BI);
15491 while (!Worklist.empty()) {
15492 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15493 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15494
15495 // If the base has no non-trivial move assignment operators,
15496 // we don't care about moves from it.
15497 if (!Base->hasNonTrivialMoveAssignment())
15498 continue;
15499
15500 // If there's nothing virtual here, skip it.
15501 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15502 continue;
15503
15504 // If we're not actually going to call a move assignment for this base,
15505 // or the selected move assignment is trivial, skip it.
15506 Sema::SpecialMemberOverloadResult SMOR =
15507 S.LookupSpecialMember(D: Base, SM: CXXSpecialMemberKind::MoveAssignment,
15508 /*ConstArg*/ false, /*VolatileArg*/ false,
15509 /*RValueThis*/ true, /*ConstThis*/ false,
15510 /*VolatileThis*/ false);
15511 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15512 !SMOR.getMethod()->isMoveAssignmentOperator())
15513 continue;
15514
15515 if (BaseSpec->isVirtual()) {
15516 // We're going to move-assign this virtual base, and its move
15517 // assignment operator is not trivial. If this can happen for
15518 // multiple distinct direct bases of Class, diagnose it. (If it
15519 // only happens in one base, we'll diagnose it when synthesizing
15520 // that base class's move assignment operator.)
15521 CXXBaseSpecifier *&Existing =
15522 VBases.insert(KV: std::make_pair(x: Base->getCanonicalDecl(), y: &BI))
15523 .first->second;
15524 if (Existing && Existing != &BI) {
15525 S.Diag(Loc: CurrentLocation, DiagID: diag::warn_vbase_moved_multiple_times)
15526 << Class << Base;
15527 S.Diag(Loc: Existing->getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15528 << (Base->getCanonicalDecl() ==
15529 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15530 << Base << Existing->getType() << Existing->getSourceRange();
15531 S.Diag(Loc: BI.getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15532 << (Base->getCanonicalDecl() ==
15533 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15534 << Base << BI.getType() << BaseSpec->getSourceRange();
15535
15536 // Only diagnose each vbase once.
15537 Existing = nullptr;
15538 }
15539 } else {
15540 // Only walk over bases that have defaulted move assignment operators.
15541 // We assume that any user-provided move assignment operator handles
15542 // the multiple-moves-of-vbase case itself somehow.
15543 if (!SMOR.getMethod()->isDefaulted())
15544 continue;
15545
15546 // We're going to move the base classes of Base. Add them to the list.
15547 llvm::append_range(C&: Worklist, R: llvm::make_pointer_range(Range: Base->bases()));
15548 }
15549 }
15550 }
15551}
15552
15553void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15554 CXXMethodDecl *MoveAssignOperator) {
15555 assert((MoveAssignOperator->isDefaulted() &&
15556 MoveAssignOperator->isOverloadedOperator() &&
15557 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15558 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15559 !MoveAssignOperator->isDeleted()) &&
15560 "DefineImplicitMoveAssignment called for wrong function");
15561 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15562 return;
15563
15564 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15565 if (ClassDecl->isInvalidDecl()) {
15566 MoveAssignOperator->setInvalidDecl();
15567 return;
15568 }
15569
15570 // C++0x [class.copy]p28:
15571 // The implicitly-defined or move assignment operator for a non-union class
15572 // X performs memberwise move assignment of its subobjects. The direct base
15573 // classes of X are assigned first, in the order of their declaration in the
15574 // base-specifier-list, and then the immediate non-static data members of X
15575 // are assigned, in the order in which they were declared in the class
15576 // definition.
15577
15578 // Issue a warning if our implicit move assignment operator will move
15579 // from a virtual base more than once.
15580 checkMoveAssignmentForRepeatedMove(S&: *this, Class: ClassDecl, CurrentLocation);
15581
15582 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15583
15584 // The exception specification is needed because we are defining the
15585 // function.
15586 ResolveExceptionSpec(Loc: CurrentLocation,
15587 FPT: MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15588
15589 // Add a context note for diagnostics produced after this point.
15590 Scope.addContextNote(UseLoc: CurrentLocation);
15591
15592 // The statements that form the synthesized function body.
15593 SmallVector<Stmt*, 8> Statements;
15594
15595 // The parameter for the "other" object, which we are move from.
15596 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(I: 0);
15597 QualType OtherRefType =
15598 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15599
15600 // Our location for everything implicitly-generated.
15601 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15602 ? MoveAssignOperator->getEndLoc()
15603 : MoveAssignOperator->getLocation();
15604
15605 // Builds a reference to the "other" object.
15606 RefBuilder OtherRef(Other, OtherRefType);
15607 // Cast to rvalue.
15608 MoveCastBuilder MoveOther(OtherRef);
15609
15610 // Builds the function object parameter.
15611 std::optional<ThisBuilder> This;
15612 std::optional<DerefBuilder> DerefThis;
15613 std::optional<RefBuilder> ExplicitObject;
15614 QualType ObjectType;
15615 bool IsArrow = false;
15616 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15617 ObjectType = MoveAssignOperator->getParamDecl(i: 0)->getType();
15618 if (ObjectType->isReferenceType())
15619 ObjectType = ObjectType->getPointeeType();
15620 ExplicitObject.emplace(args: MoveAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15621 } else {
15622 ObjectType = getCurrentThisType();
15623 This.emplace();
15624 DerefThis.emplace(args&: *This);
15625 IsArrow = !getLangOpts().HLSL;
15626 }
15627 ExprBuilder &ObjectParameter =
15628 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15629
15630 // Assign base classes.
15631 bool Invalid = false;
15632 for (auto &Base : ClassDecl->bases()) {
15633 // C++11 [class.copy]p28:
15634 // It is unspecified whether subobjects representing virtual base classes
15635 // are assigned more than once by the implicitly-defined copy assignment
15636 // operator.
15637 // FIXME: Do not assign to a vbase that will be assigned by some other base
15638 // class. For a move-assignment, this can result in the vbase being moved
15639 // multiple times.
15640
15641 // Form the assignment:
15642 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15643 QualType BaseType = Base.getType().getUnqualifiedType();
15644 if (!BaseType->isRecordType()) {
15645 Invalid = true;
15646 continue;
15647 }
15648
15649 CXXCastPath BasePath;
15650 BasePath.push_back(Elt: &Base);
15651
15652 // Construct the "from" expression, which is an implicit cast to the
15653 // appropriately-qualified base type.
15654 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15655
15656 // Implicitly cast "this" to the appropriately-qualified base type.
15657 // Dereference "this".
15658 CastBuilder To(
15659 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15660 : static_cast<ExprBuilder &>(*DerefThis),
15661 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15662 VK_LValue, BasePath);
15663
15664 // Build the move.
15665 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15666 To, From,
15667 /*CopyingBaseSubobject=*/true,
15668 /*Copying=*/false);
15669 if (Move.isInvalid()) {
15670 MoveAssignOperator->setInvalidDecl();
15671 return;
15672 }
15673
15674 // Success! Record the move.
15675 Statements.push_back(Elt: Move.getAs<Expr>());
15676 }
15677
15678 // Assign non-static members.
15679 for (auto *Field : ClassDecl->fields()) {
15680 // FIXME: We should form some kind of AST representation for the implied
15681 // memcpy in a union copy operation.
15682 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15683 continue;
15684
15685 if (Field->isInvalidDecl()) {
15686 Invalid = true;
15687 continue;
15688 }
15689
15690 // Check for members of reference type; we can't move those.
15691 if (Field->getType()->isReferenceType()) {
15692 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15693 << Context.getTagDeclType(Decl: ClassDecl) << 0 << Field->getDeclName();
15694 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15695 Invalid = true;
15696 continue;
15697 }
15698
15699 // Check for members of const-qualified, non-class type.
15700 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15701 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15702 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15703 << Context.getTagDeclType(Decl: ClassDecl) << 1 << Field->getDeclName();
15704 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15705 Invalid = true;
15706 continue;
15707 }
15708
15709 // Suppress assigning zero-width bitfields.
15710 if (Field->isZeroLengthBitField())
15711 continue;
15712
15713 QualType FieldType = Field->getType().getNonReferenceType();
15714 if (FieldType->isIncompleteArrayType()) {
15715 assert(ClassDecl->hasFlexibleArrayMember() &&
15716 "Incomplete array type is not valid");
15717 continue;
15718 }
15719
15720 // Build references to the field in the object we're copying from and to.
15721 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15722 LookupMemberName);
15723 MemberLookup.addDecl(D: Field);
15724 MemberLookup.resolveKind();
15725 MemberBuilder From(MoveOther, OtherRefType,
15726 /*IsArrow=*/false, MemberLookup);
15727 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15728
15729 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15730 "Member reference with rvalue base must be rvalue except for reference "
15731 "members, which aren't allowed for move assignment.");
15732
15733 // Build the move of this field.
15734 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15735 To, From,
15736 /*CopyingBaseSubobject=*/false,
15737 /*Copying=*/false);
15738 if (Move.isInvalid()) {
15739 MoveAssignOperator->setInvalidDecl();
15740 return;
15741 }
15742
15743 // Success! Record the copy.
15744 Statements.push_back(Elt: Move.getAs<Stmt>());
15745 }
15746
15747 if (!Invalid) {
15748 // Add a "return *this;"
15749 Expr *ThisExpr =
15750 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15751 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15752 : static_cast<ExprBuilder &>(*DerefThis))
15753 .build(S&: *this, Loc);
15754
15755 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15756 if (Return.isInvalid())
15757 Invalid = true;
15758 else
15759 Statements.push_back(Elt: Return.getAs<Stmt>());
15760 }
15761
15762 if (Invalid) {
15763 MoveAssignOperator->setInvalidDecl();
15764 return;
15765 }
15766
15767 StmtResult Body;
15768 {
15769 CompoundScopeRAII CompoundScope(*this);
15770 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15771 /*isStmtExpr=*/false);
15772 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15773 }
15774 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15775 MoveAssignOperator->markUsed(C&: Context);
15776
15777 if (ASTMutationListener *L = getASTMutationListener()) {
15778 L->CompletedImplicitDefinition(D: MoveAssignOperator);
15779 }
15780}
15781
15782CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15783 CXXRecordDecl *ClassDecl) {
15784 // C++ [class.copy]p4:
15785 // If the class definition does not explicitly declare a copy
15786 // constructor, one is declared implicitly.
15787 assert(ClassDecl->needsImplicitCopyConstructor());
15788
15789 DeclaringSpecialMember DSM(*this, ClassDecl,
15790 CXXSpecialMemberKind::CopyConstructor);
15791 if (DSM.isAlreadyBeingDeclared())
15792 return nullptr;
15793
15794 QualType ClassType = Context.getTypeDeclType(Decl: ClassDecl);
15795 QualType ArgType = ClassType;
15796 ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
15797 NamedType: ArgType, OwnedTagDecl: nullptr);
15798 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15799 if (Const)
15800 ArgType = ArgType.withConst();
15801
15802 LangAS AS = getDefaultCXXMethodAddrSpace();
15803 if (AS != LangAS::Default)
15804 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15805
15806 ArgType = Context.getLValueReferenceType(T: ArgType);
15807
15808 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15809 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Const);
15810
15811 DeclarationName Name
15812 = Context.DeclarationNames.getCXXConstructorName(
15813 Ty: Context.getCanonicalType(T: ClassType));
15814 SourceLocation ClassLoc = ClassDecl->getLocation();
15815 DeclarationNameInfo NameInfo(Name, ClassLoc);
15816
15817 // An implicitly-declared copy constructor is an inline public
15818 // member of its class.
15819 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15820 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
15821 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15822 /*isInline=*/true,
15823 /*isImplicitlyDeclared=*/true,
15824 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
15825 : ConstexprSpecKind::Unspecified);
15826 CopyConstructor->setAccess(AS_public);
15827 CopyConstructor->setDefaulted();
15828
15829 setupImplicitSpecialMemberType(SpecialMem: CopyConstructor, ResultTy: Context.VoidTy, Args: ArgType);
15830
15831 if (getLangOpts().CUDA)
15832 CUDA().inferTargetForImplicitSpecialMember(
15833 ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, MemberDecl: CopyConstructor,
15834 /* ConstRHS */ Const,
15835 /* Diagnose */ false);
15836
15837 // During template instantiation of special member functions we need a
15838 // reliable TypeSourceInfo for the parameter types in order to allow functions
15839 // to be substituted.
15840 TypeSourceInfo *TSI = nullptr;
15841 if (inTemplateInstantiation() && ClassDecl->isLambda())
15842 TSI = Context.getTrivialTypeSourceInfo(T: ArgType);
15843
15844 // Add the parameter to the constructor.
15845 ParmVarDecl *FromParam =
15846 ParmVarDecl::Create(C&: Context, DC: CopyConstructor, StartLoc: ClassLoc, IdLoc: ClassLoc,
15847 /*IdentifierInfo=*/Id: nullptr, T: ArgType,
15848 /*TInfo=*/TSI, S: SC_None, DefArg: nullptr);
15849 CopyConstructor->setParams(FromParam);
15850
15851 CopyConstructor->setTrivial(
15852 ClassDecl->needsOverloadResolutionForCopyConstructor()
15853 ? SpecialMemberIsTrivial(MD: CopyConstructor,
15854 CSM: CXXSpecialMemberKind::CopyConstructor)
15855 : ClassDecl->hasTrivialCopyConstructor());
15856
15857 CopyConstructor->setTrivialForCall(
15858 ClassDecl->hasAttr<TrivialABIAttr>() ||
15859 (ClassDecl->needsOverloadResolutionForCopyConstructor()
15860 ? SpecialMemberIsTrivial(MD: CopyConstructor,
15861 CSM: CXXSpecialMemberKind::CopyConstructor,
15862 TAH: TrivialABIHandling::ConsiderTrivialABI)
15863 : ClassDecl->hasTrivialCopyConstructorForCall()));
15864
15865 // Note that we have declared this constructor.
15866 ++getASTContext().NumImplicitCopyConstructorsDeclared;
15867
15868 Scope *S = getScopeForContext(Ctx: ClassDecl);
15869 CheckImplicitSpecialMemberDeclaration(S, FD: CopyConstructor);
15870
15871 if (ShouldDeleteSpecialMember(MD: CopyConstructor,
15872 CSM: CXXSpecialMemberKind::CopyConstructor)) {
15873 ClassDecl->setImplicitCopyConstructorIsDeleted();
15874 SetDeclDeleted(dcl: CopyConstructor, DelLoc: ClassLoc);
15875 }
15876
15877 if (S)
15878 PushOnScopeChains(D: CopyConstructor, S, AddToContext: false);
15879 ClassDecl->addDecl(D: CopyConstructor);
15880
15881 return CopyConstructor;
15882}
15883
15884void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15885 CXXConstructorDecl *CopyConstructor) {
15886 assert((CopyConstructor->isDefaulted() &&
15887 CopyConstructor->isCopyConstructor() &&
15888 !CopyConstructor->doesThisDeclarationHaveABody() &&
15889 !CopyConstructor->isDeleted()) &&
15890 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15891 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15892 return;
15893
15894 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15895 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15896
15897 SynthesizedFunctionScope Scope(*this, CopyConstructor);
15898
15899 // The exception specification is needed because we are defining the
15900 // function.
15901 ResolveExceptionSpec(Loc: CurrentLocation,
15902 FPT: CopyConstructor->getType()->castAs<FunctionProtoType>());
15903 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
15904
15905 // Add a context note for diagnostics produced after this point.
15906 Scope.addContextNote(UseLoc: CurrentLocation);
15907
15908 // C++11 [class.copy]p7:
15909 // The [definition of an implicitly declared copy constructor] is
15910 // deprecated if the class has a user-declared copy assignment operator
15911 // or a user-declared destructor.
15912 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15913 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyConstructor);
15914
15915 if (SetCtorInitializers(Constructor: CopyConstructor, /*AnyErrors=*/false)) {
15916 CopyConstructor->setInvalidDecl();
15917 } else {
15918 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15919 ? CopyConstructor->getEndLoc()
15920 : CopyConstructor->getLocation();
15921 Sema::CompoundScopeRAII CompoundScope(*this);
15922 CopyConstructor->setBody(
15923 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
15924 CopyConstructor->markUsed(C&: Context);
15925 }
15926
15927 if (ASTMutationListener *L = getASTMutationListener()) {
15928 L->CompletedImplicitDefinition(D: CopyConstructor);
15929 }
15930}
15931
15932CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15933 CXXRecordDecl *ClassDecl) {
15934 assert(ClassDecl->needsImplicitMoveConstructor());
15935
15936 DeclaringSpecialMember DSM(*this, ClassDecl,
15937 CXXSpecialMemberKind::MoveConstructor);
15938 if (DSM.isAlreadyBeingDeclared())
15939 return nullptr;
15940
15941 QualType ClassType = Context.getTypeDeclType(Decl: ClassDecl);
15942
15943 QualType ArgType = ClassType;
15944 ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
15945 NamedType: ArgType, OwnedTagDecl: nullptr);
15946 LangAS AS = getDefaultCXXMethodAddrSpace();
15947 if (AS != LangAS::Default)
15948 ArgType = Context.getAddrSpaceQualType(T: ClassType, AddressSpace: AS);
15949 ArgType = Context.getRValueReferenceType(T: ArgType);
15950
15951 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15952 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, ConstArg: false);
15953
15954 DeclarationName Name
15955 = Context.DeclarationNames.getCXXConstructorName(
15956 Ty: Context.getCanonicalType(T: ClassType));
15957 SourceLocation ClassLoc = ClassDecl->getLocation();
15958 DeclarationNameInfo NameInfo(Name, ClassLoc);
15959
15960 // C++11 [class.copy]p11:
15961 // An implicitly-declared copy/move constructor is an inline public
15962 // member of its class.
15963 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15964 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
15965 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15966 /*isInline=*/true,
15967 /*isImplicitlyDeclared=*/true,
15968 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
15969 : ConstexprSpecKind::Unspecified);
15970 MoveConstructor->setAccess(AS_public);
15971 MoveConstructor->setDefaulted();
15972
15973 setupImplicitSpecialMemberType(SpecialMem: MoveConstructor, ResultTy: Context.VoidTy, Args: ArgType);
15974
15975 if (getLangOpts().CUDA)
15976 CUDA().inferTargetForImplicitSpecialMember(
15977 ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, MemberDecl: MoveConstructor,
15978 /* ConstRHS */ false,
15979 /* Diagnose */ false);
15980
15981 // Add the parameter to the constructor.
15982 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveConstructor,
15983 StartLoc: ClassLoc, IdLoc: ClassLoc,
15984 /*IdentifierInfo=*/Id: nullptr,
15985 T: ArgType, /*TInfo=*/nullptr,
15986 S: SC_None, DefArg: nullptr);
15987 MoveConstructor->setParams(FromParam);
15988
15989 MoveConstructor->setTrivial(
15990 ClassDecl->needsOverloadResolutionForMoveConstructor()
15991 ? SpecialMemberIsTrivial(MD: MoveConstructor,
15992 CSM: CXXSpecialMemberKind::MoveConstructor)
15993 : ClassDecl->hasTrivialMoveConstructor());
15994
15995 MoveConstructor->setTrivialForCall(
15996 ClassDecl->hasAttr<TrivialABIAttr>() ||
15997 (ClassDecl->needsOverloadResolutionForMoveConstructor()
15998 ? SpecialMemberIsTrivial(MD: MoveConstructor,
15999 CSM: CXXSpecialMemberKind::MoveConstructor,
16000 TAH: TrivialABIHandling::ConsiderTrivialABI)
16001 : ClassDecl->hasTrivialMoveConstructorForCall()));
16002
16003 // Note that we have declared this constructor.
16004 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16005
16006 Scope *S = getScopeForContext(Ctx: ClassDecl);
16007 CheckImplicitSpecialMemberDeclaration(S, FD: MoveConstructor);
16008
16009 if (ShouldDeleteSpecialMember(MD: MoveConstructor,
16010 CSM: CXXSpecialMemberKind::MoveConstructor)) {
16011 ClassDecl->setImplicitMoveConstructorIsDeleted();
16012 SetDeclDeleted(dcl: MoveConstructor, DelLoc: ClassLoc);
16013 }
16014
16015 if (S)
16016 PushOnScopeChains(D: MoveConstructor, S, AddToContext: false);
16017 ClassDecl->addDecl(D: MoveConstructor);
16018
16019 return MoveConstructor;
16020}
16021
16022void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
16023 CXXConstructorDecl *MoveConstructor) {
16024 assert((MoveConstructor->isDefaulted() &&
16025 MoveConstructor->isMoveConstructor() &&
16026 !MoveConstructor->doesThisDeclarationHaveABody() &&
16027 !MoveConstructor->isDeleted()) &&
16028 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16029 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16030 return;
16031
16032 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16033 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16034
16035 SynthesizedFunctionScope Scope(*this, MoveConstructor);
16036
16037 // The exception specification is needed because we are defining the
16038 // function.
16039 ResolveExceptionSpec(Loc: CurrentLocation,
16040 FPT: MoveConstructor->getType()->castAs<FunctionProtoType>());
16041 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16042
16043 // Add a context note for diagnostics produced after this point.
16044 Scope.addContextNote(UseLoc: CurrentLocation);
16045
16046 if (SetCtorInitializers(Constructor: MoveConstructor, /*AnyErrors=*/false)) {
16047 MoveConstructor->setInvalidDecl();
16048 } else {
16049 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16050 ? MoveConstructor->getEndLoc()
16051 : MoveConstructor->getLocation();
16052 Sema::CompoundScopeRAII CompoundScope(*this);
16053 MoveConstructor->setBody(
16054 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16055 MoveConstructor->markUsed(C&: Context);
16056 }
16057
16058 if (ASTMutationListener *L = getASTMutationListener()) {
16059 L->CompletedImplicitDefinition(D: MoveConstructor);
16060 }
16061}
16062
16063bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
16064 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD);
16065}
16066
16067void Sema::DefineImplicitLambdaToFunctionPointerConversion(
16068 SourceLocation CurrentLocation,
16069 CXXConversionDecl *Conv) {
16070 SynthesizedFunctionScope Scope(*this, Conv);
16071 assert(!Conv->getReturnType()->isUndeducedType());
16072
16073 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16074 CallingConv CC =
16075 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16076
16077 CXXRecordDecl *Lambda = Conv->getParent();
16078 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16079 FunctionDecl *Invoker =
16080 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16081 ? CallOp
16082 : Lambda->getLambdaStaticInvoker(CC);
16083
16084 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16085 CallOp = InstantiateFunctionDeclaration(
16086 FTD: CallOp->getDescribedFunctionTemplate(), Args: TemplateArgs, Loc: CurrentLocation);
16087 if (!CallOp)
16088 return;
16089
16090 if (CallOp != Invoker) {
16091 Invoker = InstantiateFunctionDeclaration(
16092 FTD: Invoker->getDescribedFunctionTemplate(), Args: TemplateArgs,
16093 Loc: CurrentLocation);
16094 if (!Invoker)
16095 return;
16096 }
16097 }
16098
16099 if (CallOp->isInvalidDecl())
16100 return;
16101
16102 // Mark the call operator referenced (and add to pending instantiations
16103 // if necessary).
16104 // For both the conversion and static-invoker template specializations
16105 // we construct their body's in this function, so no need to add them
16106 // to the PendingInstantiations.
16107 MarkFunctionReferenced(Loc: CurrentLocation, Func: CallOp);
16108
16109 if (Invoker != CallOp) {
16110 // Fill in the __invoke function with a dummy implementation. IR generation
16111 // will fill in the actual details. Update its type in case it contained
16112 // an 'auto'.
16113 Invoker->markUsed(C&: Context);
16114 Invoker->setReferenced();
16115 Invoker->setType(Conv->getReturnType()->getPointeeType());
16116 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16117 }
16118
16119 // Construct the body of the conversion function { return __invoke; }.
16120 Expr *FunctionRef = BuildDeclRefExpr(D: Invoker, Ty: Invoker->getType(), VK: VK_LValue,
16121 Loc: Conv->getLocation());
16122 assert(FunctionRef && "Can't refer to __invoke function?");
16123 Stmt *Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: FunctionRef).get();
16124 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: Return, FPFeatures: FPOptionsOverride(),
16125 LB: Conv->getLocation(), RB: Conv->getLocation()));
16126 Conv->markUsed(C&: Context);
16127 Conv->setReferenced();
16128
16129 if (ASTMutationListener *L = getASTMutationListener()) {
16130 L->CompletedImplicitDefinition(D: Conv);
16131 if (Invoker != CallOp)
16132 L->CompletedImplicitDefinition(D: Invoker);
16133 }
16134}
16135
16136void Sema::DefineImplicitLambdaToBlockPointerConversion(
16137 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16138 assert(!Conv->getParent()->isGenericLambda());
16139
16140 SynthesizedFunctionScope Scope(*this, Conv);
16141
16142 // Copy-initialize the lambda object as needed to capture it.
16143 Expr *This = ActOnCXXThis(Loc: CurrentLocation).get();
16144 Expr *DerefThis =CreateBuiltinUnaryOp(OpLoc: CurrentLocation, Opc: UO_Deref, InputExpr: This).get();
16145
16146 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16147 ConvLocation: Conv->getLocation(),
16148 Conv, Src: DerefThis);
16149
16150 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16151 // behavior. Note that only the general conversion function does this
16152 // (since it's unusable otherwise); in the case where we inline the
16153 // block literal, it has block literal lifetime semantics.
16154 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16155 BuildBlock = ImplicitCastExpr::Create(
16156 Context, T: BuildBlock.get()->getType(), Kind: CK_CopyAndAutoreleaseBlockObject,
16157 Operand: BuildBlock.get(), BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
16158
16159 if (BuildBlock.isInvalid()) {
16160 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16161 Conv->setInvalidDecl();
16162 return;
16163 }
16164
16165 // Create the return statement that returns the block from the conversion
16166 // function.
16167 StmtResult Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: BuildBlock.get());
16168 if (Return.isInvalid()) {
16169 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16170 Conv->setInvalidDecl();
16171 return;
16172 }
16173
16174 // Set the body of the conversion function.
16175 Stmt *ReturnS = Return.get();
16176 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: ReturnS, FPFeatures: FPOptionsOverride(),
16177 LB: Conv->getLocation(), RB: Conv->getLocation()));
16178 Conv->markUsed(C&: Context);
16179
16180 // We're done; notify the mutation listener, if any.
16181 if (ASTMutationListener *L = getASTMutationListener()) {
16182 L->CompletedImplicitDefinition(D: Conv);
16183 }
16184}
16185
16186/// Determine whether the given list arguments contains exactly one
16187/// "real" (non-default) argument.
16188static bool hasOneRealArgument(MultiExprArg Args) {
16189 switch (Args.size()) {
16190 case 0:
16191 return false;
16192
16193 default:
16194 if (!Args[1]->isDefaultArgument())
16195 return false;
16196
16197 [[fallthrough]];
16198 case 1:
16199 return !Args[0]->isDefaultArgument();
16200 }
16201
16202 return false;
16203}
16204
16205ExprResult Sema::BuildCXXConstructExpr(
16206 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16207 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16208 bool HadMultipleCandidates, bool IsListInitialization,
16209 bool IsStdInitListInitialization, bool RequiresZeroInit,
16210 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16211 bool Elidable = false;
16212
16213 // C++0x [class.copy]p34:
16214 // When certain criteria are met, an implementation is allowed to
16215 // omit the copy/move construction of a class object, even if the
16216 // copy/move constructor and/or destructor for the object have
16217 // side effects. [...]
16218 // - when a temporary class object that has not been bound to a
16219 // reference (12.2) would be copied/moved to a class object
16220 // with the same cv-unqualified type, the copy/move operation
16221 // can be omitted by constructing the temporary object
16222 // directly into the target of the omitted copy/move
16223 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16224 // FIXME: Converting constructors should also be accepted.
16225 // But to fix this, the logic that digs down into a CXXConstructExpr
16226 // to find the source object needs to handle it.
16227 // Right now it assumes the source object is passed directly as the
16228 // first argument.
16229 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(Args: ExprArgs)) {
16230 Expr *SubExpr = ExprArgs[0];
16231 // FIXME: Per above, this is also incorrect if we want to accept
16232 // converting constructors, as isTemporaryObject will
16233 // reject temporaries with different type from the
16234 // CXXRecord itself.
16235 Elidable = SubExpr->isTemporaryObject(
16236 Ctx&: Context, TempTy: cast<CXXRecordDecl>(Val: FoundDecl->getDeclContext()));
16237 }
16238
16239 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16240 FoundDecl, Constructor,
16241 Elidable, Exprs: ExprArgs, HadMultipleCandidates,
16242 IsListInitialization,
16243 IsStdInitListInitialization, RequiresZeroInit,
16244 ConstructKind, ParenRange);
16245}
16246
16247ExprResult Sema::BuildCXXConstructExpr(
16248 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16249 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16250 bool HadMultipleCandidates, bool IsListInitialization,
16251 bool IsStdInitListInitialization, bool RequiresZeroInit,
16252 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16253 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl)) {
16254 Constructor = findInheritingConstructor(Loc: ConstructLoc, BaseCtor: Constructor, Shadow);
16255 // The only way to get here is if we did overload resolution to find the
16256 // shadow decl, so we don't need to worry about re-checking the trailing
16257 // requires clause.
16258 if (DiagnoseUseOfOverloadedDecl(D: Constructor, Loc: ConstructLoc))
16259 return ExprError();
16260 }
16261
16262 return BuildCXXConstructExpr(
16263 ConstructLoc, DeclInitType, Constructor, Elidable, Exprs: ExprArgs,
16264 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16265 RequiresZeroInit, ConstructKind, ParenRange);
16266}
16267
16268/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16269/// including handling of its default argument expressions.
16270ExprResult Sema::BuildCXXConstructExpr(
16271 SourceLocation ConstructLoc, QualType DeclInitType,
16272 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16273 bool HadMultipleCandidates, bool IsListInitialization,
16274 bool IsStdInitListInitialization, bool RequiresZeroInit,
16275 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16276 assert(declaresSameEntity(
16277 Constructor->getParent(),
16278 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16279 "given constructor for wrong type");
16280 MarkFunctionReferenced(Loc: ConstructLoc, Func: Constructor);
16281 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc: ConstructLoc, Callee: Constructor))
16282 return ExprError();
16283
16284 return CheckForImmediateInvocation(
16285 E: CXXConstructExpr::Create(
16286 Ctx: Context, Ty: DeclInitType, Loc: ConstructLoc, Ctor: Constructor, Elidable, Args: ExprArgs,
16287 HadMultipleCandidates, ListInitialization: IsListInitialization,
16288 StdInitListInitialization: IsStdInitListInitialization, ZeroInitialization: RequiresZeroInit,
16289 ConstructKind: static_cast<CXXConstructionKind>(ConstructKind), ParenOrBraceRange: ParenRange),
16290 Decl: Constructor);
16291}
16292
16293void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
16294 if (VD->isInvalidDecl()) return;
16295 // If initializing the variable failed, don't also diagnose problems with
16296 // the destructor, they're likely related.
16297 if (VD->getInit() && VD->getInit()->containsErrors())
16298 return;
16299
16300 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Record->getDecl());
16301 if (ClassDecl->isInvalidDecl()) return;
16302 if (ClassDecl->hasIrrelevantDestructor()) return;
16303 if (ClassDecl->isDependentContext()) return;
16304
16305 if (VD->isNoDestroy(getASTContext()))
16306 return;
16307
16308 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
16309 // The result of `LookupDestructor` might be nullptr if the destructor is
16310 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16311 // will not be selected by `CXXRecordDecl::getDestructor()`.
16312 if (!Destructor)
16313 return;
16314 // If this is an array, we'll require the destructor during initialization, so
16315 // we can skip over this. We still want to emit exit-time destructor warnings
16316 // though.
16317 if (!VD->getType()->isArrayType()) {
16318 MarkFunctionReferenced(Loc: VD->getLocation(), Func: Destructor);
16319 CheckDestructorAccess(Loc: VD->getLocation(), Dtor: Destructor,
16320 PDiag: PDiag(DiagID: diag::err_access_dtor_var)
16321 << VD->getDeclName() << VD->getType());
16322 DiagnoseUseOfDecl(D: Destructor, Locs: VD->getLocation());
16323 }
16324
16325 if (Destructor->isTrivial()) return;
16326
16327 // If the destructor is constexpr, check whether the variable has constant
16328 // destruction now.
16329 if (Destructor->isConstexpr()) {
16330 bool HasConstantInit = false;
16331 if (VD->getInit() && !VD->getInit()->isValueDependent())
16332 HasConstantInit = VD->evaluateValue();
16333 SmallVector<PartialDiagnosticAt, 8> Notes;
16334 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16335 HasConstantInit) {
16336 Diag(Loc: VD->getLocation(),
16337 DiagID: diag::err_constexpr_var_requires_const_destruction) << VD;
16338 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16339 Diag(Loc: Notes[I].first, PD: Notes[I].second);
16340 }
16341 }
16342
16343 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Ctx: Context))
16344 return;
16345
16346 // Emit warning for non-trivial dtor in global scope (a real global,
16347 // class-static, function-static).
16348 if (!VD->hasAttr<AlwaysDestroyAttr>())
16349 Diag(Loc: VD->getLocation(), DiagID: diag::warn_exit_time_destructor);
16350
16351 // TODO: this should be re-enabled for static locals by !CXAAtExit
16352 if (!VD->isStaticLocal())
16353 Diag(Loc: VD->getLocation(), DiagID: diag::warn_global_destructor);
16354}
16355
16356bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16357 QualType DeclInitType, MultiExprArg ArgsPtr,
16358 SourceLocation Loc,
16359 SmallVectorImpl<Expr *> &ConvertedArgs,
16360 bool AllowExplicit,
16361 bool IsListInitialization) {
16362 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16363 unsigned NumArgs = ArgsPtr.size();
16364 Expr **Args = ArgsPtr.data();
16365
16366 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16367 unsigned NumParams = Proto->getNumParams();
16368
16369 // If too few arguments are available, we'll fill in the rest with defaults.
16370 if (NumArgs < NumParams)
16371 ConvertedArgs.reserve(N: NumParams);
16372 else
16373 ConvertedArgs.reserve(N: NumArgs);
16374
16375 VariadicCallType CallType = Proto->isVariadic()
16376 ? VariadicCallType::Constructor
16377 : VariadicCallType::DoesNotApply;
16378 SmallVector<Expr *, 8> AllArgs;
16379 bool Invalid = GatherArgumentsForCall(
16380 CallLoc: Loc, FDecl: Constructor, Proto, FirstParam: 0, Args: llvm::ArrayRef(Args, NumArgs), AllArgs,
16381 CallType, AllowExplicit, IsListInitialization);
16382 ConvertedArgs.append(in_start: AllArgs.begin(), in_end: AllArgs.end());
16383
16384 DiagnoseSentinelCalls(D: Constructor, Loc, Args: AllArgs);
16385
16386 CheckConstructorCall(FDecl: Constructor, ThisType: DeclInitType, Args: llvm::ArrayRef(AllArgs),
16387 Proto, Loc);
16388
16389 return Invalid;
16390}
16391
16392TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {
16393 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16394 return typeAwareAllocationModeFromBool(IsTypeAwareAllocation: SeenTypedOperators);
16395}
16396
16397FunctionDecl *
16398Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,
16399 QualType DeallocType, SourceLocation Loc) {
16400 if (DeallocType.isNull())
16401 return nullptr;
16402
16403 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16404 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16405 return nullptr;
16406
16407 if (FnDecl->isVariadic())
16408 return nullptr;
16409
16410 unsigned NumParams = FnDecl->getNumParams();
16411 constexpr unsigned RequiredParameterCount =
16412 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16413 // A usual deallocation function has no placement parameters
16414 if (NumParams != RequiredParameterCount)
16415 return nullptr;
16416
16417 // A type aware allocation is only usual if the only dependent parameter is
16418 // the first parameter.
16419 if (llvm::any_of(Range: FnDecl->parameters().drop_front(),
16420 P: [](const ParmVarDecl *ParamDecl) {
16421 return ParamDecl->getType()->isDependentType();
16422 }))
16423 return nullptr;
16424
16425 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(Type: DeallocType, Loc);
16426 if (SpecializedTypeIdentity.isNull())
16427 return nullptr;
16428
16429 SmallVector<QualType, RequiredParameterCount> ArgTypes;
16430 ArgTypes.reserve(N: NumParams);
16431
16432 // The first parameter to a type aware operator delete is by definition the
16433 // type-identity argument, so we explicitly set this to the target
16434 // type-identity type, the remaining usual parameters should then simply match
16435 // the type declared in the function template.
16436 ArgTypes.push_back(Elt: SpecializedTypeIdentity);
16437 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16438 ArgTypes.push_back(Elt: FnDecl->getParamDecl(i: ParamIdx)->getType());
16439
16440 FunctionProtoType::ExtProtoInfo EPI;
16441 QualType ExpectedFunctionType =
16442 Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI);
16443 sema::TemplateDeductionInfo Info(Loc);
16444 FunctionDecl *Result;
16445 if (DeduceTemplateArguments(FunctionTemplate: FnTemplateDecl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType,
16446 Specialization&: Result, Info) != TemplateDeductionResult::Success)
16447 return nullptr;
16448 return Result;
16449}
16450
16451static inline bool
16452CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16453 const FunctionDecl *FnDecl) {
16454 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16455 if (isa<NamespaceDecl>(Val: DC)) {
16456 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16457 DiagID: diag::err_operator_new_delete_declared_in_namespace)
16458 << FnDecl->getDeclName();
16459 }
16460
16461 if (isa<TranslationUnitDecl>(Val: DC) &&
16462 FnDecl->getStorageClass() == SC_Static) {
16463 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16464 DiagID: diag::err_operator_new_delete_declared_static)
16465 << FnDecl->getDeclName();
16466 }
16467
16468 return false;
16469}
16470
16471static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16472 const PointerType *PtrTy) {
16473 auto &Ctx = SemaRef.Context;
16474 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16475 PtrQuals.removeAddressSpace();
16476 return Ctx.getPointerType(T: Ctx.getCanonicalType(T: Ctx.getQualifiedType(
16477 T: PtrTy->getPointeeType().getUnqualifiedType(), Qs: PtrQuals)));
16478}
16479
16480enum class AllocationOperatorKind { New, Delete };
16481
16482static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
16483 const FunctionDecl *FD,
16484 bool *WasMalformed) {
16485 const Decl *MalformedDecl = nullptr;
16486 if (FD->getNumParams() > 0 &&
16487 SemaRef.isStdTypeIdentity(Ty: FD->getParamDecl(i: 0)->getType(),
16488 /*TypeArgument=*/Element: nullptr, MalformedDecl: &MalformedDecl))
16489 return true;
16490
16491 if (!MalformedDecl)
16492 return false;
16493
16494 if (WasMalformed)
16495 *WasMalformed = true;
16496
16497 return true;
16498}
16499
16500static bool isDestroyingDeleteT(QualType Type) {
16501 auto *RD = Type->getAsCXXRecordDecl();
16502 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16503 RD->getIdentifier()->isStr(Str: "destroying_delete_t");
16504}
16505
16506static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
16507 const FunctionDecl *FD) {
16508 // C++ P0722:
16509 // Within a class C, a single object deallocation function with signature
16510 // (T, std::destroying_delete_t, <more params>)
16511 // is a destroying operator delete.
16512 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16513 SemaRef, FD, /*WasMalformed=*/nullptr);
16514 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16515 return isa<CXXMethodDecl>(Val: FD) && FD->getOverloadedOperator() == OO_Delete &&
16516 FD->getNumParams() > DestroyingDeleteIdx &&
16517 isDestroyingDeleteT(Type: FD->getParamDecl(i: DestroyingDeleteIdx)->getType());
16518}
16519
16520static inline bool CheckOperatorNewDeleteTypes(
16521 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16522 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16523 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16524 auto NormalizeType = [&SemaRef](QualType T) {
16525 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16526 // The operator is valid on any address space for OpenCL.
16527 // Drop address space from actual and expected result types.
16528 if (const auto PtrTy = T->template getAs<PointerType>())
16529 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16530 }
16531 return SemaRef.Context.getCanonicalType(T);
16532 };
16533
16534 const unsigned NumParams = FnDecl->getNumParams();
16535 unsigned FirstNonTypeParam = 0;
16536 bool MalformedTypeIdentity = false;
16537 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16538 SemaRef, FD: FnDecl, WasMalformed: &MalformedTypeIdentity);
16539 unsigned MinimumMandatoryArgumentCount = 1;
16540 unsigned SizeParameterIndex = 0;
16541 if (IsPotentiallyTypeAware) {
16542 // We don't emit this diagnosis for template instantiations as we will
16543 // have already emitted it for the original template declaration.
16544 if (!FnDecl->isTemplateInstantiation()) {
16545 unsigned DiagID = SemaRef.getLangOpts().CPlusPlus26
16546 ? diag::warn_cxx26_type_aware_allocators
16547 : diag::ext_cxx26_type_aware_allocators;
16548 SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID);
16549 }
16550
16551 if (OperatorKind == AllocationOperatorKind::New) {
16552 SizeParameterIndex = 1;
16553 MinimumMandatoryArgumentCount =
16554 FunctionDecl::RequiredTypeAwareNewParameterCount;
16555 } else {
16556 SizeParameterIndex = 2;
16557 MinimumMandatoryArgumentCount =
16558 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16559 }
16560 FirstNonTypeParam = 1;
16561 }
16562
16563 bool IsPotentiallyDestroyingDelete =
16564 IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: FnDecl);
16565
16566 if (IsPotentiallyDestroyingDelete) {
16567 ++MinimumMandatoryArgumentCount;
16568 ++SizeParameterIndex;
16569 }
16570
16571 if (NumParams < MinimumMandatoryArgumentCount)
16572 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16573 DiagID: diag::err_operator_new_delete_too_few_parameters)
16574 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16575 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16576
16577 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16578 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: Idx);
16579 if (ParamDecl->hasDefaultArg())
16580 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16581 DiagID: diag::err_operator_new_default_arg)
16582 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16583 }
16584
16585 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16586 QualType CanResultType = NormalizeType(FnType->getReturnType());
16587 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16588 QualType CanExpectedSizeOrAddressParamType =
16589 NormalizeType(ExpectedSizeOrAddressParamType);
16590
16591 // Check that the result type is what we expect.
16592 if (CanResultType != CanExpectedResultType) {
16593 // Reject even if the type is dependent; an operator delete function is
16594 // required to have a non-dependent result type.
16595 return SemaRef.Diag(
16596 Loc: FnDecl->getLocation(),
16597 DiagID: CanResultType->isDependentType()
16598 ? diag::err_operator_new_delete_dependent_result_type
16599 : diag::err_operator_new_delete_invalid_result_type)
16600 << FnDecl->getDeclName() << ExpectedResultType;
16601 }
16602
16603 // A function template must have at least 2 parameters.
16604 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16605 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16606 DiagID: diag::err_operator_new_delete_template_too_few_parameters)
16607 << FnDecl->getDeclName();
16608
16609 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16610 auto FallbackType) -> bool {
16611 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: ParamIdx);
16612 if (ExpectedType.isNull()) {
16613 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: InvalidParamTypeDiag)
16614 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16615 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16616 << ParamDecl->getSourceRange();
16617 }
16618 CanQualType CanExpectedTy =
16619 NormalizeType(SemaRef.Context.getCanonicalType(T: ExpectedType));
16620 auto ActualParamType =
16621 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16622 if (ActualParamType == CanExpectedTy)
16623 return false;
16624 unsigned Diagnostic = ActualParamType->isDependentType()
16625 ? DependentParamTypeDiag
16626 : InvalidParamTypeDiag;
16627 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: Diagnostic)
16628 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16629 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16630 << FallbackType << ParamDecl->getSourceRange();
16631 };
16632
16633 // Check that the first parameter type is what we expect.
16634 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16635 return true;
16636
16637 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16638
16639 // If the first parameter type is not a type-identity we're done, otherwise
16640 // we need to ensure the size and alignment parameters have the correct type
16641 if (!IsPotentiallyTypeAware)
16642 return false;
16643
16644 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16645 return true;
16646 TypeDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16647 QualType StdAlignValT =
16648 StdAlignValTDecl ? SemaRef.Context.getTypeDeclType(Decl: StdAlignValTDecl)
16649 : QualType();
16650 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16651 return true;
16652
16653 FnDecl->setIsTypeAwareOperatorNewOrDelete();
16654 return MalformedTypeIdentity;
16655}
16656
16657static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16658 // C++ [basic.stc.dynamic.allocation]p1:
16659 // A program is ill-formed if an allocation function is declared in a
16660 // namespace scope other than global scope or declared static in global
16661 // scope.
16662 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16663 return true;
16664
16665 CanQualType SizeTy =
16666 SemaRef.Context.getCanonicalType(T: SemaRef.Context.getSizeType());
16667
16668 // C++ [basic.stc.dynamic.allocation]p1:
16669 // The return type shall be void*. The first parameter shall have type
16670 // std::size_t.
16671 return CheckOperatorNewDeleteTypes(
16672 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::New, ExpectedResultType: SemaRef.Context.VoidPtrTy,
16673 ExpectedSizeOrAddressParamType: SizeTy, DependentParamTypeDiag: diag::err_operator_new_dependent_param_type,
16674 InvalidParamTypeDiag: diag::err_operator_new_param_type);
16675}
16676
16677static bool
16678CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16679 // C++ [basic.stc.dynamic.deallocation]p1:
16680 // A program is ill-formed if deallocation functions are declared in a
16681 // namespace scope other than global scope or declared static in global
16682 // scope.
16683 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16684 return true;
16685
16686 auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl);
16687 auto ConstructDestroyingDeleteAddressType = [&]() {
16688 assert(MD);
16689 return SemaRef.Context.getCanonicalType(T: SemaRef.Context.getPointerType(
16690 T: SemaRef.Context.getRecordType(Decl: MD->getParent())));
16691 };
16692
16693 // C++ P2719: A destroying operator delete cannot be type aware
16694 // so for QoL we actually check for this explicitly by considering
16695 // an destroying-delete appropriate address type and the presence of
16696 // any parameter of type destroying_delete_t as an erroneous attempt
16697 // to declare a type aware destroying delete, rather than emitting a
16698 // pile of incorrect parameter type errors.
16699 if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(
16700 SemaRef, FD: MD, /*WasMalformed=*/nullptr)) {
16701 QualType AddressParamType =
16702 SemaRef.Context.getCanonicalType(T: MD->getParamDecl(i: 1)->getType());
16703 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16704 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16705 // The address parameter type implies an author trying to construct a
16706 // type aware destroying delete, so we'll see if we can find a parameter
16707 // of type `std::destroying_delete_t`, and if we find it we'll report
16708 // this as being an attempt at a type aware destroying delete just stop
16709 // here. If we don't do this, the resulting incorrect parameter ordering
16710 // results in a pile mismatched argument type errors that don't explain
16711 // the core problem.
16712 for (auto Param : MD->parameters()) {
16713 if (isDestroyingDeleteT(Type: Param->getType())) {
16714 SemaRef.Diag(Loc: MD->getLocation(),
16715 DiagID: diag::err_type_aware_destroying_operator_delete)
16716 << Param->getSourceRange();
16717 return true;
16718 }
16719 }
16720 }
16721 }
16722
16723 // C++ P0722:
16724 // Within a class C, the first parameter of a destroying operator delete
16725 // shall be of type C *. The first parameter of any other deallocation
16726 // function shall be of type void *.
16727 CanQualType ExpectedAddressParamType =
16728 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: MD)
16729 ? SemaRef.Context.getCanonicalType(T: SemaRef.Context.getPointerType(
16730 T: SemaRef.Context.getRecordType(Decl: MD->getParent())))
16731 : SemaRef.Context.VoidPtrTy;
16732
16733 // C++ [basic.stc.dynamic.deallocation]p2:
16734 // Each deallocation function shall return void
16735 if (CheckOperatorNewDeleteTypes(
16736 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::Delete,
16737 ExpectedResultType: SemaRef.Context.VoidTy, ExpectedSizeOrAddressParamType: ExpectedAddressParamType,
16738 DependentParamTypeDiag: diag::err_operator_delete_dependent_param_type,
16739 InvalidParamTypeDiag: diag::err_operator_delete_param_type))
16740 return true;
16741
16742 // C++ P0722:
16743 // A destroying operator delete shall be a usual deallocation function.
16744 if (MD && !MD->getParent()->isDependentContext() &&
16745 MD->isDestroyingOperatorDelete()) {
16746 if (!SemaRef.isUsualDeallocationFunction(FD: MD)) {
16747 SemaRef.Diag(Loc: MD->getLocation(),
16748 DiagID: diag::err_destroying_operator_delete_not_usual);
16749 return true;
16750 }
16751 }
16752
16753 return false;
16754}
16755
16756bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16757 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16758 "Expected an overloaded operator declaration");
16759
16760 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16761
16762 // C++ [over.oper]p5:
16763 // The allocation and deallocation functions, operator new,
16764 // operator new[], operator delete and operator delete[], are
16765 // described completely in 3.7.3. The attributes and restrictions
16766 // found in the rest of this subclause do not apply to them unless
16767 // explicitly stated in 3.7.3.
16768 if (Op == OO_Delete || Op == OO_Array_Delete)
16769 return CheckOperatorDeleteDeclaration(SemaRef&: *this, FnDecl);
16770
16771 if (Op == OO_New || Op == OO_Array_New)
16772 return CheckOperatorNewDeclaration(SemaRef&: *this, FnDecl);
16773
16774 // C++ [over.oper]p7:
16775 // An operator function shall either be a member function or
16776 // be a non-member function and have at least one parameter
16777 // whose type is a class, a reference to a class, an enumeration,
16778 // or a reference to an enumeration.
16779 // Note: Before C++23, a member function could not be static. The only member
16780 // function allowed to be static is the call operator function.
16781 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
16782 if (MethodDecl->isStatic()) {
16783 if (Op == OO_Call || Op == OO_Subscript)
16784 Diag(Loc: FnDecl->getLocation(),
16785 DiagID: (LangOpts.CPlusPlus23
16786 ? diag::warn_cxx20_compat_operator_overload_static
16787 : diag::ext_operator_overload_static))
16788 << FnDecl;
16789 else
16790 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_static)
16791 << FnDecl;
16792 }
16793 } else {
16794 bool ClassOrEnumParam = false;
16795 for (auto *Param : FnDecl->parameters()) {
16796 QualType ParamType = Param->getType().getNonReferenceType();
16797 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16798 ParamType->isEnumeralType()) {
16799 ClassOrEnumParam = true;
16800 break;
16801 }
16802 }
16803
16804 if (!ClassOrEnumParam)
16805 return Diag(Loc: FnDecl->getLocation(),
16806 DiagID: diag::err_operator_overload_needs_class_or_enum)
16807 << FnDecl->getDeclName();
16808 }
16809
16810 // C++ [over.oper]p8:
16811 // An operator function cannot have default arguments (8.3.6),
16812 // except where explicitly stated below.
16813 //
16814 // Only the function-call operator (C++ [over.call]p1) and the subscript
16815 // operator (CWG2507) allow default arguments.
16816 if (Op != OO_Call) {
16817 ParmVarDecl *FirstDefaultedParam = nullptr;
16818 for (auto *Param : FnDecl->parameters()) {
16819 if (Param->hasDefaultArg()) {
16820 FirstDefaultedParam = Param;
16821 break;
16822 }
16823 }
16824 if (FirstDefaultedParam) {
16825 if (Op == OO_Subscript) {
16826 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
16827 ? diag::ext_subscript_overload
16828 : diag::error_subscript_overload)
16829 << FnDecl->getDeclName() << 1
16830 << FirstDefaultedParam->getDefaultArgRange();
16831 } else {
16832 return Diag(Loc: FirstDefaultedParam->getLocation(),
16833 DiagID: diag::err_operator_overload_default_arg)
16834 << FnDecl->getDeclName()
16835 << FirstDefaultedParam->getDefaultArgRange();
16836 }
16837 }
16838 }
16839
16840 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16841 { false, false, false }
16842#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16843 , { Unary, Binary, MemberOnly }
16844#include "clang/Basic/OperatorKinds.def"
16845 };
16846
16847 bool CanBeUnaryOperator = OperatorUses[Op][0];
16848 bool CanBeBinaryOperator = OperatorUses[Op][1];
16849 bool MustBeMemberOperator = OperatorUses[Op][2];
16850
16851 // C++ [over.oper]p8:
16852 // [...] Operator functions cannot have more or fewer parameters
16853 // than the number required for the corresponding operator, as
16854 // described in the rest of this subclause.
16855 unsigned NumParams = FnDecl->getNumParams() +
16856 (isa<CXXMethodDecl>(Val: FnDecl) &&
16857 !FnDecl->hasCXXExplicitFunctionObjectParameter()
16858 ? 1
16859 : 0);
16860 if (Op != OO_Call && Op != OO_Subscript &&
16861 ((NumParams == 1 && !CanBeUnaryOperator) ||
16862 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16863 (NumParams > 2))) {
16864 // We have the wrong number of parameters.
16865 unsigned ErrorKind;
16866 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16867 ErrorKind = 2; // 2 -> unary or binary.
16868 } else if (CanBeUnaryOperator) {
16869 ErrorKind = 0; // 0 -> unary
16870 } else {
16871 assert(CanBeBinaryOperator &&
16872 "All non-call overloaded operators are unary or binary!");
16873 ErrorKind = 1; // 1 -> binary
16874 }
16875 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_must_be)
16876 << FnDecl->getDeclName() << NumParams << ErrorKind;
16877 }
16878
16879 if (Op == OO_Subscript && NumParams != 2) {
16880 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
16881 ? diag::ext_subscript_overload
16882 : diag::error_subscript_overload)
16883 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16884 }
16885
16886 // Overloaded operators other than operator() and operator[] cannot be
16887 // variadic.
16888 if (Op != OO_Call &&
16889 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16890 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_variadic)
16891 << FnDecl->getDeclName();
16892 }
16893
16894 // Some operators must be member functions.
16895 if (MustBeMemberOperator && !isa<CXXMethodDecl>(Val: FnDecl)) {
16896 return Diag(Loc: FnDecl->getLocation(),
16897 DiagID: diag::err_operator_overload_must_be_member)
16898 << FnDecl->getDeclName();
16899 }
16900
16901 // C++ [over.inc]p1:
16902 // The user-defined function called operator++ implements the
16903 // prefix and postfix ++ operator. If this function is a member
16904 // function with no parameters, or a non-member function with one
16905 // parameter of class or enumeration type, it defines the prefix
16906 // increment operator ++ for objects of that type. If the function
16907 // is a member function with one parameter (which shall be of type
16908 // int) or a non-member function with two parameters (the second
16909 // of which shall be of type int), it defines the postfix
16910 // increment operator ++ for objects of that type.
16911 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16912 ParmVarDecl *LastParam = FnDecl->getParamDecl(i: FnDecl->getNumParams() - 1);
16913 QualType ParamType = LastParam->getType();
16914
16915 if (!ParamType->isSpecificBuiltinType(K: BuiltinType::Int) &&
16916 !ParamType->isDependentType())
16917 return Diag(Loc: LastParam->getLocation(),
16918 DiagID: diag::err_operator_overload_post_incdec_must_be_int)
16919 << LastParam->getType() << (Op == OO_MinusMinus);
16920 }
16921
16922 return false;
16923}
16924
16925static bool
16926checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16927 FunctionTemplateDecl *TpDecl) {
16928 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16929
16930 // Must have one or two template parameters.
16931 if (TemplateParams->size() == 1) {
16932 NonTypeTemplateParmDecl *PmDecl =
16933 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 0));
16934
16935 // The template parameter must be a char parameter pack.
16936 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16937 SemaRef.Context.hasSameType(T1: PmDecl->getType(), T2: SemaRef.Context.CharTy))
16938 return false;
16939
16940 // C++20 [over.literal]p5:
16941 // A string literal operator template is a literal operator template
16942 // whose template-parameter-list comprises a single non-type
16943 // template-parameter of class type.
16944 //
16945 // As a DR resolution, we also allow placeholders for deduced class
16946 // template specializations.
16947 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16948 !PmDecl->isTemplateParameterPack() &&
16949 (PmDecl->getType()->isRecordType() ||
16950 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16951 return false;
16952 } else if (TemplateParams->size() == 2) {
16953 TemplateTypeParmDecl *PmType =
16954 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: 0));
16955 NonTypeTemplateParmDecl *PmArgs =
16956 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 1));
16957
16958 // The second template parameter must be a parameter pack with the
16959 // first template parameter as its type.
16960 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16961 PmArgs->isTemplateParameterPack()) {
16962 const TemplateTypeParmType *TArgs =
16963 PmArgs->getType()->getAs<TemplateTypeParmType>();
16964 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16965 TArgs->getIndex() == PmType->getIndex()) {
16966 if (!SemaRef.inTemplateInstantiation())
16967 SemaRef.Diag(Loc: TpDecl->getLocation(),
16968 DiagID: diag::ext_string_literal_operator_template);
16969 return false;
16970 }
16971 }
16972 }
16973
16974 SemaRef.Diag(Loc: TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16975 DiagID: diag::err_literal_operator_template)
16976 << TpDecl->getTemplateParameters()->getSourceRange();
16977 return true;
16978}
16979
16980bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16981 if (isa<CXXMethodDecl>(Val: FnDecl)) {
16982 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_outside_namespace)
16983 << FnDecl->getDeclName();
16984 return true;
16985 }
16986
16987 if (FnDecl->isExternC()) {
16988 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_extern_c);
16989 if (const LinkageSpecDecl *LSD =
16990 FnDecl->getDeclContext()->getExternCContext())
16991 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
16992 return true;
16993 }
16994
16995 // This might be the definition of a literal operator template.
16996 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16997
16998 // This might be a specialization of a literal operator template.
16999 if (!TpDecl)
17000 TpDecl = FnDecl->getPrimaryTemplate();
17001
17002 // template <char...> type operator "" name() and
17003 // template <class T, T...> type operator "" name() are the only valid
17004 // template signatures, and the only valid signatures with no parameters.
17005 //
17006 // C++20 also allows template <SomeClass T> type operator "" name().
17007 if (TpDecl) {
17008 if (FnDecl->param_size() != 0) {
17009 Diag(Loc: FnDecl->getLocation(),
17010 DiagID: diag::err_literal_operator_template_with_params);
17011 return true;
17012 }
17013
17014 if (checkLiteralOperatorTemplateParameterList(SemaRef&: *this, TpDecl))
17015 return true;
17016
17017 } else if (FnDecl->param_size() == 1) {
17018 const ParmVarDecl *Param = FnDecl->getParamDecl(i: 0);
17019
17020 QualType ParamType = Param->getType().getUnqualifiedType();
17021
17022 // Only unsigned long long int, long double, any character type, and const
17023 // char * are allowed as the only parameters.
17024 if (ParamType->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
17025 ParamType->isSpecificBuiltinType(K: BuiltinType::LongDouble) ||
17026 Context.hasSameType(T1: ParamType, T2: Context.CharTy) ||
17027 Context.hasSameType(T1: ParamType, T2: Context.WideCharTy) ||
17028 Context.hasSameType(T1: ParamType, T2: Context.Char8Ty) ||
17029 Context.hasSameType(T1: ParamType, T2: Context.Char16Ty) ||
17030 Context.hasSameType(T1: ParamType, T2: Context.Char32Ty)) {
17031 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17032 QualType InnerType = Ptr->getPointeeType();
17033
17034 // Pointer parameter must be a const char *.
17035 if (!(Context.hasSameType(T1: InnerType.getUnqualifiedType(),
17036 T2: Context.CharTy) &&
17037 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17038 Diag(Loc: Param->getSourceRange().getBegin(),
17039 DiagID: diag::err_literal_operator_param)
17040 << ParamType << "'const char *'" << Param->getSourceRange();
17041 return true;
17042 }
17043
17044 } else if (ParamType->isRealFloatingType()) {
17045 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17046 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17047 return true;
17048
17049 } else if (ParamType->isIntegerType()) {
17050 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17051 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17052 return true;
17053
17054 } else {
17055 Diag(Loc: Param->getSourceRange().getBegin(),
17056 DiagID: diag::err_literal_operator_invalid_param)
17057 << ParamType << Param->getSourceRange();
17058 return true;
17059 }
17060
17061 } else if (FnDecl->param_size() == 2) {
17062 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17063
17064 // First, verify that the first parameter is correct.
17065
17066 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17067
17068 // Two parameter function must have a pointer to const as a
17069 // first parameter; let's strip those qualifiers.
17070 const PointerType *PT = FirstParamType->getAs<PointerType>();
17071
17072 if (!PT) {
17073 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17074 DiagID: diag::err_literal_operator_param)
17075 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17076 return true;
17077 }
17078
17079 QualType PointeeType = PT->getPointeeType();
17080 // First parameter must be const
17081 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17082 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17083 DiagID: diag::err_literal_operator_param)
17084 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17085 return true;
17086 }
17087
17088 QualType InnerType = PointeeType.getUnqualifiedType();
17089 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17090 // const char32_t* are allowed as the first parameter to a two-parameter
17091 // function
17092 if (!(Context.hasSameType(T1: InnerType, T2: Context.CharTy) ||
17093 Context.hasSameType(T1: InnerType, T2: Context.WideCharTy) ||
17094 Context.hasSameType(T1: InnerType, T2: Context.Char8Ty) ||
17095 Context.hasSameType(T1: InnerType, T2: Context.Char16Ty) ||
17096 Context.hasSameType(T1: InnerType, T2: Context.Char32Ty))) {
17097 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17098 DiagID: diag::err_literal_operator_param)
17099 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17100 return true;
17101 }
17102
17103 // Move on to the second and final parameter.
17104 ++Param;
17105
17106 // The second parameter must be a std::size_t.
17107 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17108 if (!Context.hasSameType(T1: SecondParamType, T2: Context.getSizeType())) {
17109 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17110 DiagID: diag::err_literal_operator_param)
17111 << SecondParamType << Context.getSizeType()
17112 << (*Param)->getSourceRange();
17113 return true;
17114 }
17115 } else {
17116 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_bad_param_count);
17117 return true;
17118 }
17119
17120 // Parameters are good.
17121
17122 // A parameter-declaration-clause containing a default argument is not
17123 // equivalent to any of the permitted forms.
17124 for (auto *Param : FnDecl->parameters()) {
17125 if (Param->hasDefaultArg()) {
17126 Diag(Loc: Param->getDefaultArgRange().getBegin(),
17127 DiagID: diag::err_literal_operator_default_argument)
17128 << Param->getDefaultArgRange();
17129 break;
17130 }
17131 }
17132
17133 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17134 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
17135 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
17136 !getSourceManager().isInSystemHeader(Loc: FnDecl->getLocation())) {
17137 // C++23 [usrlit.suffix]p1:
17138 // Literal suffix identifiers that do not start with an underscore are
17139 // reserved for future standardization. Literal suffix identifiers that
17140 // contain a double underscore __ are reserved for use by C++
17141 // implementations.
17142 Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_user_literal_reserved)
17143 << static_cast<int>(Status)
17144 << StringLiteralParser::isValidUDSuffix(LangOpts: getLangOpts(), Suffix: II->getName());
17145 }
17146
17147 return false;
17148}
17149
17150Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
17151 Expr *LangStr,
17152 SourceLocation LBraceLoc) {
17153 StringLiteral *Lit = cast<StringLiteral>(Val: LangStr);
17154 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17155
17156 StringRef Lang = Lit->getString();
17157 LinkageSpecLanguageIDs Language;
17158 if (Lang == "C")
17159 Language = LinkageSpecLanguageIDs::C;
17160 else if (Lang == "C++")
17161 Language = LinkageSpecLanguageIDs::CXX;
17162 else {
17163 Diag(Loc: LangStr->getExprLoc(), DiagID: diag::err_language_linkage_spec_unknown)
17164 << LangStr->getSourceRange();
17165 return nullptr;
17166 }
17167
17168 // FIXME: Add all the various semantics of linkage specifications
17169
17170 LinkageSpecDecl *D = LinkageSpecDecl::Create(C&: Context, DC: CurContext, ExternLoc,
17171 LangLoc: LangStr->getExprLoc(), Lang: Language,
17172 HasBraces: LBraceLoc.isValid());
17173
17174 /// C++ [module.unit]p7.2.3
17175 /// - Otherwise, if the declaration
17176 /// - ...
17177 /// - ...
17178 /// - appears within a linkage-specification,
17179 /// it is attached to the global module.
17180 ///
17181 /// If the declaration is already in global module fragment, we don't
17182 /// need to attach it again.
17183 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17184 Module *GlobalModule = PushImplicitGlobalModuleFragment(BeginLoc: ExternLoc);
17185 D->setLocalOwningModule(GlobalModule);
17186 }
17187
17188 CurContext->addDecl(D);
17189 PushDeclContext(S, DC: D);
17190 return D;
17191}
17192
17193Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
17194 Decl *LinkageSpec,
17195 SourceLocation RBraceLoc) {
17196 if (RBraceLoc.isValid()) {
17197 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(Val: LinkageSpec);
17198 LSDecl->setRBraceLoc(RBraceLoc);
17199 }
17200
17201 // If the current module doesn't has Parent, it implies that the
17202 // LinkageSpec isn't in the module created by itself. So we don't
17203 // need to pop it.
17204 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17205 getCurrentModule()->isImplicitGlobalModule() &&
17206 getCurrentModule()->Parent)
17207 PopImplicitGlobalModuleFragment();
17208
17209 PopDeclContext();
17210 return LinkageSpec;
17211}
17212
17213Decl *Sema::ActOnEmptyDeclaration(Scope *S,
17214 const ParsedAttributesView &AttrList,
17215 SourceLocation SemiLoc) {
17216 Decl *ED = EmptyDecl::Create(C&: Context, DC: CurContext, L: SemiLoc);
17217 // Attribute declarations appertain to empty declaration so we handle
17218 // them here.
17219 ProcessDeclAttributeList(S, D: ED, AttrList);
17220
17221 CurContext->addDecl(D: ED);
17222 return ED;
17223}
17224
17225VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
17226 SourceLocation StartLoc,
17227 SourceLocation Loc,
17228 const IdentifierInfo *Name) {
17229 bool Invalid = false;
17230 QualType ExDeclType = TInfo->getType();
17231
17232 // Arrays and functions decay.
17233 if (ExDeclType->isArrayType())
17234 ExDeclType = Context.getArrayDecayedType(T: ExDeclType);
17235 else if (ExDeclType->isFunctionType())
17236 ExDeclType = Context.getPointerType(T: ExDeclType);
17237
17238 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17239 // The exception-declaration shall not denote a pointer or reference to an
17240 // incomplete type, other than [cv] void*.
17241 // N2844 forbids rvalue references.
17242 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17243 Diag(Loc, DiagID: diag::err_catch_rvalue_ref);
17244 Invalid = true;
17245 }
17246
17247 if (ExDeclType->isVariablyModifiedType()) {
17248 Diag(Loc, DiagID: diag::err_catch_variably_modified) << ExDeclType;
17249 Invalid = true;
17250 }
17251
17252 QualType BaseType = ExDeclType;
17253 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17254 unsigned DK = diag::err_catch_incomplete;
17255 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17256 BaseType = Ptr->getPointeeType();
17257 Mode = 1;
17258 DK = diag::err_catch_incomplete_ptr;
17259 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17260 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17261 BaseType = Ref->getPointeeType();
17262 Mode = 2;
17263 DK = diag::err_catch_incomplete_ref;
17264 }
17265 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17266 !BaseType->isDependentType() && RequireCompleteType(Loc, T: BaseType, DiagID: DK))
17267 Invalid = true;
17268
17269 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17270 Diag(Loc, DiagID: diag::err_wasm_reftype_tc) << 1;
17271 Invalid = true;
17272 }
17273
17274 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17275 Diag(Loc, DiagID: diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17276 Invalid = true;
17277 }
17278
17279 if (!Invalid && !ExDeclType->isDependentType() &&
17280 RequireNonAbstractType(Loc, T: ExDeclType,
17281 DiagID: diag::err_abstract_type_in_decl,
17282 Args: AbstractVariableType))
17283 Invalid = true;
17284
17285 // Only the non-fragile NeXT runtime currently supports C++ catches
17286 // of ObjC types, and no runtime supports catching ObjC types by value.
17287 if (!Invalid && getLangOpts().ObjC) {
17288 QualType T = ExDeclType;
17289 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17290 T = RT->getPointeeType();
17291
17292 if (T->isObjCObjectType()) {
17293 Diag(Loc, DiagID: diag::err_objc_object_catch);
17294 Invalid = true;
17295 } else if (T->isObjCObjectPointerType()) {
17296 // FIXME: should this be a test for macosx-fragile specifically?
17297 if (getLangOpts().ObjCRuntime.isFragile())
17298 Diag(Loc, DiagID: diag::warn_objc_pointer_cxx_catch_fragile);
17299 }
17300 }
17301
17302 VarDecl *ExDecl = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: Loc, Id: Name,
17303 T: ExDeclType, TInfo, S: SC_None);
17304 ExDecl->setExceptionVariable(true);
17305
17306 // In ARC, infer 'retaining' for variables of retainable type.
17307 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: ExDecl))
17308 Invalid = true;
17309
17310 if (!Invalid && !ExDeclType->isDependentType()) {
17311 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
17312 // Insulate this from anything else we might currently be parsing.
17313 EnterExpressionEvaluationContext scope(
17314 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17315
17316 // C++ [except.handle]p16:
17317 // The object declared in an exception-declaration or, if the
17318 // exception-declaration does not specify a name, a temporary (12.2) is
17319 // copy-initialized (8.5) from the exception object. [...]
17320 // The object is destroyed when the handler exits, after the destruction
17321 // of any automatic objects initialized within the handler.
17322 //
17323 // We just pretend to initialize the object with itself, then make sure
17324 // it can be destroyed later.
17325 QualType initType = Context.getExceptionObjectType(T: ExDeclType);
17326
17327 InitializedEntity entity =
17328 InitializedEntity::InitializeVariable(Var: ExDecl);
17329 InitializationKind initKind =
17330 InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation());
17331
17332 Expr *opaqueValue =
17333 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17334 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17335 ExprResult result = sequence.Perform(S&: *this, Entity: entity, Kind: initKind, Args: opaqueValue);
17336 if (result.isInvalid())
17337 Invalid = true;
17338 else {
17339 // If the constructor used was non-trivial, set this as the
17340 // "initializer".
17341 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17342 if (!construct->getConstructor()->isTrivial()) {
17343 Expr *init = MaybeCreateExprWithCleanups(SubExpr: construct);
17344 ExDecl->setInit(init);
17345 }
17346
17347 // And make sure it's destructable.
17348 FinalizeVarWithDestructor(VD: ExDecl, Record: recordType);
17349 }
17350 }
17351 }
17352
17353 if (Invalid)
17354 ExDecl->setInvalidDecl();
17355
17356 return ExDecl;
17357}
17358
17359Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17360 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17361 bool Invalid = D.isInvalidType();
17362
17363 // Check for unexpanded parameter packs.
17364 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
17365 UPPC: UPPC_ExceptionType)) {
17366 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
17367 Loc: D.getIdentifierLoc());
17368 Invalid = true;
17369 }
17370
17371 const IdentifierInfo *II = D.getIdentifier();
17372 if (NamedDecl *PrevDecl =
17373 LookupSingleName(S, Name: II, Loc: D.getIdentifierLoc(), NameKind: LookupOrdinaryName,
17374 Redecl: RedeclarationKind::ForVisibleRedeclaration)) {
17375 // The scope should be freshly made just for us. There is just no way
17376 // it contains any previous declaration, except for function parameters in
17377 // a function-try-block's catch statement.
17378 assert(!S->isDeclScope(PrevDecl));
17379 if (isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
17380 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_redefinition)
17381 << D.getIdentifier();
17382 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
17383 Invalid = true;
17384 } else if (PrevDecl->isTemplateParameter())
17385 // Maybe we will complain about the shadowed template parameter.
17386 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
17387 }
17388
17389 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17390 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_catch_declarator)
17391 << D.getCXXScopeSpec().getRange();
17392 Invalid = true;
17393 }
17394
17395 VarDecl *ExDecl = BuildExceptionDeclaration(
17396 S, TInfo, StartLoc: D.getBeginLoc(), Loc: D.getIdentifierLoc(), Name: D.getIdentifier());
17397 if (Invalid)
17398 ExDecl->setInvalidDecl();
17399
17400 // Add the exception declaration into this scope.
17401 if (II)
17402 PushOnScopeChains(D: ExDecl, S);
17403 else
17404 CurContext->addDecl(D: ExDecl);
17405
17406 ProcessDeclAttributes(S, D: ExDecl, PD: D);
17407 return ExDecl;
17408}
17409
17410Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17411 Expr *AssertExpr,
17412 Expr *AssertMessageExpr,
17413 SourceLocation RParenLoc) {
17414 if (DiagnoseUnexpandedParameterPack(E: AssertExpr, UPPC: UPPC_StaticAssertExpression))
17415 return nullptr;
17416
17417 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17418 AssertMessageExpr, RParenLoc, Failed: false);
17419}
17420
17421static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17422 switch (BTK) {
17423 case BuiltinType::Char_S:
17424 case BuiltinType::Char_U:
17425 break;
17426 case BuiltinType::Char8:
17427 OS << "u8";
17428 break;
17429 case BuiltinType::Char16:
17430 OS << 'u';
17431 break;
17432 case BuiltinType::Char32:
17433 OS << 'U';
17434 break;
17435 case BuiltinType::WChar_S:
17436 case BuiltinType::WChar_U:
17437 OS << 'L';
17438 break;
17439 default:
17440 llvm_unreachable("Non-character type");
17441 }
17442}
17443
17444/// Convert character's value, interpreted as a code unit, to a string.
17445/// The value needs to be zero-extended to 32-bits.
17446/// FIXME: This assumes Unicode literal encodings
17447static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17448 unsigned TyWidth,
17449 SmallVectorImpl<char> &Str) {
17450 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17451 char *Ptr = Arr;
17452 BuiltinType::Kind K = BTy->getKind();
17453 llvm::raw_svector_ostream OS(Str);
17454
17455 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17456 // other types.
17457 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17458 K == BuiltinType::Char8 || Value <= 0x7F) {
17459 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Value);
17460 if (!Escaped.empty())
17461 EscapeStringForDiagnostic(Str: Escaped, OutStr&: Str);
17462 else
17463 OS << static_cast<char>(Value);
17464 return;
17465 }
17466
17467 switch (K) {
17468 case BuiltinType::Char16:
17469 case BuiltinType::Char32:
17470 case BuiltinType::WChar_S:
17471 case BuiltinType::WChar_U: {
17472 if (llvm::ConvertCodePointToUTF8(Source: Value, ResultPtr&: Ptr))
17473 EscapeStringForDiagnostic(Str: StringRef(Arr, Ptr - Arr), OutStr&: Str);
17474 else
17475 OS << "\\x"
17476 << llvm::format_hex_no_prefix(N: Value, Width: TyWidth / 4, /*Upper=*/true);
17477 break;
17478 }
17479 default:
17480 llvm_unreachable("Non-character type is passed");
17481 }
17482}
17483
17484/// Convert \V to a string we can present to the user in a diagnostic
17485/// \T is the type of the expression that has been evaluated into \V
17486static bool ConvertAPValueToString(const APValue &V, QualType T,
17487 SmallVectorImpl<char> &Str,
17488 ASTContext &Context) {
17489 if (!V.hasValue())
17490 return false;
17491
17492 switch (V.getKind()) {
17493 case APValue::ValueKind::Int:
17494 if (T->isBooleanType()) {
17495 // Bools are reduced to ints during evaluation, but for
17496 // diagnostic purposes we want to print them as
17497 // true or false.
17498 int64_t BoolValue = V.getInt().getExtValue();
17499 assert((BoolValue == 0 || BoolValue == 1) &&
17500 "Bool type, but value is not 0 or 1");
17501 llvm::raw_svector_ostream OS(Str);
17502 OS << (BoolValue ? "true" : "false");
17503 } else {
17504 llvm::raw_svector_ostream OS(Str);
17505 // Same is true for chars.
17506 // We want to print the character representation for textual types
17507 const auto *BTy = T->getAs<BuiltinType>();
17508 if (BTy) {
17509 switch (BTy->getKind()) {
17510 case BuiltinType::Char_S:
17511 case BuiltinType::Char_U:
17512 case BuiltinType::Char8:
17513 case BuiltinType::Char16:
17514 case BuiltinType::Char32:
17515 case BuiltinType::WChar_S:
17516 case BuiltinType::WChar_U: {
17517 unsigned TyWidth = Context.getIntWidth(T);
17518 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17519 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17520 WriteCharTypePrefix(BTK: BTy->getKind(), OS);
17521 OS << '\'';
17522 WriteCharValueForDiagnostic(Value: CodeUnit, BTy, TyWidth, Str);
17523 OS << "' (0x"
17524 << llvm::format_hex_no_prefix(N: CodeUnit, /*Width=*/2,
17525 /*Upper=*/true)
17526 << ", " << V.getInt() << ')';
17527 return true;
17528 }
17529 default:
17530 break;
17531 }
17532 }
17533 V.getInt().toString(Str);
17534 }
17535
17536 break;
17537
17538 case APValue::ValueKind::Float:
17539 V.getFloat().toString(Str);
17540 break;
17541
17542 case APValue::ValueKind::LValue:
17543 if (V.isNullPointer()) {
17544 llvm::raw_svector_ostream OS(Str);
17545 OS << "nullptr";
17546 } else
17547 return false;
17548 break;
17549
17550 case APValue::ValueKind::ComplexFloat: {
17551 llvm::raw_svector_ostream OS(Str);
17552 OS << '(';
17553 V.getComplexFloatReal().toString(Str);
17554 OS << " + ";
17555 V.getComplexFloatImag().toString(Str);
17556 OS << "i)";
17557 } break;
17558
17559 case APValue::ValueKind::ComplexInt: {
17560 llvm::raw_svector_ostream OS(Str);
17561 OS << '(';
17562 V.getComplexIntReal().toString(Str);
17563 OS << " + ";
17564 V.getComplexIntImag().toString(Str);
17565 OS << "i)";
17566 } break;
17567
17568 default:
17569 return false;
17570 }
17571
17572 return true;
17573}
17574
17575/// Some Expression types are not useful to print notes about,
17576/// e.g. literals and values that have already been expanded
17577/// before such as int-valued template parameters.
17578static bool UsefulToPrintExpr(const Expr *E) {
17579 E = E->IgnoreParenImpCasts();
17580 // Literals are pretty easy for humans to understand.
17581 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17582 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(Val: E))
17583 return false;
17584
17585 // These have been substituted from template parameters
17586 // and appear as literals in the static assert error.
17587 if (isa<SubstNonTypeTemplateParmExpr>(Val: E))
17588 return false;
17589
17590 // -5 is also simple to understand.
17591 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E))
17592 return UsefulToPrintExpr(E: UnaryOp->getSubExpr());
17593
17594 // Only print nested arithmetic operators.
17595 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E))
17596 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17597 BO->isBitwiseOp());
17598
17599 return true;
17600}
17601
17602void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17603 if (const auto *Op = dyn_cast<BinaryOperator>(Val: E);
17604 Op && Op->getOpcode() != BO_LOr) {
17605 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17606 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17607
17608 // Ignore comparisons of boolean expressions with a boolean literal.
17609 if ((isa<CXXBoolLiteralExpr>(Val: LHS) && RHS->getType()->isBooleanType()) ||
17610 (isa<CXXBoolLiteralExpr>(Val: RHS) && LHS->getType()->isBooleanType()))
17611 return;
17612
17613 // Don't print obvious expressions.
17614 if (!UsefulToPrintExpr(E: LHS) && !UsefulToPrintExpr(E: RHS))
17615 return;
17616
17617 struct {
17618 const clang::Expr *Cond;
17619 Expr::EvalResult Result;
17620 SmallString<12> ValueString;
17621 bool Print;
17622 } DiagSide[2] = {{.Cond: LHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false},
17623 {.Cond: RHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}};
17624 for (unsigned I = 0; I < 2; I++) {
17625 const Expr *Side = DiagSide[I].Cond;
17626
17627 Side->EvaluateAsRValue(Result&: DiagSide[I].Result, Ctx: Context, InConstantContext: true);
17628
17629 DiagSide[I].Print =
17630 ConvertAPValueToString(V: DiagSide[I].Result.Val, T: Side->getType(),
17631 Str&: DiagSide[I].ValueString, Context);
17632 }
17633 if (DiagSide[0].Print && DiagSide[1].Print) {
17634 Diag(Loc: Op->getExprLoc(), DiagID: diag::note_expr_evaluates_to)
17635 << DiagSide[0].ValueString << Op->getOpcodeStr()
17636 << DiagSide[1].ValueString << Op->getSourceRange();
17637 }
17638 } else {
17639 DiagnoseTypeTraitDetails(E);
17640 }
17641}
17642
17643template <typename ResultType>
17644static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17645 ResultType &Result, ASTContext &Ctx,
17646 Sema::StringEvaluationContext EvalContext,
17647 bool ErrorOnInvalidMessage) {
17648
17649 assert(Message);
17650 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17651 "can't evaluate a dependant static assert message");
17652
17653 if (const auto *SL = dyn_cast<StringLiteral>(Val: Message)) {
17654 assert(SL->isUnevaluated() && "expected an unevaluated string");
17655 if constexpr (std::is_same_v<APValue, ResultType>) {
17656 Result =
17657 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17658 const ConstantArrayType *CAT =
17659 SemaRef.getASTContext().getAsConstantArrayType(T: SL->getType());
17660 assert(CAT && "string literal isn't an array");
17661 QualType CharType = CAT->getElementType();
17662 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(T: CharType),
17663 CharType->isUnsignedIntegerType());
17664 for (unsigned I = 0; I < SL->getLength(); I++) {
17665 Value = SL->getCodeUnit(i: I);
17666 Result.getArrayInitializedElt(I) = APValue(Value);
17667 }
17668 } else {
17669 Result.assign(SL->getString().begin(), SL->getString().end());
17670 }
17671 return true;
17672 }
17673
17674 SourceLocation Loc = Message->getBeginLoc();
17675 QualType T = Message->getType().getNonReferenceType();
17676 auto *RD = T->getAsCXXRecordDecl();
17677 if (!RD) {
17678 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid) << EvalContext;
17679 return false;
17680 }
17681
17682 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17683 DeclarationName DN = SemaRef.PP.getIdentifierInfo(Name: Member);
17684 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17685 SemaRef.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
17686 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17687 OverloadCandidateSet::CSK_Normal);
17688 if (MemberLookup.empty())
17689 return std::nullopt;
17690 return std::move(MemberLookup);
17691 };
17692
17693 std::optional<LookupResult> SizeMember = FindMember("size");
17694 std::optional<LookupResult> DataMember = FindMember("data");
17695 if (!SizeMember || !DataMember) {
17696 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_missing_member_function)
17697 << EvalContext
17698 << ((!SizeMember && !DataMember) ? 2
17699 : !SizeMember ? 0
17700 : 1);
17701 return false;
17702 }
17703
17704 auto BuildExpr = [&](LookupResult &LR) {
17705 ExprResult Res = SemaRef.BuildMemberReferenceExpr(
17706 Base: Message, BaseType: Message->getType(), OpLoc: Message->getBeginLoc(), IsArrow: false,
17707 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, R&: LR, TemplateArgs: nullptr, S: nullptr);
17708 if (Res.isInvalid())
17709 return ExprError();
17710 Res = SemaRef.BuildCallExpr(S: nullptr, Fn: Res.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr,
17711 IsExecConfig: false, AllowRecovery: true);
17712 if (Res.isInvalid())
17713 return ExprError();
17714 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17715 return ExprError();
17716 return SemaRef.TemporaryMaterializationConversion(E: Res.get());
17717 };
17718
17719 ExprResult SizeE = BuildExpr(*SizeMember);
17720 ExprResult DataE = BuildExpr(*DataMember);
17721
17722 QualType SizeT = SemaRef.Context.getSizeType();
17723 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17724 T: SemaRef.Context.getConstType(T: SemaRef.Context.CharTy));
17725
17726 ExprResult EvaluatedSize =
17727 SizeE.isInvalid()
17728 ? ExprError()
17729 : SemaRef.BuildConvertedConstantExpression(
17730 From: SizeE.get(), T: SizeT, CCE: CCEKind::StaticAssertMessageSize);
17731 if (EvaluatedSize.isInvalid()) {
17732 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17733 << EvalContext << /*size*/ 0;
17734 return false;
17735 }
17736
17737 ExprResult EvaluatedData =
17738 DataE.isInvalid()
17739 ? ExprError()
17740 : SemaRef.BuildConvertedConstantExpression(
17741 From: DataE.get(), T: ConstCharPtr, CCE: CCEKind::StaticAssertMessageData);
17742 if (EvaluatedData.isInvalid()) {
17743 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17744 << EvalContext << /*data*/ 1;
17745 return false;
17746 }
17747
17748 if (!ErrorOnInvalidMessage &&
17749 SemaRef.Diags.isIgnored(DiagID: diag::warn_user_defined_msg_constexpr, Loc))
17750 return true;
17751
17752 Expr::EvalResult Status;
17753 SmallVector<PartialDiagnosticAt, 8> Notes;
17754 Status.Diag = &Notes;
17755 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17756 EvaluatedData.get(), Ctx, Status) ||
17757 !Notes.empty()) {
17758 SemaRef.Diag(Loc: Message->getBeginLoc(),
17759 DiagID: ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17760 : diag::warn_user_defined_msg_constexpr)
17761 << EvalContext;
17762 for (const auto &Note : Notes)
17763 SemaRef.Diag(Loc: Note.first, PD: Note.second);
17764 return !ErrorOnInvalidMessage;
17765 }
17766 return true;
17767}
17768
17769bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
17770 StringEvaluationContext EvalContext,
17771 bool ErrorOnInvalidMessage) {
17772 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
17773 ErrorOnInvalidMessage);
17774}
17775
17776bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17777 StringEvaluationContext EvalContext,
17778 bool ErrorOnInvalidMessage) {
17779 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
17780 ErrorOnInvalidMessage);
17781}
17782
17783Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17784 Expr *AssertExpr, Expr *AssertMessage,
17785 SourceLocation RParenLoc,
17786 bool Failed) {
17787 assert(AssertExpr != nullptr && "Expected non-null condition");
17788 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17789 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17790 !AssertMessage->isValueDependent())) &&
17791 !Failed) {
17792 // In a static_assert-declaration, the constant-expression shall be a
17793 // constant expression that can be contextually converted to bool.
17794 ExprResult Converted = PerformContextuallyConvertToBool(From: AssertExpr);
17795 if (Converted.isInvalid())
17796 Failed = true;
17797
17798 ExprResult FullAssertExpr =
17799 ActOnFinishFullExpr(Expr: Converted.get(), CC: StaticAssertLoc,
17800 /*DiscardedValue*/ false,
17801 /*IsConstexpr*/ true);
17802 if (FullAssertExpr.isInvalid())
17803 Failed = true;
17804 else
17805 AssertExpr = FullAssertExpr.get();
17806
17807 llvm::APSInt Cond;
17808 Expr *BaseExpr = AssertExpr;
17809 AllowFoldKind FoldKind = AllowFoldKind::No;
17810
17811 if (!getLangOpts().CPlusPlus) {
17812 // In C mode, allow folding as an extension for better compatibility with
17813 // C++ in terms of expressions like static_assert("test") or
17814 // static_assert(nullptr).
17815 FoldKind = AllowFoldKind::Allow;
17816 }
17817
17818 if (!Failed && VerifyIntegerConstantExpression(
17819 E: BaseExpr, Result: &Cond,
17820 DiagID: diag::err_static_assert_expression_is_not_constant,
17821 CanFold: FoldKind).isInvalid())
17822 Failed = true;
17823
17824 // If the static_assert passes, only verify that
17825 // the message is grammatically valid without evaluating it.
17826 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17827 std::string Str;
17828 EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
17829 EvalContext: StringEvaluationContext::StaticAssert,
17830 /*ErrorOnInvalidMessage=*/false);
17831 }
17832
17833 // CWG2518
17834 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17835 // template definition, the declaration has no effect.
17836 bool InTemplateDefinition =
17837 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17838
17839 if (!Failed && !Cond && !InTemplateDefinition) {
17840 SmallString<256> MsgBuffer;
17841 llvm::raw_svector_ostream Msg(MsgBuffer);
17842 bool HasMessage = AssertMessage;
17843 if (AssertMessage) {
17844 std::string Str;
17845 HasMessage = EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
17846 EvalContext: StringEvaluationContext::StaticAssert,
17847 /*ErrorOnInvalidMessage=*/true) ||
17848 !Str.empty();
17849 Msg << Str;
17850 }
17851 Expr *InnerCond = nullptr;
17852 std::string InnerCondDescription;
17853 std::tie(args&: InnerCond, args&: InnerCondDescription) =
17854 findFailedBooleanCondition(Cond: Converted.get());
17855 if (const auto *ConceptIDExpr =
17856 dyn_cast_or_null<ConceptSpecializationExpr>(Val: InnerCond)) {
17857 // Drill down into concept specialization expressions to see why they
17858 // weren't satisfied.
17859 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
17860 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17861 ConstraintSatisfaction Satisfaction;
17862 if (!CheckConstraintSatisfaction(ConstraintExpr: ConceptIDExpr, Satisfaction))
17863 DiagnoseUnsatisfiedConstraint(Satisfaction);
17864 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(Val: InnerCond) &&
17865 !isa<IntegerLiteral>(Val: InnerCond)) {
17866 Diag(Loc: InnerCond->getBeginLoc(),
17867 DiagID: diag::err_static_assert_requirement_failed)
17868 << InnerCondDescription << !HasMessage << Msg.str()
17869 << InnerCond->getSourceRange();
17870 DiagnoseStaticAssertDetails(E: InnerCond);
17871 } else {
17872 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
17873 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17874 PrintContextStack();
17875 }
17876 Failed = true;
17877 }
17878 } else {
17879 ExprResult FullAssertExpr = ActOnFinishFullExpr(Expr: AssertExpr, CC: StaticAssertLoc,
17880 /*DiscardedValue*/false,
17881 /*IsConstexpr*/true);
17882 if (FullAssertExpr.isInvalid())
17883 Failed = true;
17884 else
17885 AssertExpr = FullAssertExpr.get();
17886 }
17887
17888 Decl *Decl = StaticAssertDecl::Create(C&: Context, DC: CurContext, StaticAssertLoc,
17889 AssertExpr, Message: AssertMessage, RParenLoc,
17890 Failed);
17891
17892 CurContext->addDecl(D: Decl);
17893 return Decl;
17894}
17895
17896DeclResult Sema::ActOnTemplatedFriendTag(
17897 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17898 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17899 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
17900 MultiTemplateParamsArg TempParamLists) {
17901 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17902
17903 bool IsMemberSpecialization = false;
17904 bool Invalid = false;
17905
17906 if (TemplateParameterList *TemplateParams =
17907 MatchTemplateParametersToScopeSpecifier(
17908 DeclStartLoc: TagLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TempParamLists, /*friend*/ IsFriend: true,
17909 IsMemberSpecialization, Invalid)) {
17910 if (TemplateParams->size() > 0) {
17911 // This is a declaration of a class template.
17912 if (Invalid)
17913 return true;
17914
17915 return CheckClassTemplate(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS,
17916 Name, NameLoc, Attr, TemplateParams, AS: AS_public,
17917 /*ModulePrivateLoc=*/SourceLocation(),
17918 FriendLoc, NumOuterTemplateParamLists: TempParamLists.size() - 1,
17919 OuterTemplateParamLists: TempParamLists.data())
17920 .get();
17921 } else {
17922 // The "template<>" header is extraneous.
17923 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
17924 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17925 IsMemberSpecialization = true;
17926 }
17927 }
17928
17929 if (Invalid) return true;
17930
17931 bool isAllExplicitSpecializations = true;
17932 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17933 if (TempParamLists[I]->size()) {
17934 isAllExplicitSpecializations = false;
17935 break;
17936 }
17937 }
17938
17939 // FIXME: don't ignore attributes.
17940
17941 // If it's explicit specializations all the way down, just forget
17942 // about the template header and build an appropriate non-templated
17943 // friend. TODO: for source fidelity, remember the headers.
17944 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
17945 if (isAllExplicitSpecializations) {
17946 if (SS.isEmpty()) {
17947 bool Owned = false;
17948 bool IsDependent = false;
17949 return ActOnTag(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc,
17950 Attr, AS: AS_public,
17951 /*ModulePrivateLoc=*/SourceLocation(),
17952 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent,
17953 /*ScopedEnumKWLoc=*/SourceLocation(),
17954 /*ScopedEnumUsesClassTag=*/false,
17955 /*UnderlyingType=*/TypeResult(),
17956 /*IsTypeSpecifier=*/false,
17957 /*IsTemplateParamOrArg=*/false,
17958 /*OOK=*/OffsetOfKind::Outside);
17959 }
17960
17961 ElaboratedTypeKeyword Keyword
17962 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
17963 QualType T = CheckTypenameType(Keyword, KeywordLoc: TagLoc, QualifierLoc,
17964 II: *Name, IILoc: NameLoc);
17965 if (T.isNull())
17966 return true;
17967
17968 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17969 if (isa<DependentNameType>(Val: T)) {
17970 DependentNameTypeLoc TL =
17971 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17972 TL.setElaboratedKeywordLoc(TagLoc);
17973 TL.setQualifierLoc(QualifierLoc);
17974 TL.setNameLoc(NameLoc);
17975 } else {
17976 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
17977 TL.setElaboratedKeywordLoc(TagLoc);
17978 TL.setQualifierLoc(QualifierLoc);
17979 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17980 }
17981
17982 FriendDecl *Friend =
17983 FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend_: TSI, FriendL: FriendLoc,
17984 EllipsisLoc, FriendTypeTPLists: TempParamLists);
17985 Friend->setAccess(AS_public);
17986 CurContext->addDecl(D: Friend);
17987 return Friend;
17988 }
17989
17990 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17991
17992 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
17993 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
17994 // shall not have been introduced by the template-declaration.
17995 SmallVector<UnexpandedParameterPack, 1> Unexpanded;
17996 collectUnexpandedParameterPacks(NNS: QualifierLoc, Unexpanded);
17997 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
17998 for (UnexpandedParameterPack &U : Unexpanded) {
17999 if (getDepthAndIndex(UPP: U).first >= FriendDeclDepth) {
18000 auto *ND = dyn_cast<NamedDecl *>(Val&: U.first);
18001 if (!ND)
18002 ND = cast<const TemplateTypeParmType *>(Val&: U.first)->getDecl();
18003 Diag(Loc: U.second, DiagID: diag::friend_template_decl_malformed_pack_expansion)
18004 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18005 return true;
18006 }
18007 }
18008
18009 // Handle the case of a templated-scope friend class. e.g.
18010 // template <class T> class A<T>::B;
18011 // FIXME: we don't support these right now.
18012 Diag(Loc: NameLoc, DiagID: diag::warn_template_qualified_friend_unsupported)
18013 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(Val: CurContext);
18014 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18015 QualType T = Context.getDependentNameType(Keyword: ETK, NNS: SS.getScopeRep(), Name);
18016 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18017 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18018 TL.setElaboratedKeywordLoc(TagLoc);
18019 TL.setQualifierLoc(SS.getWithLocInContext(Context));
18020 TL.setNameLoc(NameLoc);
18021
18022 FriendDecl *Friend =
18023 FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend_: TSI, FriendL: FriendLoc,
18024 EllipsisLoc, FriendTypeTPLists: TempParamLists);
18025 Friend->setAccess(AS_public);
18026 Friend->setUnsupportedFriend(true);
18027 CurContext->addDecl(D: Friend);
18028 return Friend;
18029}
18030
18031Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
18032 MultiTemplateParamsArg TempParams,
18033 SourceLocation EllipsisLoc) {
18034 SourceLocation Loc = DS.getBeginLoc();
18035 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18036
18037 assert(DS.isFriendSpecified());
18038 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18039
18040 // C++ [class.friend]p3:
18041 // A friend declaration that does not declare a function shall have one of
18042 // the following forms:
18043 // friend elaborated-type-specifier ;
18044 // friend simple-type-specifier ;
18045 // friend typename-specifier ;
18046 //
18047 // If the friend keyword isn't first, or if the declarations has any type
18048 // qualifiers, then the declaration doesn't have that form.
18049 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
18050 Diag(Loc: FriendLoc, DiagID: diag::err_friend_not_first_in_declaration);
18051 if (DS.getTypeQualifiers()) {
18052 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
18053 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::err_friend_decl_spec) << "const";
18054 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
18055 Diag(Loc: DS.getVolatileSpecLoc(), DiagID: diag::err_friend_decl_spec) << "volatile";
18056 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
18057 Diag(Loc: DS.getRestrictSpecLoc(), DiagID: diag::err_friend_decl_spec) << "restrict";
18058 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
18059 Diag(Loc: DS.getAtomicSpecLoc(), DiagID: diag::err_friend_decl_spec) << "_Atomic";
18060 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
18061 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID: diag::err_friend_decl_spec) << "__unaligned";
18062 }
18063
18064 // Try to convert the decl specifier to a type. This works for
18065 // friend templates because ActOnTag never produces a ClassTemplateDecl
18066 // for a TagUseKind::Friend.
18067 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18068 DeclaratorContext::Member);
18069 TypeSourceInfo *TSI = GetTypeForDeclarator(D&: TheDeclarator);
18070 QualType T = TSI->getType();
18071 if (TheDeclarator.isInvalidType())
18072 return nullptr;
18073
18074 // If '...' is present, the type must contain an unexpanded parameter
18075 // pack, and vice versa.
18076 bool Invalid = false;
18077 if (EllipsisLoc.isInvalid() &&
18078 DiagnoseUnexpandedParameterPack(Loc, T: TSI, UPPC: UPPC_FriendDeclaration))
18079 return nullptr;
18080 if (EllipsisLoc.isValid() &&
18081 !TSI->getType()->containsUnexpandedParameterPack()) {
18082 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
18083 << TSI->getTypeLoc().getSourceRange();
18084 Invalid = true;
18085 }
18086
18087 if (!T->isElaboratedTypeSpecifier()) {
18088 if (TempParams.size()) {
18089 // C++23 [dcl.pre]p5:
18090 // In a simple-declaration, the optional init-declarator-list can be
18091 // omitted only when declaring a class or enumeration, that is, when
18092 // the decl-specifier-seq contains either a class-specifier, an
18093 // elaborated-type-specifier with a class-key, or an enum-specifier.
18094 //
18095 // The declaration of a template-declaration or explicit-specialization
18096 // is never a member-declaration, so this must be a simple-declaration
18097 // with no init-declarator-list. Therefore, this is ill-formed.
18098 Diag(Loc, DiagID: diag::err_tagless_friend_type_template) << DS.getSourceRange();
18099 return nullptr;
18100 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18101 SmallString<16> InsertionText(" ");
18102 InsertionText += RD->getKindName();
18103
18104 Diag(Loc, DiagID: getLangOpts().CPlusPlus11
18105 ? diag::warn_cxx98_compat_unelaborated_friend_type
18106 : diag::ext_unelaborated_friend_type)
18107 << (unsigned)RD->getTagKind() << T
18108 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: FriendLoc),
18109 Code: InsertionText);
18110 } else {
18111 DiagCompat(Loc: FriendLoc, CompatDiagId: diag_compat::nonclass_type_friend)
18112 << T << DS.getSourceRange();
18113 }
18114 }
18115
18116 // C++98 [class.friend]p1: A friend of a class is a function
18117 // or class that is not a member of the class . . .
18118 // This is fixed in DR77, which just barely didn't make the C++03
18119 // deadline. It's also a very silly restriction that seriously
18120 // affects inner classes and which nobody else seems to implement;
18121 // thus we never diagnose it, not even in -pedantic.
18122 //
18123 // But note that we could warn about it: it's always useless to
18124 // friend one of your own members (it's not, however, worthless to
18125 // friend a member of an arbitrary specialization of your template).
18126
18127 Decl *D;
18128 if (!TempParams.empty())
18129 // TODO: Support variadic friend template decls?
18130 D = FriendTemplateDecl::Create(Context, DC: CurContext, Loc, Params: TempParams, Friend: TSI,
18131 FriendLoc);
18132 else
18133 D = FriendDecl::Create(C&: Context, DC: CurContext, L: TSI->getTypeLoc().getBeginLoc(),
18134 Friend_: TSI, FriendL: FriendLoc, EllipsisLoc);
18135
18136 if (!D)
18137 return nullptr;
18138
18139 D->setAccess(AS_public);
18140 CurContext->addDecl(D);
18141
18142 if (Invalid)
18143 D->setInvalidDecl();
18144
18145 return D;
18146}
18147
18148NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
18149 MultiTemplateParamsArg TemplateParams) {
18150 const DeclSpec &DS = D.getDeclSpec();
18151
18152 assert(DS.isFriendSpecified());
18153 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18154
18155 SourceLocation Loc = D.getIdentifierLoc();
18156 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18157
18158 // C++ [class.friend]p1
18159 // A friend of a class is a function or class....
18160 // Note that this sees through typedefs, which is intended.
18161 // It *doesn't* see through dependent types, which is correct
18162 // according to [temp.arg.type]p3:
18163 // If a declaration acquires a function type through a
18164 // type dependent on a template-parameter and this causes
18165 // a declaration that does not use the syntactic form of a
18166 // function declarator to have a function type, the program
18167 // is ill-formed.
18168 if (!TInfo->getType()->isFunctionType()) {
18169 Diag(Loc, DiagID: diag::err_unexpected_friend);
18170
18171 // It might be worthwhile to try to recover by creating an
18172 // appropriate declaration.
18173 return nullptr;
18174 }
18175
18176 // C++ [namespace.memdef]p3
18177 // - If a friend declaration in a non-local class first declares a
18178 // class or function, the friend class or function is a member
18179 // of the innermost enclosing namespace.
18180 // - The name of the friend is not found by simple name lookup
18181 // until a matching declaration is provided in that namespace
18182 // scope (either before or after the class declaration granting
18183 // friendship).
18184 // - If a friend function is called, its name may be found by the
18185 // name lookup that considers functions from namespaces and
18186 // classes associated with the types of the function arguments.
18187 // - When looking for a prior declaration of a class or a function
18188 // declared as a friend, scopes outside the innermost enclosing
18189 // namespace scope are not considered.
18190
18191 CXXScopeSpec &SS = D.getCXXScopeSpec();
18192 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
18193 assert(NameInfo.getName());
18194
18195 // Check for unexpanded parameter packs.
18196 if (DiagnoseUnexpandedParameterPack(Loc, T: TInfo, UPPC: UPPC_FriendDeclaration) ||
18197 DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_FriendDeclaration) ||
18198 DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_FriendDeclaration))
18199 return nullptr;
18200
18201 // The context we found the declaration in, or in which we should
18202 // create the declaration.
18203 DeclContext *DC;
18204 Scope *DCScope = S;
18205 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18206 RedeclarationKind::ForExternalRedeclaration);
18207
18208 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18209
18210 // There are five cases here.
18211 // - There's no scope specifier and we're in a local class. Only look
18212 // for functions declared in the immediately-enclosing block scope.
18213 // We recover from invalid scope qualifiers as if they just weren't there.
18214 FunctionDecl *FunctionContainingLocalClass = nullptr;
18215 if ((SS.isInvalid() || !SS.isSet()) &&
18216 (FunctionContainingLocalClass =
18217 cast<CXXRecordDecl>(Val: CurContext)->isLocalClass())) {
18218 // C++11 [class.friend]p11:
18219 // If a friend declaration appears in a local class and the name
18220 // specified is an unqualified name, a prior declaration is
18221 // looked up without considering scopes that are outside the
18222 // innermost enclosing non-class scope. For a friend function
18223 // declaration, if there is no prior declaration, the program is
18224 // ill-formed.
18225
18226 // Find the innermost enclosing non-class scope. This is the block
18227 // scope containing the local class definition (or for a nested class,
18228 // the outer local class).
18229 DCScope = S->getFnParent();
18230
18231 // Look up the function name in the scope.
18232 Previous.clear(Kind: LookupLocalFriendName);
18233 LookupName(R&: Previous, S, /*AllowBuiltinCreation*/false);
18234
18235 if (!Previous.empty()) {
18236 // All possible previous declarations must have the same context:
18237 // either they were declared at block scope or they are members of
18238 // one of the enclosing local classes.
18239 DC = Previous.getRepresentativeDecl()->getDeclContext();
18240 } else {
18241 // This is ill-formed, but provide the context that we would have
18242 // declared the function in, if we were permitted to, for error recovery.
18243 DC = FunctionContainingLocalClass;
18244 }
18245 adjustContextForLocalExternDecl(DC);
18246
18247 // - There's no scope specifier, in which case we just go to the
18248 // appropriate scope and look for a function or function template
18249 // there as appropriate.
18250 } else if (SS.isInvalid() || !SS.isSet()) {
18251 // C++11 [namespace.memdef]p3:
18252 // If the name in a friend declaration is neither qualified nor
18253 // a template-id and the declaration is a function or an
18254 // elaborated-type-specifier, the lookup to determine whether
18255 // the entity has been previously declared shall not consider
18256 // any scopes outside the innermost enclosing namespace.
18257
18258 // Find the appropriate context according to the above.
18259 DC = CurContext;
18260
18261 // Skip class contexts. If someone can cite chapter and verse
18262 // for this behavior, that would be nice --- it's what GCC and
18263 // EDG do, and it seems like a reasonable intent, but the spec
18264 // really only says that checks for unqualified existing
18265 // declarations should stop at the nearest enclosing namespace,
18266 // not that they should only consider the nearest enclosing
18267 // namespace.
18268 while (DC->isRecord())
18269 DC = DC->getParent();
18270
18271 DeclContext *LookupDC = DC->getNonTransparentContext();
18272 while (true) {
18273 LookupQualifiedName(R&: Previous, LookupCtx: LookupDC);
18274
18275 if (!Previous.empty()) {
18276 DC = LookupDC;
18277 break;
18278 }
18279
18280 if (isTemplateId) {
18281 if (isa<TranslationUnitDecl>(Val: LookupDC)) break;
18282 } else {
18283 if (LookupDC->isFileContext()) break;
18284 }
18285 LookupDC = LookupDC->getParent();
18286 }
18287
18288 DCScope = getScopeForDeclContext(S, DC);
18289
18290 // - There's a non-dependent scope specifier, in which case we
18291 // compute it and do a previous lookup there for a function
18292 // or function template.
18293 } else if (!SS.getScopeRep()->isDependent()) {
18294 DC = computeDeclContext(SS);
18295 if (!DC) return nullptr;
18296
18297 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18298
18299 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18300
18301 // C++ [class.friend]p1: A friend of a class is a function or
18302 // class that is not a member of the class . . .
18303 if (DC->Equals(DC: CurContext))
18304 Diag(Loc: DS.getFriendSpecLoc(),
18305 DiagID: getLangOpts().CPlusPlus11 ?
18306 diag::warn_cxx98_compat_friend_is_member :
18307 diag::err_friend_is_member);
18308
18309 // - There's a scope specifier that does not match any template
18310 // parameter lists, in which case we use some arbitrary context,
18311 // create a method or method template, and wait for instantiation.
18312 // - There's a scope specifier that does match some template
18313 // parameter lists, which we don't handle right now.
18314 } else {
18315 DC = CurContext;
18316 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18317 }
18318
18319 if (!DC->isRecord()) {
18320 int DiagArg = -1;
18321 switch (D.getName().getKind()) {
18322 case UnqualifiedIdKind::IK_ConstructorTemplateId:
18323 case UnqualifiedIdKind::IK_ConstructorName:
18324 DiagArg = 0;
18325 break;
18326 case UnqualifiedIdKind::IK_DestructorName:
18327 DiagArg = 1;
18328 break;
18329 case UnqualifiedIdKind::IK_ConversionFunctionId:
18330 DiagArg = 2;
18331 break;
18332 case UnqualifiedIdKind::IK_DeductionGuideName:
18333 DiagArg = 3;
18334 break;
18335 case UnqualifiedIdKind::IK_Identifier:
18336 case UnqualifiedIdKind::IK_ImplicitSelfParam:
18337 case UnqualifiedIdKind::IK_LiteralOperatorId:
18338 case UnqualifiedIdKind::IK_OperatorFunctionId:
18339 case UnqualifiedIdKind::IK_TemplateId:
18340 break;
18341 }
18342 // This implies that it has to be an operator or function.
18343 if (DiagArg >= 0) {
18344 Diag(Loc, DiagID: diag::err_introducing_special_friend) << DiagArg;
18345 return nullptr;
18346 }
18347 }
18348
18349 // FIXME: This is an egregious hack to cope with cases where the scope stack
18350 // does not contain the declaration context, i.e., in an out-of-line
18351 // definition of a class.
18352 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18353 if (!DCScope) {
18354 FakeDCScope.setEntity(DC);
18355 DCScope = &FakeDCScope;
18356 }
18357
18358 bool AddToScope = true;
18359 NamedDecl *ND = ActOnFunctionDeclarator(S: DCScope, D, DC, TInfo, Previous,
18360 TemplateParamLists: TemplateParams, AddToScope);
18361 if (!ND) return nullptr;
18362
18363 assert(ND->getLexicalDeclContext() == CurContext);
18364
18365 // If we performed typo correction, we might have added a scope specifier
18366 // and changed the decl context.
18367 DC = ND->getDeclContext();
18368
18369 // Add the function declaration to the appropriate lookup tables,
18370 // adjusting the redeclarations list as necessary. We don't
18371 // want to do this yet if the friending class is dependent.
18372 //
18373 // Also update the scope-based lookup if the target context's
18374 // lookup context is in lexical scope.
18375 if (!CurContext->isDependentContext()) {
18376 DC = DC->getRedeclContext();
18377 DC->makeDeclVisibleInContext(D: ND);
18378 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18379 PushOnScopeChains(D: ND, S: EnclosingScope, /*AddToContext=*/ false);
18380 }
18381
18382 FriendDecl *FrD = FriendDecl::Create(C&: Context, DC: CurContext,
18383 L: D.getIdentifierLoc(), Friend_: ND,
18384 FriendL: DS.getFriendSpecLoc());
18385 FrD->setAccess(AS_public);
18386 CurContext->addDecl(D: FrD);
18387
18388 if (ND->isInvalidDecl()) {
18389 FrD->setInvalidDecl();
18390 } else {
18391 if (DC->isRecord()) CheckFriendAccess(D: ND);
18392
18393 FunctionDecl *FD;
18394 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: ND))
18395 FD = FTD->getTemplatedDecl();
18396 else
18397 FD = cast<FunctionDecl>(Val: ND);
18398
18399 // C++ [class.friend]p6:
18400 // A function may be defined in a friend declaration of a class if and
18401 // only if the class is a non-local class, and the function name is
18402 // unqualified.
18403 if (D.isFunctionDefinition()) {
18404 // Qualified friend function definition.
18405 if (SS.isNotEmpty()) {
18406 // FIXME: We should only do this if the scope specifier names the
18407 // innermost enclosing namespace; otherwise the fixit changes the
18408 // meaning of the code.
18409 SemaDiagnosticBuilder DB =
18410 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def);
18411
18412 DB << SS.getScopeRep();
18413 if (DC->isFileContext())
18414 DB << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
18415
18416 // Friend function defined in a local class.
18417 } else if (FunctionContainingLocalClass) {
18418 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_def_in_local_class);
18419
18420 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18421 // a template-id, the function name is not unqualified because these is
18422 // no name. While the wording requires some reading in-between the
18423 // lines, GCC, MSVC, and EDG all consider a friend function
18424 // specialization definitions to be de facto explicit specialization
18425 // and diagnose them as such.
18426 } else if (isTemplateId) {
18427 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_specialization_def);
18428 }
18429 }
18430
18431 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18432 // default argument expression, that declaration shall be a definition
18433 // and shall be the only declaration of the function or function
18434 // template in the translation unit.
18435 if (functionDeclHasDefaultArgument(FD)) {
18436 // We can't look at FD->getPreviousDecl() because it may not have been set
18437 // if we're in a dependent context. If the function is known to be a
18438 // redeclaration, we will have narrowed Previous down to the right decl.
18439 if (D.isRedeclaration()) {
18440 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
18441 Diag(Loc: Previous.getRepresentativeDecl()->getLocation(),
18442 DiagID: diag::note_previous_declaration);
18443 } else if (!D.isFunctionDefinition())
18444 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_must_be_def);
18445 }
18446
18447 // Mark templated-scope function declarations as unsupported.
18448 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18449 Diag(Loc: FD->getLocation(), DiagID: diag::warn_template_qualified_friend_unsupported)
18450 << SS.getScopeRep() << SS.getRange()
18451 << cast<CXXRecordDecl>(Val: CurContext);
18452 FrD->setUnsupportedFriend(true);
18453 }
18454 }
18455
18456 warnOnReservedIdentifier(D: ND);
18457
18458 return ND;
18459}
18460
18461void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
18462 StringLiteral *Message) {
18463 AdjustDeclIfTemplate(Decl&: Dcl);
18464
18465 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: Dcl);
18466 if (!Fn) {
18467 Diag(Loc: DelLoc, DiagID: diag::err_deleted_non_function);
18468 return;
18469 }
18470
18471 // Deleted function does not have a body.
18472 Fn->setWillHaveBody(false);
18473
18474 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18475 // Don't consider the implicit declaration we generate for explicit
18476 // specializations. FIXME: Do not generate these implicit declarations.
18477 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18478 Prev->getPreviousDecl()) &&
18479 !Prev->isDefined()) {
18480 Diag(Loc: DelLoc, DiagID: diag::err_deleted_decl_not_first);
18481 Diag(Loc: Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18482 DiagID: Prev->isImplicit() ? diag::note_previous_implicit_declaration
18483 : diag::note_previous_declaration);
18484 // We can't recover from this; the declaration might have already
18485 // been used.
18486 Fn->setInvalidDecl();
18487 return;
18488 }
18489
18490 // To maintain the invariant that functions are only deleted on their first
18491 // declaration, mark the implicitly-instantiated declaration of the
18492 // explicitly-specialized function as deleted instead of marking the
18493 // instantiated redeclaration.
18494 Fn = Fn->getCanonicalDecl();
18495 }
18496
18497 // dllimport/dllexport cannot be deleted.
18498 if (const InheritableAttr *DLLAttr = getDLLAttr(D: Fn)) {
18499 Diag(Loc: Fn->getLocation(), DiagID: diag::err_attribute_dll_deleted) << DLLAttr;
18500 Fn->setInvalidDecl();
18501 }
18502
18503 // C++11 [basic.start.main]p3:
18504 // A program that defines main as deleted [...] is ill-formed.
18505 if (Fn->isMain())
18506 Diag(Loc: DelLoc, DiagID: diag::err_deleted_main);
18507
18508 // C++11 [dcl.fct.def.delete]p4:
18509 // A deleted function is implicitly inline.
18510 Fn->setImplicitlyInline();
18511 Fn->setDeletedAsWritten(D: true, Message);
18512}
18513
18514void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18515 if (!Dcl || Dcl->isInvalidDecl())
18516 return;
18517
18518 auto *FD = dyn_cast<FunctionDecl>(Val: Dcl);
18519 if (!FD) {
18520 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Dcl)) {
18521 if (getDefaultedFunctionKind(FD: FTD->getTemplatedDecl()).isComparison()) {
18522 Diag(Loc: DefaultLoc, DiagID: diag::err_defaulted_comparison_template);
18523 return;
18524 }
18525 }
18526
18527 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18528 << getLangOpts().CPlusPlus20;
18529 return;
18530 }
18531
18532 // Reject if this can't possibly be a defaultable function.
18533 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
18534 if (!DefKind &&
18535 // A dependent function that doesn't locally look defaultable can
18536 // still instantiate to a defaultable function if it's a constructor
18537 // or assignment operator.
18538 (!FD->isDependentContext() ||
18539 (!isa<CXXConstructorDecl>(Val: FD) &&
18540 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18541 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18542 << getLangOpts().CPlusPlus20;
18543 return;
18544 }
18545
18546 // Issue compatibility warning. We already warned if the operator is
18547 // 'operator<=>' when parsing the '<=>' token.
18548 if (DefKind.isComparison() &&
18549 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18550 Diag(Loc: DefaultLoc, DiagID: getLangOpts().CPlusPlus20
18551 ? diag::warn_cxx17_compat_defaulted_comparison
18552 : diag::ext_defaulted_comparison);
18553 }
18554
18555 FD->setDefaulted();
18556 FD->setExplicitlyDefaulted();
18557 FD->setDefaultLoc(DefaultLoc);
18558
18559 // Defer checking functions that are defaulted in a dependent context.
18560 if (FD->isDependentContext())
18561 return;
18562
18563 // Unset that we will have a body for this function. We might not,
18564 // if it turns out to be trivial, and we don't need this marking now
18565 // that we've marked it as defaulted.
18566 FD->setWillHaveBody(false);
18567
18568 if (DefKind.isComparison()) {
18569 // If this comparison's defaulting occurs within the definition of its
18570 // lexical class context, we have to do the checking when complete.
18571 if (auto const *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()))
18572 if (!RD->isCompleteDefinition())
18573 return;
18574 }
18575
18576 // If this member fn was defaulted on its first declaration, we will have
18577 // already performed the checking in CheckCompletedCXXClass. Such a
18578 // declaration doesn't trigger an implicit definition.
18579 if (isa<CXXMethodDecl>(Val: FD)) {
18580 const FunctionDecl *Primary = FD;
18581 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18582 // Ask the template instantiation pattern that actually had the
18583 // '= default' on it.
18584 Primary = Pattern;
18585 if (Primary->getCanonicalDecl()->isDefaulted())
18586 return;
18587 }
18588
18589 if (DefKind.isComparison()) {
18590 if (CheckExplicitlyDefaultedComparison(S: nullptr, FD, DCK: DefKind.asComparison()))
18591 FD->setInvalidDecl();
18592 else
18593 DefineDefaultedComparison(UseLoc: DefaultLoc, FD, DCK: DefKind.asComparison());
18594 } else {
18595 auto *MD = cast<CXXMethodDecl>(Val: FD);
18596
18597 if (CheckExplicitlyDefaultedSpecialMember(MD, CSM: DefKind.asSpecialMember(),
18598 DefaultLoc))
18599 MD->setInvalidDecl();
18600 else
18601 DefineDefaultedFunction(S&: *this, FD: MD, DefaultLoc);
18602 }
18603}
18604
18605static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18606 for (Stmt *SubStmt : S->children()) {
18607 if (!SubStmt)
18608 continue;
18609 if (isa<ReturnStmt>(Val: SubStmt))
18610 Self.Diag(Loc: SubStmt->getBeginLoc(),
18611 DiagID: diag::err_return_in_constructor_handler);
18612 if (!isa<Expr>(Val: SubStmt))
18613 SearchForReturnInStmt(Self, S: SubStmt);
18614 }
18615}
18616
18617void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18618 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18619 CXXCatchStmt *Handler = TryBlock->getHandler(i: I);
18620 SearchForReturnInStmt(Self&: *this, S: Handler);
18621 }
18622}
18623
18624void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
18625 StringLiteral *DeletedMessage) {
18626 switch (BodyKind) {
18627 case FnBodyKind::Delete:
18628 SetDeclDeleted(Dcl: D, DelLoc: Loc, Message: DeletedMessage);
18629 break;
18630 case FnBodyKind::Default:
18631 SetDeclDefaulted(Dcl: D, DefaultLoc: Loc);
18632 break;
18633 case FnBodyKind::Other:
18634 llvm_unreachable(
18635 "Parsed function body should be '= delete;' or '= default;'");
18636 }
18637}
18638
18639bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
18640 const CXXMethodDecl *Old) {
18641 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18642 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18643
18644 if (OldFT->hasExtParameterInfos()) {
18645 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18646 // A parameter of the overriding method should be annotated with noescape
18647 // if the corresponding parameter of the overridden method is annotated.
18648 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18649 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18650 Diag(Loc: New->getParamDecl(i: I)->getLocation(),
18651 DiagID: diag::warn_overriding_method_missing_noescape);
18652 Diag(Loc: Old->getParamDecl(i: I)->getLocation(),
18653 DiagID: diag::note_overridden_marked_noescape);
18654 }
18655 }
18656
18657 // SME attributes must match when overriding a function declaration.
18658 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
18659 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_overriding_attributes)
18660 << New << New->getType() << Old->getType();
18661 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18662 return true;
18663 }
18664
18665 // Virtual overrides must have the same code_seg.
18666 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18667 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18668 if ((NewCSA || OldCSA) &&
18669 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18670 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_code_seg_override);
18671 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
18672 return true;
18673 }
18674
18675 // Virtual overrides: check for matching effects.
18676 if (Context.hasAnyFunctionEffects()) {
18677 const auto OldFX = Old->getFunctionEffects();
18678 const auto NewFXOrig = New->getFunctionEffects();
18679
18680 if (OldFX != NewFXOrig) {
18681 FunctionEffectSet NewFX(NewFXOrig);
18682 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18683 FunctionEffectSet::Conflicts Errs;
18684 for (const auto &Diff : Diffs) {
18685 switch (Diff.shouldDiagnoseMethodOverride(OldMethod: *Old, OldFX, NewMethod: *New, NewFX)) {
18686 case FunctionEffectDiff::OverrideResult::NoAction:
18687 break;
18688 case FunctionEffectDiff::OverrideResult::Warn:
18689 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_func_effect_override)
18690 << Diff.effectName();
18691 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18692 << Old->getReturnTypeSourceRange();
18693 break;
18694 case FunctionEffectDiff::OverrideResult::Merge: {
18695 NewFX.insert(NewEC: Diff.Old.value(), Errs);
18696 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18697 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18698 EPI.FunctionEffects = FunctionEffectsRef(NewFX);
18699 QualType ModQT = Context.getFunctionType(ResultTy: NewFT->getReturnType(),
18700 Args: NewFT->getParamTypes(), EPI);
18701 New->setType(ModQT);
18702 break;
18703 }
18704 }
18705 }
18706 if (!Errs.empty())
18707 diagnoseFunctionEffectMergeConflicts(Errs, NewLoc: New->getLocation(),
18708 OldLoc: Old->getLocation());
18709 }
18710 }
18711
18712 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18713
18714 // If the calling conventions match, everything is fine
18715 if (NewCC == OldCC)
18716 return false;
18717
18718 // If the calling conventions mismatch because the new function is static,
18719 // suppress the calling convention mismatch error; the error about static
18720 // function override (err_static_overrides_virtual from
18721 // Sema::CheckFunctionDeclaration) is more clear.
18722 if (New->getStorageClass() == SC_Static)
18723 return false;
18724
18725 Diag(Loc: New->getLocation(),
18726 DiagID: diag::err_conflicting_overriding_cc_attributes)
18727 << New->getDeclName() << New->getType() << Old->getType();
18728 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18729 return true;
18730}
18731
18732bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
18733 const CXXMethodDecl *Old) {
18734 // CWG2553
18735 // A virtual function shall not be an explicit object member function.
18736 if (!New->isExplicitObjectMemberFunction())
18737 return true;
18738 Diag(Loc: New->getParamDecl(i: 0)->getBeginLoc(),
18739 DiagID: diag::err_explicit_object_parameter_nonmember)
18740 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18741 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18742 New->setInvalidDecl();
18743 return false;
18744}
18745
18746bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18747 const CXXMethodDecl *Old) {
18748 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18749 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18750
18751 if (Context.hasSameType(T1: NewTy, T2: OldTy) ||
18752 NewTy->isDependentType() || OldTy->isDependentType())
18753 return false;
18754
18755 // Check if the return types are covariant
18756 QualType NewClassTy, OldClassTy;
18757
18758 /// Both types must be pointers or references to classes.
18759 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18760 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18761 NewClassTy = NewPT->getPointeeType();
18762 OldClassTy = OldPT->getPointeeType();
18763 }
18764 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18765 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18766 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18767 NewClassTy = NewRT->getPointeeType();
18768 OldClassTy = OldRT->getPointeeType();
18769 }
18770 }
18771 }
18772
18773 // The return types aren't either both pointers or references to a class type.
18774 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
18775 Diag(Loc: New->getLocation(),
18776 DiagID: diag::err_different_return_type_for_overriding_virtual_function)
18777 << New->getDeclName() << NewTy << OldTy
18778 << New->getReturnTypeSourceRange();
18779 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18780 << Old->getReturnTypeSourceRange();
18781
18782 return true;
18783 }
18784
18785 if (!Context.hasSameUnqualifiedType(T1: NewClassTy, T2: OldClassTy)) {
18786 // C++14 [class.virtual]p8:
18787 // If the class type in the covariant return type of D::f differs from
18788 // that of B::f, the class type in the return type of D::f shall be
18789 // complete at the point of declaration of D::f or shall be the class
18790 // type D.
18791 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18792 if (!RT->isBeingDefined() &&
18793 RequireCompleteType(Loc: New->getLocation(), T: NewClassTy,
18794 DiagID: diag::err_covariant_return_incomplete,
18795 Args: New->getDeclName()))
18796 return true;
18797 }
18798
18799 // Check if the new class derives from the old class.
18800 if (!IsDerivedFrom(Loc: New->getLocation(), Derived: NewClassTy, Base: OldClassTy)) {
18801 Diag(Loc: New->getLocation(), DiagID: diag::err_covariant_return_not_derived)
18802 << New->getDeclName() << NewTy << OldTy
18803 << New->getReturnTypeSourceRange();
18804 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18805 << Old->getReturnTypeSourceRange();
18806 return true;
18807 }
18808
18809 // Check if we the conversion from derived to base is valid.
18810 if (CheckDerivedToBaseConversion(
18811 Derived: NewClassTy, Base: OldClassTy,
18812 InaccessibleBaseID: diag::err_covariant_return_inaccessible_base,
18813 AmbiguousBaseConvID: diag::err_covariant_return_ambiguous_derived_to_base_conv,
18814 Loc: New->getLocation(), Range: New->getReturnTypeSourceRange(),
18815 Name: New->getDeclName(), BasePath: nullptr)) {
18816 // FIXME: this note won't trigger for delayed access control
18817 // diagnostics, and it's impossible to get an undelayed error
18818 // here from access control during the original parse because
18819 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18820 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18821 << Old->getReturnTypeSourceRange();
18822 return true;
18823 }
18824 }
18825
18826 // The qualifiers of the return types must be the same.
18827 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18828 Diag(Loc: New->getLocation(),
18829 DiagID: diag::err_covariant_return_type_different_qualifications)
18830 << New->getDeclName() << NewTy << OldTy
18831 << New->getReturnTypeSourceRange();
18832 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18833 << Old->getReturnTypeSourceRange();
18834 return true;
18835 }
18836
18837
18838 // The new class type must have the same or less qualifiers as the old type.
18839 if (!OldClassTy.isAtLeastAsQualifiedAs(other: NewClassTy, Ctx: getASTContext())) {
18840 Diag(Loc: New->getLocation(),
18841 DiagID: diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
18842 << New->getDeclName() << NewTy << OldTy
18843 << New->getReturnTypeSourceRange();
18844 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18845 << Old->getReturnTypeSourceRange();
18846 return true;
18847 }
18848
18849 return false;
18850}
18851
18852bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
18853 SourceLocation EndLoc = InitRange.getEnd();
18854 if (EndLoc.isValid())
18855 Method->setRangeEnd(EndLoc);
18856
18857 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18858 Method->setIsPureVirtual();
18859 return false;
18860 }
18861
18862 if (!Method->isInvalidDecl())
18863 Diag(Loc: Method->getLocation(), DiagID: diag::err_non_virtual_pure)
18864 << Method->getDeclName() << InitRange;
18865 return true;
18866}
18867
18868void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
18869 if (D->getFriendObjectKind())
18870 Diag(Loc: D->getLocation(), DiagID: diag::err_pure_friend);
18871 else if (auto *M = dyn_cast<CXXMethodDecl>(Val: D))
18872 CheckPureMethod(Method: M, InitRange: ZeroLoc);
18873 else
18874 Diag(Loc: D->getLocation(), DiagID: diag::err_illegal_initializer);
18875}
18876
18877/// Invoked when we are about to parse an initializer for the declaration
18878/// 'Dcl'.
18879///
18880/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18881/// static data member of class X, names should be looked up in the scope of
18882/// class X. If the declaration had a scope specifier, a scope will have
18883/// been created and passed in for this purpose. Otherwise, S will be null.
18884void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
18885 assert(D && !D->isInvalidDecl());
18886
18887 // We will always have a nested name specifier here, but this declaration
18888 // might not be out of line if the specifier names the current namespace:
18889 // extern int n;
18890 // int ::n = 0;
18891 if (S && D->isOutOfLine())
18892 EnterDeclaratorContext(S, DC: D->getDeclContext());
18893
18894 PushExpressionEvaluationContext(
18895 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, LambdaContextDecl: D);
18896}
18897
18898void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
18899 assert(D);
18900
18901 if (S && D->isOutOfLine())
18902 ExitDeclaratorContext(S);
18903
18904 if (getLangOpts().CPlusPlus23) {
18905 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18906 // [...]
18907 // - the initializer of a variable that is usable in constant expressions or
18908 // has constant initialization.
18909 if (auto *VD = dyn_cast<VarDecl>(Val: D);
18910 VD && (VD->isUsableInConstantExpressions(C: Context) ||
18911 VD->hasConstantInitialization())) {
18912 // An expression or conversion is in an 'immediate function context' if it
18913 // is potentially evaluated and either:
18914 // [...]
18915 // - it is a subexpression of a manifestly constant-evaluated expression
18916 // or conversion.
18917 ExprEvalContexts.back().InImmediateFunctionContext = true;
18918 }
18919 }
18920
18921 // Unless the initializer is in an immediate function context (as determined
18922 // above), this will evaluate all contained immediate function calls as
18923 // constant expressions. If the initializer IS an immediate function context,
18924 // the initializer has been determined to be a constant expression, and all
18925 // such evaluations will be elided (i.e., as if we "knew the whole time" that
18926 // it was a constant expression).
18927 PopExpressionEvaluationContext();
18928}
18929
18930DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
18931 // C++ 6.4p2:
18932 // The declarator shall not specify a function or an array.
18933 // The type-specifier-seq shall not contain typedef and shall not declare a
18934 // new class or enumeration.
18935 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18936 "Parser allowed 'typedef' as storage class of condition decl.");
18937
18938 Decl *Dcl = ActOnDeclarator(S, D);
18939 if (!Dcl)
18940 return true;
18941
18942 if (isa<FunctionDecl>(Val: Dcl)) { // The declarator shall not specify a function.
18943 Diag(Loc: Dcl->getLocation(), DiagID: diag::err_invalid_use_of_function_type)
18944 << D.getSourceRange();
18945 return true;
18946 }
18947
18948 if (auto *VD = dyn_cast<VarDecl>(Val: Dcl))
18949 VD->setCXXCondDecl();
18950
18951 return Dcl;
18952}
18953
18954void Sema::LoadExternalVTableUses() {
18955 if (!ExternalSource)
18956 return;
18957
18958 SmallVector<ExternalVTableUse, 4> VTables;
18959 ExternalSource->ReadUsedVTables(VTables);
18960 SmallVector<VTableUse, 4> NewUses;
18961 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18962 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18963 = VTablesUsed.find(Val: VTables[I].Record);
18964 // Even if a definition wasn't required before, it may be required now.
18965 if (Pos != VTablesUsed.end()) {
18966 if (!Pos->second && VTables[I].DefinitionRequired)
18967 Pos->second = true;
18968 continue;
18969 }
18970
18971 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18972 NewUses.push_back(Elt: VTableUse(VTables[I].Record, VTables[I].Location));
18973 }
18974
18975 VTableUses.insert(I: VTableUses.begin(), From: NewUses.begin(), To: NewUses.end());
18976}
18977
18978void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
18979 bool DefinitionRequired) {
18980 // Ignore any vtable uses in unevaluated operands or for classes that do
18981 // not have a vtable.
18982 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18983 CurContext->isDependentContext() || isUnevaluatedContext())
18984 return;
18985 // Do not mark as used if compiling for the device outside of the target
18986 // region.
18987 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18988 !OpenMP().isInOpenMPDeclareTargetContext() &&
18989 !OpenMP().isInOpenMPTargetExecutionDirective()) {
18990 if (!DefinitionRequired)
18991 MarkVirtualMembersReferenced(Loc, RD: Class);
18992 return;
18993 }
18994
18995 // Try to insert this class into the map.
18996 LoadExternalVTableUses();
18997 Class = Class->getCanonicalDecl();
18998 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18999 Pos = VTablesUsed.insert(KV: std::make_pair(x&: Class, y&: DefinitionRequired));
19000 if (!Pos.second) {
19001 // If we already had an entry, check to see if we are promoting this vtable
19002 // to require a definition. If so, we need to reappend to the VTableUses
19003 // list, since we may have already processed the first entry.
19004 if (DefinitionRequired && !Pos.first->second) {
19005 Pos.first->second = true;
19006 } else {
19007 // Otherwise, we can early exit.
19008 return;
19009 }
19010 } else {
19011 // The Microsoft ABI requires that we perform the destructor body
19012 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19013 // the deleting destructor is emitted with the vtable, not with the
19014 // destructor definition as in the Itanium ABI.
19015 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19016 CXXDestructorDecl *DD = Class->getDestructor();
19017 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19018 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19019 // If this is an out-of-line declaration, marking it referenced will
19020 // not do anything. Manually call CheckDestructor to look up operator
19021 // delete().
19022 ContextRAII SavedContext(*this, DD);
19023 CheckDestructor(Destructor: DD);
19024 } else {
19025 MarkFunctionReferenced(Loc, Func: Class->getDestructor());
19026 }
19027 }
19028 }
19029 }
19030
19031 // Local classes need to have their virtual members marked
19032 // immediately. For all other classes, we mark their virtual members
19033 // at the end of the translation unit.
19034 if (Class->isLocalClass())
19035 MarkVirtualMembersReferenced(Loc, RD: Class->getDefinition());
19036 else
19037 VTableUses.push_back(Elt: std::make_pair(x&: Class, y&: Loc));
19038}
19039
19040bool Sema::DefineUsedVTables() {
19041 LoadExternalVTableUses();
19042 if (VTableUses.empty())
19043 return false;
19044
19045 // Note: The VTableUses vector could grow as a result of marking
19046 // the members of a class as "used", so we check the size each
19047 // time through the loop and prefer indices (which are stable) to
19048 // iterators (which are not).
19049 bool DefinedAnything = false;
19050 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19051 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19052 if (!Class)
19053 continue;
19054 TemplateSpecializationKind ClassTSK =
19055 Class->getTemplateSpecializationKind();
19056
19057 SourceLocation Loc = VTableUses[I].second;
19058
19059 bool DefineVTable = true;
19060
19061 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(RD: Class);
19062 // V-tables for non-template classes with an owning module are always
19063 // uniquely emitted in that module.
19064 if (Class->isInCurrentModuleUnit()) {
19065 DefineVTable = true;
19066 } else if (KeyFunction && !KeyFunction->hasBody()) {
19067 // If this class has a key function, but that key function is
19068 // defined in another translation unit, we don't need to emit the
19069 // vtable even though we're using it.
19070 // The key function is in another translation unit.
19071 DefineVTable = false;
19072 TemplateSpecializationKind TSK =
19073 KeyFunction->getTemplateSpecializationKind();
19074 assert(TSK != TSK_ExplicitInstantiationDefinition &&
19075 TSK != TSK_ImplicitInstantiation &&
19076 "Instantiations don't have key functions");
19077 (void)TSK;
19078 } else if (!KeyFunction) {
19079 // If we have a class with no key function that is the subject
19080 // of an explicit instantiation declaration, suppress the
19081 // vtable; it will live with the explicit instantiation
19082 // definition.
19083 bool IsExplicitInstantiationDeclaration =
19084 ClassTSK == TSK_ExplicitInstantiationDeclaration;
19085 for (auto *R : Class->redecls()) {
19086 TemplateSpecializationKind TSK
19087 = cast<CXXRecordDecl>(Val: R)->getTemplateSpecializationKind();
19088 if (TSK == TSK_ExplicitInstantiationDeclaration)
19089 IsExplicitInstantiationDeclaration = true;
19090 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19091 IsExplicitInstantiationDeclaration = false;
19092 break;
19093 }
19094 }
19095
19096 if (IsExplicitInstantiationDeclaration)
19097 DefineVTable = false;
19098 }
19099
19100 // The exception specifications for all virtual members may be needed even
19101 // if we are not providing an authoritative form of the vtable in this TU.
19102 // We may choose to emit it available_externally anyway.
19103 if (!DefineVTable) {
19104 MarkVirtualMemberExceptionSpecsNeeded(Loc, RD: Class);
19105 continue;
19106 }
19107
19108 // Mark all of the virtual members of this class as referenced, so
19109 // that we can build a vtable. Then, tell the AST consumer that a
19110 // vtable for this class is required.
19111 DefinedAnything = true;
19112 MarkVirtualMembersReferenced(Loc, RD: Class);
19113 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19114 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
19115 Consumer.HandleVTable(RD: Class);
19116
19117 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19118 // no key function or the key function is inlined. Don't warn in C++ ABIs
19119 // that lack key functions, since the user won't be able to make one.
19120 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19121 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
19122 ClassTSK != TSK_ExplicitInstantiationDefinition) {
19123 const FunctionDecl *KeyFunctionDef = nullptr;
19124 if (!KeyFunction || (KeyFunction->hasBody(Definition&: KeyFunctionDef) &&
19125 KeyFunctionDef->isInlined()))
19126 Diag(Loc: Class->getLocation(), DiagID: diag::warn_weak_vtable) << Class;
19127 }
19128 }
19129 VTableUses.clear();
19130
19131 return DefinedAnything;
19132}
19133
19134void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
19135 const CXXRecordDecl *RD) {
19136 for (const auto *I : RD->methods())
19137 if (I->isVirtual() && !I->isPureVirtual())
19138 ResolveExceptionSpec(Loc, FPT: I->getType()->castAs<FunctionProtoType>());
19139}
19140
19141void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
19142 const CXXRecordDecl *RD,
19143 bool ConstexprOnly) {
19144 // Mark all functions which will appear in RD's vtable as used.
19145 CXXFinalOverriderMap FinalOverriders;
19146 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
19147 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
19148 E = FinalOverriders.end();
19149 I != E; ++I) {
19150 for (OverridingMethods::const_iterator OI = I->second.begin(),
19151 OE = I->second.end();
19152 OI != OE; ++OI) {
19153 assert(OI->second.size() > 0 && "no final overrider");
19154 CXXMethodDecl *Overrider = OI->second.front().Method;
19155
19156 // C++ [basic.def.odr]p2:
19157 // [...] A virtual member function is used if it is not pure. [...]
19158 if (!Overrider->isPureVirtual() &&
19159 (!ConstexprOnly || Overrider->isConstexpr()))
19160 MarkFunctionReferenced(Loc, Func: Overrider);
19161 }
19162 }
19163
19164 // Only classes that have virtual bases need a VTT.
19165 if (RD->getNumVBases() == 0)
19166 return;
19167
19168 for (const auto &I : RD->bases()) {
19169 const auto *Base =
19170 cast<CXXRecordDecl>(Val: I.getType()->castAs<RecordType>()->getDecl());
19171 if (Base->getNumVBases() == 0)
19172 continue;
19173 MarkVirtualMembersReferenced(Loc, RD: Base);
19174 }
19175}
19176
19177static
19178void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
19179 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
19180 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
19181 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
19182 Sema &S) {
19183 if (Ctor->isInvalidDecl())
19184 return;
19185
19186 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
19187
19188 // Target may not be determinable yet, for instance if this is a dependent
19189 // call in an uninstantiated template.
19190 if (Target) {
19191 const FunctionDecl *FNTarget = nullptr;
19192 (void)Target->hasBody(Definition&: FNTarget);
19193 Target = const_cast<CXXConstructorDecl*>(
19194 cast_or_null<CXXConstructorDecl>(Val: FNTarget));
19195 }
19196
19197 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19198 // Avoid dereferencing a null pointer here.
19199 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19200
19201 if (!Current.insert(Ptr: Canonical).second)
19202 return;
19203
19204 // We know that beyond here, we aren't chaining into a cycle.
19205 if (!Target || !Target->isDelegatingConstructor() ||
19206 Target->isInvalidDecl() || Valid.count(Ptr: TCanonical)) {
19207 Valid.insert_range(R&: Current);
19208 Current.clear();
19209 // We've hit a cycle.
19210 } else if (TCanonical == Canonical || Invalid.count(Ptr: TCanonical) ||
19211 Current.count(Ptr: TCanonical)) {
19212 // If we haven't diagnosed this cycle yet, do so now.
19213 if (!Invalid.count(Ptr: TCanonical)) {
19214 S.Diag(Loc: (*Ctor->init_begin())->getSourceLocation(),
19215 DiagID: diag::warn_delegating_ctor_cycle)
19216 << Ctor;
19217
19218 // Don't add a note for a function delegating directly to itself.
19219 if (TCanonical != Canonical)
19220 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_it_delegates_to);
19221
19222 CXXConstructorDecl *C = Target;
19223 while (C->getCanonicalDecl() != Canonical) {
19224 const FunctionDecl *FNTarget = nullptr;
19225 (void)C->getTargetConstructor()->hasBody(Definition&: FNTarget);
19226 assert(FNTarget && "Ctor cycle through bodiless function");
19227
19228 C = const_cast<CXXConstructorDecl*>(
19229 cast<CXXConstructorDecl>(Val: FNTarget));
19230 S.Diag(Loc: C->getLocation(), DiagID: diag::note_which_delegates_to);
19231 }
19232 }
19233
19234 Invalid.insert_range(R&: Current);
19235 Current.clear();
19236 } else {
19237 DelegatingCycleHelper(Ctor: Target, Valid, Invalid, Current, S);
19238 }
19239}
19240
19241
19242void Sema::CheckDelegatingCtorCycles() {
19243 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
19244
19245 for (DelegatingCtorDeclsType::iterator
19246 I = DelegatingCtorDecls.begin(source: ExternalSource.get()),
19247 E = DelegatingCtorDecls.end();
19248 I != E; ++I)
19249 DelegatingCycleHelper(Ctor: *I, Valid, Invalid, Current, S&: *this);
19250
19251 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
19252 (*CI)->setInvalidDecl();
19253}
19254
19255namespace {
19256 /// AST visitor that finds references to the 'this' expression.
19257class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19258 Sema &S;
19259
19260public:
19261 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19262
19263 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19264 S.Diag(Loc: E->getLocation(), DiagID: diag::err_this_static_member_func)
19265 << E->isImplicit();
19266 return false;
19267 }
19268};
19269}
19270
19271bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
19272 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19273 if (!TSInfo)
19274 return false;
19275
19276 TypeLoc TL = TSInfo->getTypeLoc();
19277 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19278 if (!ProtoTL)
19279 return false;
19280
19281 // C++11 [expr.prim.general]p3:
19282 // [The expression this] shall not appear before the optional
19283 // cv-qualifier-seq and it shall not appear within the declaration of a
19284 // static member function (although its type and value category are defined
19285 // within a static member function as they are within a non-static member
19286 // function). [ Note: this is because declaration matching does not occur
19287 // until the complete declarator is known. - end note ]
19288 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19289 FindCXXThisExpr Finder(*this);
19290
19291 // If the return type came after the cv-qualifier-seq, check it now.
19292 if (Proto->hasTrailingReturn() &&
19293 !Finder.TraverseTypeLoc(TL: ProtoTL.getReturnLoc()))
19294 return true;
19295
19296 // Check the exception specification.
19297 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
19298 return true;
19299
19300 // Check the trailing requires clause
19301 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19302 if (!Finder.TraverseStmt(S: const_cast<Expr *>(TRC.ConstraintExpr)))
19303 return true;
19304
19305 return checkThisInStaticMemberFunctionAttributes(Method);
19306}
19307
19308bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
19309 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19310 if (!TSInfo)
19311 return false;
19312
19313 TypeLoc TL = TSInfo->getTypeLoc();
19314 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19315 if (!ProtoTL)
19316 return false;
19317
19318 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19319 FindCXXThisExpr Finder(*this);
19320
19321 switch (Proto->getExceptionSpecType()) {
19322 case EST_Unparsed:
19323 case EST_Uninstantiated:
19324 case EST_Unevaluated:
19325 case EST_BasicNoexcept:
19326 case EST_NoThrow:
19327 case EST_DynamicNone:
19328 case EST_MSAny:
19329 case EST_None:
19330 break;
19331
19332 case EST_DependentNoexcept:
19333 case EST_NoexceptFalse:
19334 case EST_NoexceptTrue:
19335 if (!Finder.TraverseStmt(S: Proto->getNoexceptExpr()))
19336 return true;
19337 [[fallthrough]];
19338
19339 case EST_Dynamic:
19340 for (const auto &E : Proto->exceptions()) {
19341 if (!Finder.TraverseType(T: E))
19342 return true;
19343 }
19344 break;
19345 }
19346
19347 return false;
19348}
19349
19350bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19351 FindCXXThisExpr Finder(*this);
19352
19353 // Check attributes.
19354 for (const auto *A : Method->attrs()) {
19355 // FIXME: This should be emitted by tblgen.
19356 Expr *Arg = nullptr;
19357 ArrayRef<Expr *> Args;
19358 if (const auto *G = dyn_cast<GuardedByAttr>(Val: A))
19359 Arg = G->getArg();
19360 else if (const auto *G = dyn_cast<PtGuardedByAttr>(Val: A))
19361 Arg = G->getArg();
19362 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(Val: A))
19363 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19364 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(Val: A))
19365 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19366 else if (const auto *LR = dyn_cast<LockReturnedAttr>(Val: A))
19367 Arg = LR->getArg();
19368 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(Val: A))
19369 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19370 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(Val: A))
19371 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19372 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(Val: A))
19373 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19374 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(Val: A)) {
19375 Arg = AC->getSuccessValue();
19376 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19377 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(Val: A))
19378 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19379
19380 if (Arg && !Finder.TraverseStmt(S: Arg))
19381 return true;
19382
19383 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
19384 if (!Finder.TraverseStmt(S: Args[I]))
19385 return true;
19386 }
19387 }
19388
19389 return false;
19390}
19391
19392void Sema::checkExceptionSpecification(
19393 bool IsTopLevel, ExceptionSpecificationType EST,
19394 ArrayRef<ParsedType> DynamicExceptions,
19395 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19396 SmallVectorImpl<QualType> &Exceptions,
19397 FunctionProtoType::ExceptionSpecInfo &ESI) {
19398 Exceptions.clear();
19399 ESI.Type = EST;
19400 if (EST == EST_Dynamic) {
19401 Exceptions.reserve(N: DynamicExceptions.size());
19402 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19403 // FIXME: Preserve type source info.
19404 QualType ET = GetTypeFromParser(Ty: DynamicExceptions[ei]);
19405
19406 if (IsTopLevel) {
19407 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19408 collectUnexpandedParameterPacks(T: ET, Unexpanded);
19409 if (!Unexpanded.empty()) {
19410 DiagnoseUnexpandedParameterPacks(
19411 Loc: DynamicExceptionRanges[ei].getBegin(), UPPC: UPPC_ExceptionType,
19412 Unexpanded);
19413 continue;
19414 }
19415 }
19416
19417 // Check that the type is valid for an exception spec, and
19418 // drop it if not.
19419 if (!CheckSpecifiedExceptionType(T&: ET, Range: DynamicExceptionRanges[ei]))
19420 Exceptions.push_back(Elt: ET);
19421 }
19422 ESI.Exceptions = Exceptions;
19423 return;
19424 }
19425
19426 if (isComputedNoexcept(ESpecType: EST)) {
19427 assert((NoexceptExpr->isTypeDependent() ||
19428 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19429 Context.BoolTy) &&
19430 "Parser should have made sure that the expression is boolean");
19431 if (IsTopLevel && DiagnoseUnexpandedParameterPack(E: NoexceptExpr)) {
19432 ESI.Type = EST_BasicNoexcept;
19433 return;
19434 }
19435
19436 ESI.NoexceptExpr = NoexceptExpr;
19437 return;
19438 }
19439}
19440
19441void Sema::actOnDelayedExceptionSpecification(
19442 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19443 ArrayRef<ParsedType> DynamicExceptions,
19444 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19445 if (!D)
19446 return;
19447
19448 // Dig out the function we're referring to.
19449 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
19450 D = FTD->getTemplatedDecl();
19451
19452 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D);
19453 if (!FD)
19454 return;
19455
19456 // Check the exception specification.
19457 llvm::SmallVector<QualType, 4> Exceptions;
19458 FunctionProtoType::ExceptionSpecInfo ESI;
19459 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19460 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19461 ESI);
19462
19463 // Update the exception specification on the function type.
19464 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19465
19466 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
19467 if (MD->isStatic())
19468 checkThisInStaticMemberFunctionExceptionSpec(Method: MD);
19469
19470 if (MD->isVirtual()) {
19471 // Check overrides, which we previously had to delay.
19472 for (const CXXMethodDecl *O : MD->overridden_methods())
19473 CheckOverridingFunctionExceptionSpec(New: MD, Old: O);
19474 }
19475 }
19476}
19477
19478/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19479///
19480MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19481 SourceLocation DeclStart, Declarator &D,
19482 Expr *BitWidth,
19483 InClassInitStyle InitStyle,
19484 AccessSpecifier AS,
19485 const ParsedAttr &MSPropertyAttr) {
19486 const IdentifierInfo *II = D.getIdentifier();
19487 if (!II) {
19488 Diag(Loc: DeclStart, DiagID: diag::err_anonymous_property);
19489 return nullptr;
19490 }
19491 SourceLocation Loc = D.getIdentifierLoc();
19492
19493 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19494 QualType T = TInfo->getType();
19495 if (getLangOpts().CPlusPlus) {
19496 CheckExtraCXXDefaultArguments(D);
19497
19498 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19499 UPPC: UPPC_DataMemberType)) {
19500 D.setInvalidType();
19501 T = Context.IntTy;
19502 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19503 }
19504 }
19505
19506 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19507
19508 if (D.getDeclSpec().isInlineSpecified())
19509 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19510 << getLangOpts().CPlusPlus17;
19511 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19512 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19513 DiagID: diag::err_invalid_thread)
19514 << DeclSpec::getSpecifierName(S: TSCS);
19515
19516 // Check to see if this name was declared as a member previously
19517 NamedDecl *PrevDecl = nullptr;
19518 LookupResult Previous(*this, II, Loc, LookupMemberName,
19519 RedeclarationKind::ForVisibleRedeclaration);
19520 LookupName(R&: Previous, S);
19521 switch (Previous.getResultKind()) {
19522 case LookupResultKind::Found:
19523 case LookupResultKind::FoundUnresolvedValue:
19524 PrevDecl = Previous.getAsSingle<NamedDecl>();
19525 break;
19526
19527 case LookupResultKind::FoundOverloaded:
19528 PrevDecl = Previous.getRepresentativeDecl();
19529 break;
19530
19531 case LookupResultKind::NotFound:
19532 case LookupResultKind::NotFoundInCurrentInstantiation:
19533 case LookupResultKind::Ambiguous:
19534 break;
19535 }
19536
19537 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19538 // Maybe we will complain about the shadowed template parameter.
19539 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19540 // Just pretend that we didn't see the previous declaration.
19541 PrevDecl = nullptr;
19542 }
19543
19544 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19545 PrevDecl = nullptr;
19546
19547 SourceLocation TSSL = D.getBeginLoc();
19548 MSPropertyDecl *NewPD =
19549 MSPropertyDecl::Create(C&: Context, DC: Record, L: Loc, N: II, T, TInfo, StartL: TSSL,
19550 Getter: MSPropertyAttr.getPropertyDataGetter(),
19551 Setter: MSPropertyAttr.getPropertyDataSetter());
19552 ProcessDeclAttributes(S: TUScope, D: NewPD, PD: D);
19553 NewPD->setAccess(AS);
19554
19555 if (NewPD->isInvalidDecl())
19556 Record->setInvalidDecl();
19557
19558 if (D.getDeclSpec().isModulePrivateSpecified())
19559 NewPD->setModulePrivate();
19560
19561 if (NewPD->isInvalidDecl() && PrevDecl) {
19562 // Don't introduce NewFD into scope; there's already something
19563 // with the same name in the same scope.
19564 } else if (II) {
19565 PushOnScopeChains(D: NewPD, S);
19566 } else
19567 Record->addDecl(D: NewPD);
19568
19569 return NewPD;
19570}
19571
19572void Sema::ActOnStartFunctionDeclarationDeclarator(
19573 Declarator &Declarator, unsigned TemplateParameterDepth) {
19574 auto &Info = InventedParameterInfos.emplace_back();
19575 TemplateParameterList *ExplicitParams = nullptr;
19576 ArrayRef<TemplateParameterList *> ExplicitLists =
19577 Declarator.getTemplateParameterLists();
19578 if (!ExplicitLists.empty()) {
19579 bool IsMemberSpecialization, IsInvalid;
19580 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19581 DeclStartLoc: Declarator.getBeginLoc(), DeclLoc: Declarator.getIdentifierLoc(),
19582 SS: Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19583 ParamLists: ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, Invalid&: IsInvalid,
19584 /*SuppressDiagnostic=*/true);
19585 }
19586 // C++23 [dcl.fct]p23:
19587 // An abbreviated function template can have a template-head. The invented
19588 // template-parameters are appended to the template-parameter-list after
19589 // the explicitly declared template-parameters.
19590 //
19591 // A template-head must have one or more template-parameters (read:
19592 // 'template<>' is *not* a template-head). Only append the invented
19593 // template parameters if we matched the nested-name-specifier to a non-empty
19594 // TemplateParameterList.
19595 if (ExplicitParams && !ExplicitParams->empty()) {
19596 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19597 llvm::append_range(C&: Info.TemplateParams, R&: *ExplicitParams);
19598 Info.NumExplicitTemplateParams = ExplicitParams->size();
19599 } else {
19600 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19601 Info.NumExplicitTemplateParams = 0;
19602 }
19603}
19604
19605void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19606 auto &FSI = InventedParameterInfos.back();
19607 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19608 if (FSI.NumExplicitTemplateParams != 0) {
19609 TemplateParameterList *ExplicitParams =
19610 Declarator.getTemplateParameterLists().back();
19611 Declarator.setInventedTemplateParameterList(
19612 TemplateParameterList::Create(
19613 C: Context, TemplateLoc: ExplicitParams->getTemplateLoc(),
19614 LAngleLoc: ExplicitParams->getLAngleLoc(), Params: FSI.TemplateParams,
19615 RAngleLoc: ExplicitParams->getRAngleLoc(),
19616 RequiresClause: ExplicitParams->getRequiresClause()));
19617 } else {
19618 Declarator.setInventedTemplateParameterList(
19619 TemplateParameterList::Create(
19620 C: Context, TemplateLoc: SourceLocation(), LAngleLoc: SourceLocation(), Params: FSI.TemplateParams,
19621 RAngleLoc: SourceLocation(), /*RequiresClause=*/nullptr));
19622 }
19623 }
19624 InventedParameterInfos.pop_back();
19625}
19626