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(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(DRE->getBeginLoc(),
116 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(DRE->getBeginLoc(),
133 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(ThisE->getBeginLoc(),
145 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(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(&LC))
173 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
174 // Init captures are always VarDecl.
175 auto *D = cast<VarDecl>(Val: LC.getCapturedVar());
176 Invalid |= Visit(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(Self->Context.getCanonicalType(E)).second)
248 Exceptions.push_back(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(Param->getLocation(), Param->getType(),
283 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(EqualLoc, 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(EqualLoc, 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(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(Param->getLocation(), diag::err_param_default_argument_nonfunc)
433 << SR;
434 } else if (Param->getDefaultArg()) {
435 Diag(Param->getLocation(), 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(*this, PrevForDefaultArgs))
473 continue;
474
475 if (S && !isDeclInScope(PrevForDefaultArgs, 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(NewParam->getLocation(), 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(OldParam->getLocation(), 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(NewParam->getLocation(),
588 diag::err_param_default_argument_template_redecl)
589 << NewParam->getDefaultArgRange();
590 Diag(PrevForDefaultArgs->getLocation(),
591 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(NewParam->getLocation(), 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>(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(NewParam->getLocation(),
631 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(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
649 << NewParam->getDefaultArgRange() << NewSM;
650 Diag(Old->getLocation(), 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(New->getLocation(), diag::err_constexpr_redecl_mismatch)
660 << New << static_cast<int>(New->getConstexprKind())
661 << static_cast<int>(Old->getConstexprKind());
662 Diag(Old->getLocation(), 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(New->getLocation(), diag::err_inline_decl_follows_def) << New;
675 Diag(Def->getLocation(), 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(Old)) {
685 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
686 Diag(Old->getLocation(), 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(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
696 Diag(Old->getLocation(), 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, 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(Decomp.getLSquareLoc(), 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(TemplateParamLists.front()->getTemplateLoc(),
742 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(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(BadSpecifierLocs.front(), 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(CPlusPlus20SpecifierLocs.front(),
811 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(DS.getVolatileSpecLoc(),
828 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(Decomp.getLSquareLoc(),
845 (D.hasGroupingParens() ||
846 (D.getNumTypeObjects() &&
847 D.getTypeObject(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(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
870 << TemplRange << FixItHint::CreateRemoval(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(B.NameLoc, Previous.getFoundDecl());
892 Previous.clear();
893 }
894
895 QualType QT;
896 if (B.EllipsisLoc.isValid()) {
897 if (!cast<Decl>(DC)->isTemplated())
898 Diag(B.EllipsisLoc, 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, BD, *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->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(B.NameLoc, diag::err_redefinition) << B.Name;
933 Diag(Old->getLocation(), diag::note_previous_definition);
934 }
935 } else if (ShadowedDecl && !D.isRedeclaration()) {
936 CheckShadow(BD, ShadowedDecl, Previous);
937 }
938 PushOnScopeChains(BD, S, true);
939 Bindings.push_back(Elt: BD);
940 ParsingInitForAutoVars.insert(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(New);
957 CurContext->addHiddenDecl(New);
958 }
959
960 if (OpenMP().isInOpenMPDeclareTargetContext())
961 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, 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(DD->getLocation(), 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 llvm::APSInt(CAT->getSize()),
1060 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(Result, 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, diag::err_std_type_trait_not_class_template) << Trait;
1137 S.Diag(Found->getLocation(), 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, TraitTy, DiagID,
1149 printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1150 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(TraitMemberLookup, 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, diag::err_decomp_decl_std_tuple_size_not_constant)
1205 << printTemplateArgs(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, R, Loc, "tuple_element", Args,
1235 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, diag::err_decomp_decl_std_tuple_element_not_specialized)
1242 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1243 /*Params*/ nullptr);
1244 if (!R.empty())
1245 S.Diag(R.getRepresentativeDecl()->getLocation(), 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(MemberGet, 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>(D->getUnderlyingDecl())) {
1297 TemplateParameterList *TPL = FTD->getTemplateParameters();
1298 if (TPL->size() != 0 &&
1299 isa<NonTypeTemplateParmDecl>(TPL->getParam(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(Src, DecompType, 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(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(CXXScopeSpec(),
1390 DeclarationNameInfo(B->getDeclName(), Loc),
1391 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(const_cast<CXXRecordDecl*>(RD), 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, 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, 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(Loc, BaseType, S.Context.getRecordType(RD),
1456 *BestPath, 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, 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(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, diag::err_decomp_decl_lambda);
1493 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1494 return true;
1495 }
1496
1497 if (FD->isAnonymousStructOrUnion()) {
1498 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1499 << DecompType << FD->getType()->isUnionType();
1500 S.Diag(FD->getLocation(), 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 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1512 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1513 BasePair.getAccess(), 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(Src->getLocation(), DecompType,
1522 diag::err_incomplete_type))
1523 return true;
1524
1525 CXXCastPath BasePath;
1526 DeclAccessPair BasePair =
1527 findDecomposableBaseClass(S, Src->getLocation(), 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(S.Context.getRecordType(Decl: RD),
1532 DecompType.getQualifiers());
1533
1534 auto *DD = cast<DecompositionDecl>(Val: Src);
1535 unsigned NumFields = llvm::count_if(
1536 RD->fields(), [](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, 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(Src, DecompType, VK_LValue, Loc);
1562 if (E.isInvalid())
1563 return true;
1564 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1565 VK_LValue, &BasePath);
1566 if (E.isInvalid())
1567 return true;
1568 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1569 CXXScopeSpec(), FD,
1570 DeclAccessPair::make(FD, FD->getAccess()),
1571 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(S.BuildQualifiedType(FD->getType(), Loc, Q), 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(DecompType)) {
1612 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1613 DD->setInvalidDecl();
1614 return;
1615 }
1616 if (auto *VT = DecompType->getAs<VectorType>()) {
1617 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1618 DD->setInvalidDecl();
1619 return;
1620 }
1621 if (auto *CT = DecompType->getAs<ComplexType>()) {
1622 if (checkComplexDecomposition(*this, Bindings, 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(*this, DD->getLocation(), DecompType, TupleSize)) {
1632 case IsTupleLike::Error:
1633 DD->setInvalidDecl();
1634 return;
1635
1636 case IsTupleLike::TupleLike:
1637 if (checkTupleLikeDecomposition(*this, Bindings, 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(DD->getLocation(), 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(*this, Bindings, DD, DecompType, 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, 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 RD->fields(), [](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 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1744 NewType->getAs<FunctionProtoType>(), 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(Param)))
1782 continue;
1783 if (Param->isInvalidDecl())
1784 /* We already complained about this parameter. */;
1785 else if (Param->getIdentifier())
1786 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1787 << Param->getIdentifier();
1788 else
1789 Diag(Param->getLocation(), 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(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1829 << static_cast<int>(DD->getConstexprKind()) << !FD
1830 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1831 SemaRef.Diag(Loc, 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, ParamLoc, *i,
1863 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1864 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1865 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, FD->getLocation(), FD->getReturnType(),
1878 diag::err_constexpr_non_literal_return,
1879 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(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1923 << isa<CXXConstructorDecl>(NewFD)
1924 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1925 for (const auto &I : RD->vbases())
1926 Diag(I.getBeginLoc(), 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(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1942 } else {
1943 if (Kind == CheckConstexprKind::CheckValid)
1944 return false;
1945
1946 Method = Method->getCanonicalDecl();
1947 Diag(Method->getLocation(), 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(WrittenVirtual->getLocation(),
1956 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(TL.getBeginLoc(), diag::err_constexpr_vla)
2027 << TL.getSourceRange() << TL.getType()
2028 << isa<CXXConstructorDecl>(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(DS->getBeginLoc(),
2041 diag_compat::constexpr_type_definition)
2042 << isa<CXXConstructorDecl>(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(VD->getLocation(),
2067 diag_compat::constexpr_static_var)
2068 << isa<CXXConstructorDecl>(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, VD->getLocation(), VD->getType(),
2076 diag::warn_cxx20_compat_constexpr_var,
2077 isa<CXXConstructorDecl>(Dcl));
2078 } else if (CheckLiteralType(
2079 SemaRef, Kind, VD->getLocation(), VD->getType(),
2080 diag::err_constexpr_local_var_non_literal_type,
2081 isa<CXXConstructorDecl>(Dcl))) {
2082 return false;
2083 }
2084 if (!VD->getType()->isDependentType() &&
2085 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2086 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2087 SemaRef.DiagCompat(VD->getLocation(),
2088 diag_compat::constexpr_local_var_no_init)
2089 << isa<CXXConstructorDecl>(Dcl);
2090 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2091 return false;
2092 }
2093 continue;
2094 }
2095 }
2096 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2097 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2098 << isa<CXXConstructorDecl>(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(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2116 << isa<CXXConstructorDecl>(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(Field)) {
2165 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2166 if (!Diagnosed) {
2167 SemaRef.DiagCompat(Dcl->getLocation(),
2168 diag_compat::constexpr_ctor_missing_init);
2169 Diagnosed = true;
2170 }
2171 SemaRef.Diag(Field->getLocation(),
2172 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(I))
2182 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, 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(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2344 << isa<CXXConstructorDecl>(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(Body->getBeginLoc(),
2380 diag_compat::constexpr_function_try_block)
2381 << isa<CXXConstructorDecl>(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(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2408 << isa<CXXConstructorDecl>(Dcl);
2409 } else if (Cxx2aLoc.isValid()) {
2410 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2411 << isa<CXXConstructorDecl>(Dcl);
2412 } else if (Cxx1yLoc.isValid()) {
2413 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2414 << isa<CXXConstructorDecl>(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(Dcl->getLocation(),
2431 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(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, 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(ReturnStmts.back(),
2495 diag_compat::constexpr_body_multiple_return);
2496 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2497 SemaRef.Diag(ReturnStmts[I],
2498 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(Dcl->getLocation()) ||
2528 SemaRef.getDiagnostics().isIgnored(
2529 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2530 SmallVector<PartialDiagnosticAt, 8> Diags;
2531 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2532 !Expr::isPotentialConstantExpr(FD: Dcl, Diags)) {
2533 SemaRef.Diag(Dcl->getLocation(),
2534 diag::ext_constexpr_function_never_constant_expr)
2535 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2536 << Dcl->getNameInfo().getSourceRange();
2537 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2538 SemaRef.Diag(Diags[I].first, 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(Dcl->getLocation(),
2562 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(FD->getCanonicalDecl());
2576 if (it != UndefinedButUsed.end()) {
2577 Diag(it->second, diag::err_immediate_function_used_before_definition)
2578 << it->first;
2579 Diag(FD->getLocation(), 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, diag::note_immediate_function_reason)
2619 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2620 << isa<CXXConstructorDecl>(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, E->getDirectCallee(), /*IsCall=*/true);
2630 return false;
2631 }
2632
2633 for (Expr *A : E->arguments())
2634 if (!TraverseStmt(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, 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, 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(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(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(EllipsisLoc, 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(BaseLoc, 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(BaseLoc, diag::warn_qual_base_type)
2755 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2756 Diag(BaseLoc, 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(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(BaseLoc, BaseType, diag::err_incomplete_base_class,
2772 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(Class->getLocation(), diag::err_mismatched_code_seg_base);
2789 Diag(BaseDecl->getLocation(), 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(BaseLoc, 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(BaseLoc, diag::err_class_marked_final_used_as_base)
2811 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2812 Diag(BaseDecl->getLocation(), 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(BaseLoc, 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 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2869 << AL << AL.getRange();
2870 else
2871 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2872 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2873 }
2874
2875 TypeSourceInfo *TInfo = nullptr;
2876 GetTypeFromParser(Ty: basetype, TInfo: &TInfo);
2877
2878 if (EllipsisLoc.isInvalid() &&
2879 DiagnoseUnexpandedParameterPack(Loc: SpecifierRange.getBegin(), T: TInfo,
2880 UPPC: UPPC_BaseType))
2881 return true;
2882
2883 // C++ [class.union.general]p4:
2884 // [...] A union shall not have base classes.
2885 if (Class->isUnion()) {
2886 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2887 << SpecifierRange;
2888 return true;
2889 }
2890
2891 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2892 Virtual, Access, TInfo,
2893 EllipsisLoc))
2894 return BaseSpec;
2895
2896 Class->setInvalidDecl();
2897 return true;
2898}
2899
2900/// Use small set to collect indirect bases. As this is only used
2901/// locally, there's no need to abstract the small size parameter.
2902typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2903
2904/// Recursively add the bases of Type. Don't add Type itself.
2905static void
2906NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2907 const QualType &Type)
2908{
2909 // Even though the incoming type is a base, it might not be
2910 // a class -- it could be a template parm, for instance.
2911 if (auto Rec = Type->getAs<RecordType>()) {
2912 auto Decl = Rec->getAsCXXRecordDecl();
2913
2914 // Iterate over its bases.
2915 for (const auto &BaseSpec : Decl->bases()) {
2916 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2917 .getUnqualifiedType();
2918 if (Set.insert(Base).second)
2919 // If we've not already seen it, recurse.
2920 NoteIndirectBases(Context, Set, Base);
2921 }
2922 }
2923}
2924
2925bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2926 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2927 if (Bases.empty())
2928 return false;
2929
2930 // Used to keep track of which base types we have already seen, so
2931 // that we can properly diagnose redundant direct base types. Note
2932 // that the key is always the unqualified canonical type of the base
2933 // class.
2934 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2935
2936 // Used to track indirect bases so we can see if a direct base is
2937 // ambiguous.
2938 IndirectBaseSet IndirectBaseTypes;
2939
2940 // Copy non-redundant base specifiers into permanent storage.
2941 unsigned NumGoodBases = 0;
2942 bool Invalid = false;
2943 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2944 QualType NewBaseType
2945 = Context.getCanonicalType(T: Bases[idx]->getType());
2946 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2947
2948 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2949 if (KnownBase) {
2950 // C++ [class.mi]p3:
2951 // A class shall not be specified as a direct base class of a
2952 // derived class more than once.
2953 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2954 << KnownBase->getType() << Bases[idx]->getSourceRange();
2955
2956 // Delete the duplicate base class specifier; we're going to
2957 // overwrite its pointer later.
2958 Context.Deallocate(Ptr: Bases[idx]);
2959
2960 Invalid = true;
2961 } else {
2962 // Okay, add this new base class.
2963 KnownBase = Bases[idx];
2964 Bases[NumGoodBases++] = Bases[idx];
2965
2966 if (NewBaseType->isDependentType())
2967 continue;
2968 // Note this base's direct & indirect bases, if there could be ambiguity.
2969 if (Bases.size() > 1)
2970 NoteIndirectBases(Context, Set&: IndirectBaseTypes, Type: NewBaseType);
2971
2972 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2973 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: Record->getDecl());
2974 if (Class->isInterface() &&
2975 (!RD->isInterfaceLike() ||
2976 KnownBase->getAccessSpecifier() != AS_public)) {
2977 // The Microsoft extension __interface does not permit bases that
2978 // are not themselves public interfaces.
2979 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2980 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2981 << RD->getSourceRange();
2982 Invalid = true;
2983 }
2984 if (RD->hasAttr<WeakAttr>())
2985 Class->addAttr(WeakAttr::CreateImplicit(Context));
2986 }
2987 }
2988 }
2989
2990 // Attach the remaining base class specifiers to the derived class.
2991 Class->setBases(Bases: Bases.data(), NumBases: NumGoodBases);
2992
2993 // Check that the only base classes that are duplicate are virtual.
2994 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2995 // Check whether this direct base is inaccessible due to ambiguity.
2996 QualType BaseType = Bases[idx]->getType();
2997
2998 // Skip all dependent types in templates being used as base specifiers.
2999 // Checks below assume that the base specifier is a CXXRecord.
3000 if (BaseType->isDependentType())
3001 continue;
3002
3003 CanQualType CanonicalBase = Context.getCanonicalType(T: BaseType)
3004 .getUnqualifiedType();
3005
3006 if (IndirectBaseTypes.count(Ptr: CanonicalBase)) {
3007 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3008 /*DetectVirtual=*/true);
3009 bool found
3010 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3011 assert(found);
3012 (void)found;
3013
3014 if (Paths.isAmbiguous(BaseType: CanonicalBase))
3015 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3016 << BaseType << getAmbiguousPathsDisplayString(Paths)
3017 << Bases[idx]->getSourceRange();
3018 else
3019 assert(Bases[idx]->isVirtual());
3020 }
3021
3022 // Delete the base class specifier, since its data has been copied
3023 // into the CXXRecordDecl.
3024 Context.Deallocate(Ptr: Bases[idx]);
3025 }
3026
3027 return Invalid;
3028}
3029
3030void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3031 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3032 if (!ClassDecl || Bases.empty())
3033 return;
3034
3035 AdjustDeclIfTemplate(Decl&: ClassDecl);
3036 AttachBaseSpecifiers(Class: cast<CXXRecordDecl>(Val: ClassDecl), Bases);
3037}
3038
3039bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3040 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3041 if (!getLangOpts().CPlusPlus)
3042 return false;
3043
3044 if (!Base || !Derived)
3045 return false;
3046
3047 // If either the base or the derived type is invalid, don't try to
3048 // check whether one is derived from the other.
3049 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3050 return false;
3051
3052 // FIXME: In a modules build, do we need the entire path to be visible for us
3053 // to be able to use the inheritance relationship?
3054 if (!isCompleteType(Loc, T: Context.getTypeDeclType(Derived)) &&
3055 !Derived->isBeingDefined())
3056 return false;
3057
3058 return Derived->isDerivedFrom(Base, Paths);
3059}
3060
3061bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3062 CXXRecordDecl *Base) {
3063 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3064 /*DetectVirtual=*/false);
3065 return IsDerivedFrom(Loc, Derived, Base, Paths);
3066}
3067
3068bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3069 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3070 /*DetectVirtual=*/false);
3071 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3072 Base: Base->getAsCXXRecordDecl(), Paths);
3073}
3074
3075bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3076 CXXBasePaths &Paths) {
3077 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3078 Base: Base->getAsCXXRecordDecl(), Paths);
3079}
3080
3081static void BuildBasePathArray(const CXXBasePath &Path,
3082 CXXCastPath &BasePathArray) {
3083 // We first go backward and check if we have a virtual base.
3084 // FIXME: It would be better if CXXBasePath had the base specifier for
3085 // the nearest virtual base.
3086 unsigned Start = 0;
3087 for (unsigned I = Path.size(); I != 0; --I) {
3088 if (Path[I - 1].Base->isVirtual()) {
3089 Start = I - 1;
3090 break;
3091 }
3092 }
3093
3094 // Now add all bases.
3095 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3096 BasePathArray.push_back(Elt: const_cast<CXXBaseSpecifier*>(Path[I].Base));
3097}
3098
3099
3100void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3101 CXXCastPath &BasePathArray) {
3102 assert(BasePathArray.empty() && "Base path array must be empty!");
3103 assert(Paths.isRecordingPaths() && "Must record paths!");
3104 return ::BuildBasePathArray(Path: Paths.front(), BasePathArray);
3105}
3106
3107bool
3108Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3109 unsigned InaccessibleBaseID,
3110 unsigned AmbiguousBaseConvID,
3111 SourceLocation Loc, SourceRange Range,
3112 DeclarationName Name,
3113 CXXCastPath *BasePath,
3114 bool IgnoreAccess) {
3115 // First, determine whether the path from Derived to Base is
3116 // ambiguous. This is slightly more expensive than checking whether
3117 // the Derived to Base conversion exists, because here we need to
3118 // explore multiple paths to determine if there is an ambiguity.
3119 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3120 /*DetectVirtual=*/false);
3121 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3122 if (!DerivationOkay)
3123 return true;
3124
3125 const CXXBasePath *Path = nullptr;
3126 if (!Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: Base).getUnqualifiedType()))
3127 Path = &Paths.front();
3128
3129 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3130 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3131 // user to access such bases.
3132 if (!Path && getLangOpts().MSVCCompat) {
3133 for (const CXXBasePath &PossiblePath : Paths) {
3134 if (PossiblePath.size() == 1) {
3135 Path = &PossiblePath;
3136 if (AmbiguousBaseConvID)
3137 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3138 << Base << Derived << Range;
3139 break;
3140 }
3141 }
3142 }
3143
3144 if (Path) {
3145 if (!IgnoreAccess) {
3146 // Check that the base class can be accessed.
3147 switch (
3148 CheckBaseClassAccess(AccessLoc: Loc, Base, Derived, Path: *Path, DiagID: InaccessibleBaseID)) {
3149 case AR_inaccessible:
3150 return true;
3151 case AR_accessible:
3152 case AR_dependent:
3153 case AR_delayed:
3154 break;
3155 }
3156 }
3157
3158 // Build a base path if necessary.
3159 if (BasePath)
3160 ::BuildBasePathArray(Path: *Path, BasePathArray&: *BasePath);
3161 return false;
3162 }
3163
3164 if (AmbiguousBaseConvID) {
3165 // We know that the derived-to-base conversion is ambiguous, and
3166 // we're going to produce a diagnostic. Perform the derived-to-base
3167 // search just one more time to compute all of the possible paths so
3168 // that we can print them out. This is more expensive than any of
3169 // the previous derived-to-base checks we've done, but at this point
3170 // performance isn't as much of an issue.
3171 Paths.clear();
3172 Paths.setRecordingPaths(true);
3173 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3174 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3175 (void)StillOkay;
3176
3177 // Build up a textual representation of the ambiguous paths, e.g.,
3178 // D -> B -> A, that will be used to illustrate the ambiguous
3179 // conversions in the diagnostic. We only print one of the paths
3180 // to each base class subobject.
3181 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3182
3183 Diag(Loc, AmbiguousBaseConvID)
3184 << Derived << Base << PathDisplayStr << Range << Name;
3185 }
3186 return true;
3187}
3188
3189bool
3190Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3191 SourceLocation Loc, SourceRange Range,
3192 CXXCastPath *BasePath,
3193 bool IgnoreAccess) {
3194 return CheckDerivedToBaseConversion(
3195 Derived, Base, diag::err_upcast_to_inaccessible_base,
3196 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3197 BasePath, IgnoreAccess);
3198}
3199
3200std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3201 std::string PathDisplayStr;
3202 std::set<unsigned> DisplayedPaths;
3203 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3204 Path != Paths.end(); ++Path) {
3205 if (DisplayedPaths.insert(x: Path->back().SubobjectNumber).second) {
3206 // We haven't displayed a path to this particular base
3207 // class subobject yet.
3208 PathDisplayStr += "\n ";
3209 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3210 for (CXXBasePath::const_iterator Element = Path->begin();
3211 Element != Path->end(); ++Element)
3212 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3213 }
3214 }
3215
3216 return PathDisplayStr;
3217}
3218
3219//===----------------------------------------------------------------------===//
3220// C++ class member Handling
3221//===----------------------------------------------------------------------===//
3222
3223bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3224 SourceLocation ColonLoc,
3225 const ParsedAttributesView &Attrs) {
3226 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3227 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(C&: Context, AS: Access, DC: CurContext,
3228 ASLoc, ColonLoc);
3229 CurContext->addHiddenDecl(ASDecl);
3230 return ProcessAccessDeclAttributeList(ASDecl, AttrList: Attrs);
3231}
3232
3233void Sema::CheckOverrideControl(NamedDecl *D) {
3234 if (D->isInvalidDecl())
3235 return;
3236
3237 // We only care about "override" and "final" declarations.
3238 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3239 return;
3240
3241 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3242
3243 // We can't check dependent instance methods.
3244 if (MD && MD->isInstance() &&
3245 (MD->getParent()->hasAnyDependentBases() ||
3246 MD->getType()->isDependentType()))
3247 return;
3248
3249 if (MD && !MD->isVirtual()) {
3250 // If we have a non-virtual method, check if it hides a virtual method.
3251 // (In that case, it's most likely the method has the wrong type.)
3252 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3253 FindHiddenVirtualMethods(MD, OverloadedMethods);
3254
3255 if (!OverloadedMethods.empty()) {
3256 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3257 Diag(OA->getLocation(),
3258 diag::override_keyword_hides_virtual_member_function)
3259 << "override" << (OverloadedMethods.size() > 1);
3260 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3261 Diag(FA->getLocation(),
3262 diag::override_keyword_hides_virtual_member_function)
3263 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3264 << (OverloadedMethods.size() > 1);
3265 }
3266 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3267 MD->setInvalidDecl();
3268 return;
3269 }
3270 // Fall through into the general case diagnostic.
3271 // FIXME: We might want to attempt typo correction here.
3272 }
3273
3274 if (!MD || !MD->isVirtual()) {
3275 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3276 Diag(OA->getLocation(),
3277 diag::override_keyword_only_allowed_on_virtual_member_functions)
3278 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3279 D->dropAttr<OverrideAttr>();
3280 }
3281 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3282 Diag(FA->getLocation(),
3283 diag::override_keyword_only_allowed_on_virtual_member_functions)
3284 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3285 << FixItHint::CreateRemoval(FA->getLocation());
3286 D->dropAttr<FinalAttr>();
3287 }
3288 return;
3289 }
3290
3291 // C++11 [class.virtual]p5:
3292 // If a function is marked with the virt-specifier override and
3293 // does not override a member function of a base class, the program is
3294 // ill-formed.
3295 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3296 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3297 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3298 << MD->getDeclName();
3299}
3300
3301void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3302 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3303 return;
3304 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3305 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3306 return;
3307
3308 SourceLocation Loc = MD->getLocation();
3309 SourceLocation SpellingLoc = Loc;
3310 if (getSourceManager().isMacroArgExpansion(Loc))
3311 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3312 SpellingLoc = getSourceManager().getSpellingLoc(Loc: SpellingLoc);
3313 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(Loc: SpellingLoc))
3314 return;
3315
3316 if (MD->size_overridden_methods() > 0) {
3317 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3318 unsigned DiagID =
3319 Inconsistent && !Diags.isIgnored(DiagID: DiagInconsistent, Loc: MD->getLocation())
3320 ? DiagInconsistent
3321 : DiagSuggest;
3322 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3323 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3324 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3325 };
3326 if (isa<CXXDestructorDecl>(MD))
3327 EmitDiag(
3328 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3329 diag::warn_suggest_destructor_marked_not_override_overriding);
3330 else
3331 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3332 diag::warn_suggest_function_marked_not_override_overriding);
3333 }
3334}
3335
3336bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3337 const CXXMethodDecl *Old) {
3338 FinalAttr *FA = Old->getAttr<FinalAttr>();
3339 if (!FA)
3340 return false;
3341
3342 Diag(New->getLocation(), diag::err_final_function_overridden)
3343 << New->getDeclName()
3344 << FA->isSpelledAsSealed();
3345 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3346 return true;
3347}
3348
3349static bool InitializationHasSideEffects(const FieldDecl &FD) {
3350 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3351 // FIXME: Destruction of ObjC lifetime types has side-effects.
3352 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3353 return !RD->isCompleteDefinition() ||
3354 !RD->hasTrivialDefaultConstructor() ||
3355 !RD->hasTrivialDestructor();
3356 return false;
3357}
3358
3359void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3360 DeclarationName FieldName,
3361 const CXXRecordDecl *RD,
3362 bool DeclIsField) {
3363 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3364 return;
3365
3366 // To record a shadowed field in a base
3367 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3368 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3369 CXXBasePath &Path) {
3370 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3371 // Record an ambiguous path directly
3372 if (Bases.find(x: Base) != Bases.end())
3373 return true;
3374 for (const auto Field : Base->lookup(FieldName)) {
3375 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3376 Field->getAccess() != AS_private) {
3377 assert(Field->getAccess() != AS_none);
3378 assert(Bases.find(Base) == Bases.end());
3379 Bases[Base] = Field;
3380 return true;
3381 }
3382 }
3383 return false;
3384 };
3385
3386 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3387 /*DetectVirtual=*/true);
3388 if (!RD->lookupInBases(BaseMatches: FieldShadowed, Paths))
3389 return;
3390
3391 for (const auto &P : Paths) {
3392 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3393 auto It = Bases.find(x: Base);
3394 // Skip duplicated bases
3395 if (It == Bases.end())
3396 continue;
3397 auto BaseField = It->second;
3398 assert(BaseField->getAccess() != AS_private);
3399 if (AS_none !=
3400 CXXRecordDecl::MergeAccess(PathAccess: P.Access, DeclAccess: BaseField->getAccess())) {
3401 Diag(Loc, diag::warn_shadow_field)
3402 << FieldName << RD << Base << DeclIsField;
3403 Diag(BaseField->getLocation(), diag::note_shadow_field);
3404 Bases.erase(position: It);
3405 }
3406 }
3407}
3408
3409template <typename AttrType>
3410inline static bool HasAttribute(const QualType &T) {
3411 if (const TagDecl *TD = T->getAsTagDecl())
3412 return TD->hasAttr<AttrType>();
3413 if (const TypedefType *TDT = T->getAs<TypedefType>())
3414 return TDT->getDecl()->hasAttr<AttrType>();
3415 return false;
3416}
3417
3418static bool IsUnusedPrivateField(const FieldDecl *FD) {
3419 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3420 QualType FieldType = FD->getType();
3421 if (HasAttribute<WarnUnusedAttr>(FieldType))
3422 return true;
3423
3424 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3425 !FD->getParent()->isDependentContext() &&
3426 !HasAttribute<UnusedAttr>(FieldType) &&
3427 !InitializationHasSideEffects(*FD);
3428 }
3429 return false;
3430}
3431
3432NamedDecl *
3433Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3434 MultiTemplateParamsArg TemplateParameterLists,
3435 Expr *BW, const VirtSpecifiers &VS,
3436 InClassInitStyle InitStyle) {
3437 const DeclSpec &DS = D.getDeclSpec();
3438 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3439 DeclarationName Name = NameInfo.getName();
3440 SourceLocation Loc = NameInfo.getLoc();
3441
3442 // For anonymous bitfields, the location should point to the type.
3443 if (Loc.isInvalid())
3444 Loc = D.getBeginLoc();
3445
3446 Expr *BitWidth = static_cast<Expr*>(BW);
3447
3448 assert(isa<CXXRecordDecl>(CurContext));
3449 assert(!DS.isFriendSpecified());
3450
3451 bool isFunc = D.isDeclarationOfFunction();
3452 const ParsedAttr *MSPropertyAttr =
3453 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3454
3455 if (cast<CXXRecordDecl>(Val: CurContext)->isInterface()) {
3456 // The Microsoft extension __interface only permits public member functions
3457 // and prohibits constructors, destructors, operators, non-public member
3458 // functions, static methods and data members.
3459 unsigned InvalidDecl;
3460 bool ShowDeclName = true;
3461 if (!isFunc &&
3462 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3463 InvalidDecl = 0;
3464 else if (!isFunc)
3465 InvalidDecl = 1;
3466 else if (AS != AS_public)
3467 InvalidDecl = 2;
3468 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3469 InvalidDecl = 3;
3470 else switch (Name.getNameKind()) {
3471 case DeclarationName::CXXConstructorName:
3472 InvalidDecl = 4;
3473 ShowDeclName = false;
3474 break;
3475
3476 case DeclarationName::CXXDestructorName:
3477 InvalidDecl = 5;
3478 ShowDeclName = false;
3479 break;
3480
3481 case DeclarationName::CXXOperatorName:
3482 case DeclarationName::CXXConversionFunctionName:
3483 InvalidDecl = 6;
3484 break;
3485
3486 default:
3487 InvalidDecl = 0;
3488 break;
3489 }
3490
3491 if (InvalidDecl) {
3492 if (ShowDeclName)
3493 Diag(Loc, diag::err_invalid_member_in_interface)
3494 << (InvalidDecl-1) << Name;
3495 else
3496 Diag(Loc, diag::err_invalid_member_in_interface)
3497 << (InvalidDecl-1) << "";
3498 return nullptr;
3499 }
3500 }
3501
3502 // C++ 9.2p6: A member shall not be declared to have automatic storage
3503 // duration (auto, register) or with the extern storage-class-specifier.
3504 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3505 // data members and cannot be applied to names declared const or static,
3506 // and cannot be applied to reference members.
3507 switch (DS.getStorageClassSpec()) {
3508 case DeclSpec::SCS_unspecified:
3509 case DeclSpec::SCS_typedef:
3510 case DeclSpec::SCS_static:
3511 break;
3512 case DeclSpec::SCS_mutable:
3513 if (isFunc) {
3514 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3515
3516 // FIXME: It would be nicer if the keyword was ignored only for this
3517 // declarator. Otherwise we could get follow-up errors.
3518 D.getMutableDeclSpec().ClearStorageClassSpecs();
3519 }
3520 break;
3521 default:
3522 Diag(DS.getStorageClassSpecLoc(),
3523 diag::err_storageclass_invalid_for_member);
3524 D.getMutableDeclSpec().ClearStorageClassSpecs();
3525 break;
3526 }
3527
3528 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3529 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3530 !isFunc && TemplateParameterLists.empty();
3531
3532 if (DS.hasConstexprSpecifier() && isInstField) {
3533 SemaDiagnosticBuilder B =
3534 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3535 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3536 if (InitStyle == ICIS_NoInit) {
3537 B << 0 << 0;
3538 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3539 B << FixItHint::CreateRemoval(RemoveRange: ConstexprLoc);
3540 else {
3541 B << FixItHint::CreateReplacement(RemoveRange: ConstexprLoc, Code: "const");
3542 D.getMutableDeclSpec().ClearConstexprSpec();
3543 const char *PrevSpec;
3544 unsigned DiagID;
3545 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3546 T: DeclSpec::TQ_const, Loc: ConstexprLoc, PrevSpec, DiagID, Lang: getLangOpts());
3547 (void)Failed;
3548 assert(!Failed && "Making a constexpr member const shouldn't fail");
3549 }
3550 } else {
3551 B << 1;
3552 const char *PrevSpec;
3553 unsigned DiagID;
3554 if (D.getMutableDeclSpec().SetStorageClassSpec(
3555 S&: *this, SC: DeclSpec::SCS_static, Loc: ConstexprLoc, PrevSpec, DiagID,
3556 Policy: Context.getPrintingPolicy())) {
3557 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3558 "This is the only DeclSpec that should fail to be applied");
3559 B << 1;
3560 } else {
3561 B << 0 << FixItHint::CreateInsertion(InsertionLoc: ConstexprLoc, Code: "static ");
3562 isInstField = false;
3563 }
3564 }
3565 }
3566
3567 NamedDecl *Member;
3568 if (isInstField) {
3569 CXXScopeSpec &SS = D.getCXXScopeSpec();
3570
3571 // Data members must have identifiers for names.
3572 if (!Name.isIdentifier()) {
3573 Diag(Loc, diag::err_bad_variable_name)
3574 << Name;
3575 return nullptr;
3576 }
3577
3578 IdentifierInfo *II = Name.getAsIdentifierInfo();
3579 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3580 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3581 << II
3582 << SourceRange(D.getName().TemplateId->LAngleLoc,
3583 D.getName().TemplateId->RAngleLoc)
3584 << D.getName().TemplateId->LAngleLoc;
3585 D.SetIdentifier(Id: II, IdLoc: Loc);
3586 }
3587
3588 if (SS.isSet() && !SS.isInvalid()) {
3589 // The user provided a superfluous scope specifier inside a class
3590 // definition:
3591 //
3592 // class X {
3593 // int X::member;
3594 // };
3595 if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) {
3596 TemplateIdAnnotation *TemplateId =
3597 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3598 ? D.getName().TemplateId
3599 : nullptr;
3600 diagnoseQualifiedDeclaration(SS, DC, Name, Loc: D.getIdentifierLoc(),
3601 TemplateId,
3602 /*IsMemberSpecialization=*/false);
3603 } else {
3604 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3605 << Name << SS.getRange();
3606 }
3607 SS.clear();
3608 }
3609
3610 if (MSPropertyAttr) {
3611 Member = HandleMSProperty(S, cast<CXXRecordDecl>(Val: CurContext), Loc, D,
3612 BitWidth, InitStyle, AS, *MSPropertyAttr);
3613 if (!Member)
3614 return nullptr;
3615 isInstField = false;
3616 } else {
3617 Member = HandleField(S, cast<CXXRecordDecl>(Val: CurContext), Loc, D,
3618 BitWidth, InitStyle, AS);
3619 if (!Member)
3620 return nullptr;
3621 }
3622
3623 CheckShadowInheritedFields(Loc, FieldName: Name, RD: cast<CXXRecordDecl>(Val: CurContext));
3624 } else {
3625 Member = HandleDeclarator(S, D, TemplateParameterLists);
3626 if (!Member)
3627 return nullptr;
3628
3629 // Non-instance-fields can't have a bitfield.
3630 if (BitWidth) {
3631 if (Member->isInvalidDecl()) {
3632 // don't emit another diagnostic.
3633 } else if (isa<VarDecl>(Val: Member) || isa<VarTemplateDecl>(Val: Member)) {
3634 // C++ 9.6p3: A bit-field shall not be a static member.
3635 // "static member 'A' cannot be a bit-field"
3636 Diag(Loc, diag::err_static_not_bitfield)
3637 << Name << BitWidth->getSourceRange();
3638 } else if (isa<TypedefDecl>(Val: Member)) {
3639 // "typedef member 'x' cannot be a bit-field"
3640 Diag(Loc, diag::err_typedef_not_bitfield)
3641 << Name << BitWidth->getSourceRange();
3642 } else {
3643 // A function typedef ("typedef int f(); f a;").
3644 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3645 Diag(Loc, diag::err_not_integral_type_bitfield)
3646 << Name << cast<ValueDecl>(Member)->getType()
3647 << BitWidth->getSourceRange();
3648 }
3649
3650 BitWidth = nullptr;
3651 Member->setInvalidDecl();
3652 }
3653
3654 NamedDecl *NonTemplateMember = Member;
3655 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Member))
3656 NonTemplateMember = FunTmpl->getTemplatedDecl();
3657 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Val: Member))
3658 NonTemplateMember = VarTmpl->getTemplatedDecl();
3659
3660 Member->setAccess(AS);
3661
3662 // If we have declared a member function template or static data member
3663 // template, set the access of the templated declaration as well.
3664 if (NonTemplateMember != Member)
3665 NonTemplateMember->setAccess(AS);
3666
3667 // C++ [temp.deduct.guide]p3:
3668 // A deduction guide [...] for a member class template [shall be
3669 // declared] with the same access [as the template].
3670 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: NonTemplateMember)) {
3671 auto *TD = DG->getDeducedTemplate();
3672 // Access specifiers are only meaningful if both the template and the
3673 // deduction guide are from the same scope.
3674 if (AS != TD->getAccess() &&
3675 TD->getDeclContext()->getRedeclContext()->Equals(
3676 DG->getDeclContext()->getRedeclContext())) {
3677 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3678 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3679 << TD->getAccess();
3680 const AccessSpecDecl *LastAccessSpec = nullptr;
3681 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3682 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3683 LastAccessSpec = AccessSpec;
3684 }
3685 assert(LastAccessSpec && "differing access with no access specifier");
3686 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3687 << AS;
3688 }
3689 }
3690 }
3691
3692 if (VS.isOverrideSpecified())
3693 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3694 if (VS.isFinalSpecified())
3695 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3696 VS.isFinalSpelledSealed()
3697 ? FinalAttr::Keyword_sealed
3698 : FinalAttr::Keyword_final));
3699
3700 if (VS.getLastLocation().isValid()) {
3701 // Update the end location of a method that has a virt-specifiers.
3702 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Member))
3703 MD->setRangeEnd(VS.getLastLocation());
3704 }
3705
3706 CheckOverrideControl(D: Member);
3707
3708 assert((Name || isInstField) && "No identifier for non-field ?");
3709
3710 if (isInstField) {
3711 FieldDecl *FD = cast<FieldDecl>(Val: Member);
3712 FieldCollector->Add(D: FD);
3713
3714 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3715 IsUnusedPrivateField(FD)) {
3716 // Remember all explicit private FieldDecls that have a name, no side
3717 // effects and are not part of a dependent type declaration.
3718 UnusedPrivateFields.insert(FD);
3719 }
3720 }
3721
3722 return Member;
3723}
3724
3725namespace {
3726 class UninitializedFieldVisitor
3727 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3728 Sema &S;
3729 // List of Decls to generate a warning on. Also remove Decls that become
3730 // initialized.
3731 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3732 // List of base classes of the record. Classes are removed after their
3733 // initializers.
3734 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3735 // Vector of decls to be removed from the Decl set prior to visiting the
3736 // nodes. These Decls may have been initialized in the prior initializer.
3737 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3738 // If non-null, add a note to the warning pointing back to the constructor.
3739 const CXXConstructorDecl *Constructor;
3740 // Variables to hold state when processing an initializer list. When
3741 // InitList is true, special case initialization of FieldDecls matching
3742 // InitListFieldDecl.
3743 bool InitList;
3744 FieldDecl *InitListFieldDecl;
3745 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3746
3747 public:
3748 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3749 UninitializedFieldVisitor(Sema &S,
3750 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3751 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3752 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3753 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3754
3755 // Returns true if the use of ME is not an uninitialized use.
3756 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3757 bool CheckReferenceOnly) {
3758 llvm::SmallVector<FieldDecl*, 4> Fields;
3759 bool ReferenceField = false;
3760 while (ME) {
3761 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
3762 if (!FD)
3763 return false;
3764 Fields.push_back(Elt: FD);
3765 if (FD->getType()->isReferenceType())
3766 ReferenceField = true;
3767 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParenImpCasts());
3768 }
3769
3770 // Binding a reference to an uninitialized field is not an
3771 // uninitialized use.
3772 if (CheckReferenceOnly && !ReferenceField)
3773 return true;
3774
3775 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3776 // Discard the first field since it is the field decl that is being
3777 // initialized.
3778 for (const FieldDecl *FD : llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Fields)))
3779 UsedFieldIndex.push_back(Elt: FD->getFieldIndex());
3780
3781 for (auto UsedIter = UsedFieldIndex.begin(),
3782 UsedEnd = UsedFieldIndex.end(),
3783 OrigIter = InitFieldIndex.begin(),
3784 OrigEnd = InitFieldIndex.end();
3785 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3786 if (*UsedIter < *OrigIter)
3787 return true;
3788 if (*UsedIter > *OrigIter)
3789 break;
3790 }
3791
3792 return false;
3793 }
3794
3795 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3796 bool AddressOf) {
3797 if (isa<EnumConstantDecl>(Val: ME->getMemberDecl()))
3798 return;
3799
3800 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3801 // or union.
3802 MemberExpr *FieldME = ME;
3803
3804 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3805
3806 Expr *Base = ME;
3807 while (MemberExpr *SubME =
3808 dyn_cast<MemberExpr>(Val: Base->IgnoreParenImpCasts())) {
3809
3810 if (isa<VarDecl>(Val: SubME->getMemberDecl()))
3811 return;
3812
3813 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: SubME->getMemberDecl()))
3814 if (!FD->isAnonymousStructOrUnion())
3815 FieldME = SubME;
3816
3817 if (!FieldME->getType().isPODType(S.Context))
3818 AllPODFields = false;
3819
3820 Base = SubME->getBase();
3821 }
3822
3823 if (!isa<CXXThisExpr>(Val: Base->IgnoreParenImpCasts())) {
3824 Visit(Base);
3825 return;
3826 }
3827
3828 if (AddressOf && AllPODFields)
3829 return;
3830
3831 ValueDecl* FoundVD = FieldME->getMemberDecl();
3832
3833 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Val: Base)) {
3834 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3835 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3836 }
3837
3838 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3839 QualType T = BaseCast->getType();
3840 if (T->isPointerType() &&
3841 BaseClasses.count(Ptr: T->getPointeeType())) {
3842 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3843 << T->getPointeeType() << FoundVD;
3844 }
3845 }
3846 }
3847
3848 if (!Decls.count(Ptr: FoundVD))
3849 return;
3850
3851 const bool IsReference = FoundVD->getType()->isReferenceType();
3852
3853 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3854 // Special checking for initializer lists.
3855 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3856 return;
3857 }
3858 } else {
3859 // Prevent double warnings on use of unbounded references.
3860 if (CheckReferenceOnly && !IsReference)
3861 return;
3862 }
3863
3864 unsigned diag = IsReference
3865 ? diag::warn_reference_field_is_uninit
3866 : diag::warn_field_is_uninit;
3867 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3868 if (Constructor)
3869 S.Diag(Constructor->getLocation(),
3870 diag::note_uninit_in_this_constructor)
3871 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3872
3873 }
3874
3875 void HandleValue(Expr *E, bool AddressOf) {
3876 E = E->IgnoreParens();
3877
3878 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
3879 HandleMemberExpr(ME, CheckReferenceOnly: false /*CheckReferenceOnly*/,
3880 AddressOf /*AddressOf*/);
3881 return;
3882 }
3883
3884 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
3885 Visit(CO->getCond());
3886 HandleValue(E: CO->getTrueExpr(), AddressOf);
3887 HandleValue(E: CO->getFalseExpr(), AddressOf);
3888 return;
3889 }
3890
3891 if (BinaryConditionalOperator *BCO =
3892 dyn_cast<BinaryConditionalOperator>(Val: E)) {
3893 Visit(BCO->getCond());
3894 HandleValue(E: BCO->getFalseExpr(), AddressOf);
3895 return;
3896 }
3897
3898 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
3899 HandleValue(E: OVE->getSourceExpr(), AddressOf);
3900 return;
3901 }
3902
3903 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
3904 switch (BO->getOpcode()) {
3905 default:
3906 break;
3907 case(BO_PtrMemD):
3908 case(BO_PtrMemI):
3909 HandleValue(E: BO->getLHS(), AddressOf);
3910 Visit(BO->getRHS());
3911 return;
3912 case(BO_Comma):
3913 Visit(BO->getLHS());
3914 HandleValue(E: BO->getRHS(), AddressOf);
3915 return;
3916 }
3917 }
3918
3919 Visit(E);
3920 }
3921
3922 void CheckInitListExpr(InitListExpr *ILE) {
3923 InitFieldIndex.push_back(Elt: 0);
3924 for (auto *Child : ILE->children()) {
3925 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Val: Child)) {
3926 CheckInitListExpr(ILE: SubList);
3927 } else {
3928 Visit(S: Child);
3929 }
3930 ++InitFieldIndex.back();
3931 }
3932 InitFieldIndex.pop_back();
3933 }
3934
3935 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3936 FieldDecl *Field, const Type *BaseClass) {
3937 // Remove Decls that may have been initialized in the previous
3938 // initializer.
3939 for (ValueDecl* VD : DeclsToRemove)
3940 Decls.erase(Ptr: VD);
3941 DeclsToRemove.clear();
3942
3943 Constructor = FieldConstructor;
3944 InitListExpr *ILE = dyn_cast<InitListExpr>(Val: E);
3945
3946 if (ILE && Field) {
3947 InitList = true;
3948 InitListFieldDecl = Field;
3949 InitFieldIndex.clear();
3950 CheckInitListExpr(ILE);
3951 } else {
3952 InitList = false;
3953 Visit(E);
3954 }
3955
3956 if (Field)
3957 Decls.erase(Field);
3958 if (BaseClass)
3959 BaseClasses.erase(Ptr: BaseClass->getCanonicalTypeInternal());
3960 }
3961
3962 void VisitMemberExpr(MemberExpr *ME) {
3963 // All uses of unbounded reference fields will warn.
3964 HandleMemberExpr(ME, CheckReferenceOnly: true /*CheckReferenceOnly*/, AddressOf: false /*AddressOf*/);
3965 }
3966
3967 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3968 if (E->getCastKind() == CK_LValueToRValue) {
3969 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
3970 return;
3971 }
3972
3973 Inherited::VisitImplicitCastExpr(E);
3974 }
3975
3976 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3977 if (E->getConstructor()->isCopyConstructor()) {
3978 Expr *ArgExpr = E->getArg(Arg: 0);
3979 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
3980 if (ILE->getNumInits() == 1)
3981 ArgExpr = ILE->getInit(Init: 0);
3982 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
3983 if (ICE->getCastKind() == CK_NoOp)
3984 ArgExpr = ICE->getSubExpr();
3985 HandleValue(E: ArgExpr, AddressOf: false /*AddressOf*/);
3986 return;
3987 }
3988 Inherited::VisitCXXConstructExpr(E);
3989 }
3990
3991 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3992 Expr *Callee = E->getCallee();
3993 if (isa<MemberExpr>(Val: Callee)) {
3994 HandleValue(E: Callee, AddressOf: false /*AddressOf*/);
3995 for (auto *Arg : E->arguments())
3996 Visit(Arg);
3997 return;
3998 }
3999
4000 Inherited::VisitCXXMemberCallExpr(E);
4001 }
4002
4003 void VisitCallExpr(CallExpr *E) {
4004 // Treat std::move as a use.
4005 if (E->isCallToStdMove()) {
4006 HandleValue(E: E->getArg(Arg: 0), /*AddressOf=*/false);
4007 return;
4008 }
4009
4010 Inherited::VisitCallExpr(CE: E);
4011 }
4012
4013 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4014 Expr *Callee = E->getCallee();
4015
4016 if (isa<UnresolvedLookupExpr>(Callee))
4017 return Inherited::VisitCXXOperatorCallExpr(E);
4018
4019 Visit(Callee);
4020 for (auto *Arg : E->arguments())
4021 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4022 }
4023
4024 void VisitBinaryOperator(BinaryOperator *E) {
4025 // If a field assignment is detected, remove the field from the
4026 // uninitiailized field set.
4027 if (E->getOpcode() == BO_Assign)
4028 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getLHS()))
4029 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()))
4030 if (!FD->getType()->isReferenceType())
4031 DeclsToRemove.push_back(FD);
4032
4033 if (E->isCompoundAssignmentOp()) {
4034 HandleValue(E: E->getLHS(), AddressOf: false /*AddressOf*/);
4035 Visit(E->getRHS());
4036 return;
4037 }
4038
4039 Inherited::VisitBinaryOperator(E);
4040 }
4041
4042 void VisitUnaryOperator(UnaryOperator *E) {
4043 if (E->isIncrementDecrementOp()) {
4044 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4045 return;
4046 }
4047 if (E->getOpcode() == UO_AddrOf) {
4048 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getSubExpr())) {
4049 HandleValue(E: ME->getBase(), AddressOf: true /*AddressOf*/);
4050 return;
4051 }
4052 }
4053
4054 Inherited::VisitUnaryOperator(E);
4055 }
4056 };
4057
4058 // Diagnose value-uses of fields to initialize themselves, e.g.
4059 // foo(foo)
4060 // where foo is not also a parameter to the constructor.
4061 // Also diagnose across field uninitialized use such as
4062 // x(y), y(x)
4063 // TODO: implement -Wuninitialized and fold this into that framework.
4064 static void DiagnoseUninitializedFields(
4065 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4066
4067 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4068 Constructor->getLocation())) {
4069 return;
4070 }
4071
4072 if (Constructor->isInvalidDecl())
4073 return;
4074
4075 const CXXRecordDecl *RD = Constructor->getParent();
4076
4077 if (RD->isDependentContext())
4078 return;
4079
4080 // Holds fields that are uninitialized.
4081 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4082
4083 // At the beginning, all fields are uninitialized.
4084 for (auto *I : RD->decls()) {
4085 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4086 UninitializedFields.insert(FD);
4087 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4088 UninitializedFields.insert(IFD->getAnonField());
4089 }
4090 }
4091
4092 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4093 for (const auto &I : RD->bases())
4094 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4095
4096 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4097 return;
4098
4099 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4100 UninitializedFields,
4101 UninitializedBaseClasses);
4102
4103 for (const auto *FieldInit : Constructor->inits()) {
4104 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4105 break;
4106
4107 Expr *InitExpr = FieldInit->getInit();
4108 if (!InitExpr)
4109 continue;
4110
4111 if (CXXDefaultInitExpr *Default =
4112 dyn_cast<CXXDefaultInitExpr>(Val: InitExpr)) {
4113 InitExpr = Default->getExpr();
4114 if (!InitExpr)
4115 continue;
4116 // In class initializers will point to the constructor.
4117 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: Constructor,
4118 Field: FieldInit->getAnyMember(),
4119 BaseClass: FieldInit->getBaseClass());
4120 } else {
4121 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: nullptr,
4122 Field: FieldInit->getAnyMember(),
4123 BaseClass: FieldInit->getBaseClass());
4124 }
4125 }
4126 }
4127} // namespace
4128
4129void Sema::ActOnStartCXXInClassMemberInitializer() {
4130 // Create a synthetic function scope to represent the call to the constructor
4131 // that notionally surrounds a use of this initializer.
4132 PushFunctionScope();
4133}
4134
4135void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4136 if (!D.isFunctionDeclarator())
4137 return;
4138 auto &FTI = D.getFunctionTypeInfo();
4139 if (!FTI.Params)
4140 return;
4141 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4142 FTI.NumParams)) {
4143 auto *ParamDecl = cast<NamedDecl>(Val: Param.Param);
4144 if (ParamDecl->getDeclName())
4145 PushOnScopeChains(D: ParamDecl, S, /*AddToContext=*/false);
4146 }
4147}
4148
4149ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4150 return ActOnRequiresClause(ConstraintExpr);
4151}
4152
4153ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4154 if (ConstraintExpr.isInvalid())
4155 return ExprError();
4156
4157 ConstraintExpr = CorrectDelayedTyposInExpr(ER: ConstraintExpr);
4158 if (ConstraintExpr.isInvalid())
4159 return ExprError();
4160
4161 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr.get(),
4162 UPPC: UPPC_RequiresClause))
4163 return ExprError();
4164
4165 return ConstraintExpr;
4166}
4167
4168ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4169 Expr *InitExpr,
4170 SourceLocation InitLoc) {
4171 InitializedEntity Entity =
4172 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: FD);
4173 InitializationKind Kind =
4174 FD->getInClassInitStyle() == ICIS_ListInit
4175 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4176 InitExpr->getBeginLoc(),
4177 InitExpr->getEndLoc())
4178 : InitializationKind::CreateCopy(InitLoc: InitExpr->getBeginLoc(), EqualLoc: InitLoc);
4179 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4180 return Seq.Perform(S&: *this, Entity, Kind, Args: InitExpr);
4181}
4182
4183void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4184 SourceLocation InitLoc,
4185 ExprResult InitExpr) {
4186 // Pop the notional constructor scope we created earlier.
4187 PopFunctionScopeInfo(WP: nullptr, D);
4188
4189 // Microsoft C++'s property declaration cannot have a default member
4190 // initializer.
4191 if (isa<MSPropertyDecl>(Val: D)) {
4192 D->setInvalidDecl();
4193 return;
4194 }
4195
4196 FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
4197 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4198 "must set init style when field is created");
4199
4200 if (!InitExpr.isUsable() ||
4201 DiagnoseUnexpandedParameterPack(E: InitExpr.get(), UPPC: UPPC_Initializer)) {
4202 FD->setInvalidDecl();
4203 ExprResult RecoveryInit =
4204 CreateRecoveryExpr(Begin: InitLoc, End: InitLoc, SubExprs: {}, T: FD->getType());
4205 if (RecoveryInit.isUsable())
4206 FD->setInClassInitializer(RecoveryInit.get());
4207 return;
4208 }
4209
4210 ExprResult Init = CorrectDelayedTyposInExpr(ER: InitExpr, /*InitDecl=*/nullptr,
4211 /*RecoverUncorrectedTypos=*/true);
4212 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4213 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4214 Init = ConvertMemberDefaultInitExpression(FD, InitExpr: Init.get(), InitLoc);
4215 // C++11 [class.base.init]p7:
4216 // The initialization of each base and member constitutes a
4217 // full-expression.
4218 if (!Init.isInvalid())
4219 Init = ActOnFinishFullExpr(Expr: Init.get(), /*DiscarededValue=*/DiscardedValue: false);
4220 if (Init.isInvalid()) {
4221 FD->setInvalidDecl();
4222 return;
4223 }
4224 }
4225
4226 FD->setInClassInitializer(Init.get());
4227}
4228
4229/// Find the direct and/or virtual base specifiers that
4230/// correspond to the given base type, for use in base initialization
4231/// within a constructor.
4232static bool FindBaseInitializer(Sema &SemaRef,
4233 CXXRecordDecl *ClassDecl,
4234 QualType BaseType,
4235 const CXXBaseSpecifier *&DirectBaseSpec,
4236 const CXXBaseSpecifier *&VirtualBaseSpec) {
4237 // First, check for a direct base class.
4238 DirectBaseSpec = nullptr;
4239 for (const auto &Base : ClassDecl->bases()) {
4240 if (SemaRef.Context.hasSameUnqualifiedType(T1: BaseType, T2: Base.getType())) {
4241 // We found a direct base of this type. That's what we're
4242 // initializing.
4243 DirectBaseSpec = &Base;
4244 break;
4245 }
4246 }
4247
4248 // Check for a virtual base class.
4249 // FIXME: We might be able to short-circuit this if we know in advance that
4250 // there are no virtual bases.
4251 VirtualBaseSpec = nullptr;
4252 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4253 // We haven't found a base yet; search the class hierarchy for a
4254 // virtual base class.
4255 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4256 /*DetectVirtual=*/false);
4257 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4258 SemaRef.Context.getTypeDeclType(ClassDecl),
4259 BaseType, Paths)) {
4260 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4261 Path != Paths.end(); ++Path) {
4262 if (Path->back().Base->isVirtual()) {
4263 VirtualBaseSpec = Path->back().Base;
4264 break;
4265 }
4266 }
4267 }
4268 }
4269
4270 return DirectBaseSpec || VirtualBaseSpec;
4271}
4272
4273MemInitResult
4274Sema::ActOnMemInitializer(Decl *ConstructorD,
4275 Scope *S,
4276 CXXScopeSpec &SS,
4277 IdentifierInfo *MemberOrBase,
4278 ParsedType TemplateTypeTy,
4279 const DeclSpec &DS,
4280 SourceLocation IdLoc,
4281 Expr *InitList,
4282 SourceLocation EllipsisLoc) {
4283 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4284 DS, IdLoc, Init: InitList,
4285 EllipsisLoc);
4286}
4287
4288MemInitResult
4289Sema::ActOnMemInitializer(Decl *ConstructorD,
4290 Scope *S,
4291 CXXScopeSpec &SS,
4292 IdentifierInfo *MemberOrBase,
4293 ParsedType TemplateTypeTy,
4294 const DeclSpec &DS,
4295 SourceLocation IdLoc,
4296 SourceLocation LParenLoc,
4297 ArrayRef<Expr *> Args,
4298 SourceLocation RParenLoc,
4299 SourceLocation EllipsisLoc) {
4300 Expr *List = ParenListExpr::Create(Ctx: Context, LParenLoc, Exprs: Args, RParenLoc);
4301 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4302 DS, IdLoc, Init: List, EllipsisLoc);
4303}
4304
4305namespace {
4306
4307// Callback to only accept typo corrections that can be a valid C++ member
4308// initializer: either a non-static field member or a base class.
4309class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4310public:
4311 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4312 : ClassDecl(ClassDecl) {}
4313
4314 bool ValidateCandidate(const TypoCorrection &candidate) override {
4315 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4316 if (FieldDecl *Member = dyn_cast<FieldDecl>(Val: ND))
4317 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4318 return isa<TypeDecl>(Val: ND);
4319 }
4320 return false;
4321 }
4322
4323 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4324 return std::make_unique<MemInitializerValidatorCCC>(args&: *this);
4325 }
4326
4327private:
4328 CXXRecordDecl *ClassDecl;
4329};
4330
4331}
4332
4333bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4334 RecordDecl *ClassDecl,
4335 const IdentifierInfo *Name) {
4336 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4337 DeclContextLookupResult::iterator Found =
4338 llvm::find_if(Range&: Result, P: [this](const NamedDecl *Elem) {
4339 return isa<FieldDecl, IndirectFieldDecl>(Val: Elem) &&
4340 Elem->isPlaceholderVar(LangOpts: getLangOpts());
4341 });
4342 // We did not find a placeholder variable
4343 if (Found == Result.end())
4344 return false;
4345 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4346 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4347 const NamedDecl *ND = *It;
4348 if (ND->getDeclContext() != ND->getDeclContext())
4349 break;
4350 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4351 ND->isPlaceholderVar(getLangOpts()))
4352 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4353 }
4354 return true;
4355}
4356
4357ValueDecl *
4358Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4359 const IdentifierInfo *MemberOrBase) {
4360 ValueDecl *ND = nullptr;
4361 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4362 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4363 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4364 if (ND) {
4365 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4366 return nullptr;
4367 break;
4368 }
4369 if (!IsPlaceholder)
4370 return cast<ValueDecl>(D);
4371 ND = cast<ValueDecl>(D);
4372 }
4373 }
4374 return ND;
4375}
4376
4377ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4378 CXXScopeSpec &SS,
4379 ParsedType TemplateTypeTy,
4380 IdentifierInfo *MemberOrBase) {
4381 if (SS.getScopeRep() || TemplateTypeTy)
4382 return nullptr;
4383 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4384}
4385
4386MemInitResult
4387Sema::BuildMemInitializer(Decl *ConstructorD,
4388 Scope *S,
4389 CXXScopeSpec &SS,
4390 IdentifierInfo *MemberOrBase,
4391 ParsedType TemplateTypeTy,
4392 const DeclSpec &DS,
4393 SourceLocation IdLoc,
4394 Expr *Init,
4395 SourceLocation EllipsisLoc) {
4396 ExprResult Res = CorrectDelayedTyposInExpr(E: Init, /*InitDecl=*/nullptr,
4397 /*RecoverUncorrectedTypos=*/true);
4398 if (!Res.isUsable())
4399 return true;
4400 Init = Res.get();
4401
4402 if (!ConstructorD)
4403 return true;
4404
4405 AdjustDeclIfTemplate(Decl&: ConstructorD);
4406
4407 CXXConstructorDecl *Constructor
4408 = dyn_cast<CXXConstructorDecl>(Val: ConstructorD);
4409 if (!Constructor) {
4410 // The user wrote a constructor initializer on a function that is
4411 // not a C++ constructor. Ignore the error for now, because we may
4412 // have more member initializers coming; we'll diagnose it just
4413 // once in ActOnMemInitializers.
4414 return true;
4415 }
4416
4417 CXXRecordDecl *ClassDecl = Constructor->getParent();
4418
4419 // C++ [class.base.init]p2:
4420 // Names in a mem-initializer-id are looked up in the scope of the
4421 // constructor's class and, if not found in that scope, are looked
4422 // up in the scope containing the constructor's definition.
4423 // [Note: if the constructor's class contains a member with the
4424 // same name as a direct or virtual base class of the class, a
4425 // mem-initializer-id naming the member or base class and composed
4426 // of a single identifier refers to the class member. A
4427 // mem-initializer-id for the hidden base class may be specified
4428 // using a qualified name. ]
4429
4430 // Look for a member, first.
4431 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4432 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4433 if (EllipsisLoc.isValid())
4434 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4435 << MemberOrBase
4436 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4437
4438 return BuildMemberInitializer(Member, Init, IdLoc);
4439 }
4440 // It didn't name a member, so see if it names a class.
4441 QualType BaseType;
4442 TypeSourceInfo *TInfo = nullptr;
4443
4444 if (TemplateTypeTy) {
4445 BaseType = GetTypeFromParser(Ty: TemplateTypeTy, TInfo: &TInfo);
4446 if (BaseType.isNull())
4447 return true;
4448 } else if (DS.getTypeSpecType() == TST_decltype) {
4449 BaseType = BuildDecltypeType(E: DS.getRepAsExpr());
4450 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4451 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4452 return true;
4453 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4454 BaseType =
4455 BuildPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(),
4456 Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc());
4457 } else {
4458 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4459 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
4460
4461 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4462 if (!TyD) {
4463 if (R.isAmbiguous()) return true;
4464
4465 // We don't want access-control diagnostics here.
4466 R.suppressDiagnostics();
4467
4468 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4469 bool NotUnknownSpecialization = false;
4470 DeclContext *DC = computeDeclContext(SS, EnteringContext: false);
4471 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Val: DC))
4472 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4473
4474 if (!NotUnknownSpecialization) {
4475 // When the scope specifier can refer to a member of an unknown
4476 // specialization, we take it as a type name.
4477 BaseType = CheckTypenameType(
4478 Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(),
4479 QualifierLoc: SS.getWithLocInContext(Context), II: *MemberOrBase, IILoc: IdLoc);
4480 if (BaseType.isNull())
4481 return true;
4482
4483 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4484 DependentNameTypeLoc TL =
4485 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4486 if (!TL.isNull()) {
4487 TL.setNameLoc(IdLoc);
4488 TL.setElaboratedKeywordLoc(SourceLocation());
4489 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4490 }
4491
4492 R.clear();
4493 R.setLookupName(MemberOrBase);
4494 }
4495 }
4496
4497 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4498 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4499 auto *TempSpec = cast<TemplateSpecializationType>(
4500 Val: UnqualifiedBase->getInjectedClassNameSpecialization());
4501 TemplateName TN = TempSpec->getTemplateName();
4502 for (auto const &Base : ClassDecl->bases()) {
4503 auto BaseTemplate =
4504 Base.getType()->getAs<TemplateSpecializationType>();
4505 if (BaseTemplate &&
4506 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4507 /*IgnoreDeduced=*/true)) {
4508 Diag(IdLoc, diag::ext_unqualified_base_class)
4509 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4510 BaseType = Base.getType();
4511 break;
4512 }
4513 }
4514 }
4515 }
4516
4517 // If no results were found, try to correct typos.
4518 TypoCorrection Corr;
4519 MemInitializerValidatorCCC CCC(ClassDecl);
4520 if (R.empty() && BaseType.isNull() &&
4521 (Corr =
4522 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4523 CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {
4524 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4525 // We have found a non-static data member with a similar
4526 // name to what was typed; complain and initialize that
4527 // member.
4528 diagnoseTypo(Corr,
4529 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4530 << MemberOrBase << true);
4531 return BuildMemberInitializer(Member, Init, IdLoc);
4532 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4533 const CXXBaseSpecifier *DirectBaseSpec;
4534 const CXXBaseSpecifier *VirtualBaseSpec;
4535 if (FindBaseInitializer(SemaRef&: *this, ClassDecl,
4536 BaseType: Context.getTypeDeclType(Decl: Type),
4537 DirectBaseSpec, VirtualBaseSpec)) {
4538 // We have found a direct or virtual base class with a
4539 // similar name to what was typed; complain and initialize
4540 // that base class.
4541 diagnoseTypo(Corr,
4542 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4543 << MemberOrBase << false,
4544 PDiag() /*Suppress note, we provide our own.*/);
4545
4546 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4547 : VirtualBaseSpec;
4548 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4549 << BaseSpec->getType() << BaseSpec->getSourceRange();
4550
4551 TyD = Type;
4552 }
4553 }
4554 }
4555
4556 if (!TyD && BaseType.isNull()) {
4557 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4558 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4559 return true;
4560 }
4561 }
4562
4563 if (BaseType.isNull()) {
4564 BaseType = getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS,
4565 T: Context.getTypeDeclType(Decl: TyD));
4566 MarkAnyDeclReferenced(Loc: TyD->getLocation(), D: TyD, /*OdrUse=*/MightBeOdrUse: false);
4567 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4568 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4569 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4570 TL.setElaboratedKeywordLoc(SourceLocation());
4571 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4572 }
4573 }
4574
4575 if (!TInfo)
4576 TInfo = Context.getTrivialTypeSourceInfo(T: BaseType, Loc: IdLoc);
4577
4578 return BuildBaseInitializer(BaseType, BaseTInfo: TInfo, Init, ClassDecl, EllipsisLoc);
4579}
4580
4581MemInitResult
4582Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4583 SourceLocation IdLoc) {
4584 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Val: Member);
4585 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Val: Member);
4586 assert((DirectMember || IndirectMember) &&
4587 "Member must be a FieldDecl or IndirectFieldDecl");
4588
4589 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4590 return true;
4591
4592 if (Member->isInvalidDecl())
4593 return true;
4594
4595 MultiExprArg Args;
4596 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4597 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4598 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
4599 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4600 } else {
4601 // Template instantiation doesn't reconstruct ParenListExprs for us.
4602 Args = Init;
4603 }
4604
4605 SourceRange InitRange = Init->getSourceRange();
4606
4607 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4608 // Can't check initialization for a member of dependent type or when
4609 // any of the arguments are type-dependent expressions.
4610 DiscardCleanupsInEvaluationContext();
4611 } else {
4612 bool InitList = false;
4613 if (isa<InitListExpr>(Val: Init)) {
4614 InitList = true;
4615 Args = Init;
4616 }
4617
4618 // Initialize the member.
4619 InitializedEntity MemberEntity =
4620 DirectMember ? InitializedEntity::InitializeMember(Member: DirectMember, Parent: nullptr)
4621 : InitializedEntity::InitializeMember(Member: IndirectMember,
4622 Parent: nullptr);
4623 InitializationKind Kind =
4624 InitList ? InitializationKind::CreateDirectList(
4625 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4626 : InitializationKind::CreateDirect(InitLoc: IdLoc, LParenLoc: InitRange.getBegin(),
4627 RParenLoc: InitRange.getEnd());
4628
4629 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4630 ExprResult MemberInit = InitSeq.Perform(S&: *this, Entity: MemberEntity, Kind, Args,
4631 ResultType: nullptr);
4632 if (!MemberInit.isInvalid()) {
4633 // C++11 [class.base.init]p7:
4634 // The initialization of each base and member constitutes a
4635 // full-expression.
4636 MemberInit = ActOnFinishFullExpr(Expr: MemberInit.get(), CC: InitRange.getBegin(),
4637 /*DiscardedValue*/ false);
4638 }
4639
4640 if (MemberInit.isInvalid()) {
4641 // Args were sensible expressions but we couldn't initialize the member
4642 // from them. Preserve them in a RecoveryExpr instead.
4643 Init = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4644 T: Member->getType())
4645 .get();
4646 if (!Init)
4647 return true;
4648 } else {
4649 Init = MemberInit.get();
4650 }
4651 }
4652
4653 if (DirectMember) {
4654 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4655 InitRange.getBegin(), Init,
4656 InitRange.getEnd());
4657 } else {
4658 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4659 InitRange.getBegin(), Init,
4660 InitRange.getEnd());
4661 }
4662}
4663
4664MemInitResult
4665Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4666 CXXRecordDecl *ClassDecl) {
4667 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4668 if (!LangOpts.CPlusPlus11)
4669 return Diag(NameLoc, diag::err_delegating_ctor)
4670 << TInfo->getTypeLoc().getSourceRange();
4671 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4672
4673 bool InitList = true;
4674 MultiExprArg Args = Init;
4675 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4676 InitList = false;
4677 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4678 }
4679
4680 SourceRange InitRange = Init->getSourceRange();
4681 // Initialize the object.
4682 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4683 Type: QualType(ClassDecl->getTypeForDecl(), 0));
4684 InitializationKind Kind =
4685 InitList ? InitializationKind::CreateDirectList(
4686 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4687 : InitializationKind::CreateDirect(InitLoc: NameLoc, LParenLoc: InitRange.getBegin(),
4688 RParenLoc: InitRange.getEnd());
4689 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4690 ExprResult DelegationInit = InitSeq.Perform(S&: *this, Entity: DelegationEntity, Kind,
4691 Args, ResultType: nullptr);
4692 if (!DelegationInit.isInvalid()) {
4693 assert((DelegationInit.get()->containsErrors() ||
4694 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4695 "Delegating constructor with no target?");
4696
4697 // C++11 [class.base.init]p7:
4698 // The initialization of each base and member constitutes a
4699 // full-expression.
4700 DelegationInit = ActOnFinishFullExpr(
4701 Expr: DelegationInit.get(), CC: InitRange.getBegin(), /*DiscardedValue*/ false);
4702 }
4703
4704 if (DelegationInit.isInvalid()) {
4705 DelegationInit =
4706 CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4707 T: QualType(ClassDecl->getTypeForDecl(), 0));
4708 if (DelegationInit.isInvalid())
4709 return true;
4710 } else {
4711 // If we are in a dependent context, template instantiation will
4712 // perform this type-checking again. Just save the arguments that we
4713 // received in a ParenListExpr.
4714 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4715 // of the information that we have about the base
4716 // initializer. However, deconstructing the ASTs is a dicey process,
4717 // and this approach is far more likely to get the corner cases right.
4718 if (CurContext->isDependentContext())
4719 DelegationInit = Init;
4720 }
4721
4722 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4723 DelegationInit.getAs<Expr>(),
4724 InitRange.getEnd());
4725}
4726
4727MemInitResult
4728Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4729 Expr *Init, CXXRecordDecl *ClassDecl,
4730 SourceLocation EllipsisLoc) {
4731 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4732
4733 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4734 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4735 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4736
4737 // C++ [class.base.init]p2:
4738 // [...] Unless the mem-initializer-id names a nonstatic data
4739 // member of the constructor's class or a direct or virtual base
4740 // of that class, the mem-initializer is ill-formed. A
4741 // mem-initializer-list can initialize a base class using any
4742 // name that denotes that base class type.
4743
4744 // We can store the initializers in "as-written" form and delay analysis until
4745 // instantiation if the constructor is dependent. But not for dependent
4746 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4747 bool Dependent = CurContext->isDependentContext() &&
4748 (BaseType->isDependentType() || Init->isTypeDependent());
4749
4750 SourceRange InitRange = Init->getSourceRange();
4751 if (EllipsisLoc.isValid()) {
4752 // This is a pack expansion.
4753 if (!BaseType->containsUnexpandedParameterPack()) {
4754 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4755 << SourceRange(BaseLoc, InitRange.getEnd());
4756
4757 EllipsisLoc = SourceLocation();
4758 }
4759 } else {
4760 // Check for any unexpanded parameter packs.
4761 if (DiagnoseUnexpandedParameterPack(Loc: BaseLoc, T: BaseTInfo, UPPC: UPPC_Initializer))
4762 return true;
4763
4764 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4765 return true;
4766 }
4767
4768 // Check for direct and virtual base classes.
4769 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4770 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4771 if (!Dependent) {
4772 if (Context.hasSameUnqualifiedType(T1: QualType(ClassDecl->getTypeForDecl(),0),
4773 T2: BaseType))
4774 return BuildDelegatingInitializer(TInfo: BaseTInfo, Init, ClassDecl);
4775
4776 FindBaseInitializer(SemaRef&: *this, ClassDecl, BaseType, DirectBaseSpec,
4777 VirtualBaseSpec);
4778
4779 // C++ [base.class.init]p2:
4780 // Unless the mem-initializer-id names a nonstatic data member of the
4781 // constructor's class or a direct or virtual base of that class, the
4782 // mem-initializer is ill-formed.
4783 if (!DirectBaseSpec && !VirtualBaseSpec) {
4784 // If the class has any dependent bases, then it's possible that
4785 // one of those types will resolve to the same type as
4786 // BaseType. Therefore, just treat this as a dependent base
4787 // class initialization. FIXME: Should we try to check the
4788 // initialization anyway? It seems odd.
4789 if (ClassDecl->hasAnyDependentBases())
4790 Dependent = true;
4791 else
4792 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4793 << BaseType << Context.getTypeDeclType(ClassDecl)
4794 << BaseTInfo->getTypeLoc().getSourceRange();
4795 }
4796 }
4797
4798 if (Dependent) {
4799 DiscardCleanupsInEvaluationContext();
4800
4801 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4802 /*IsVirtual=*/false,
4803 InitRange.getBegin(), Init,
4804 InitRange.getEnd(), EllipsisLoc);
4805 }
4806
4807 // C++ [base.class.init]p2:
4808 // If a mem-initializer-id is ambiguous because it designates both
4809 // a direct non-virtual base class and an inherited virtual base
4810 // class, the mem-initializer is ill-formed.
4811 if (DirectBaseSpec && VirtualBaseSpec)
4812 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4813 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4814
4815 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4816 if (!BaseSpec)
4817 BaseSpec = VirtualBaseSpec;
4818
4819 // Initialize the base.
4820 bool InitList = true;
4821 MultiExprArg Args = Init;
4822 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4823 InitList = false;
4824 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4825 }
4826
4827 InitializedEntity BaseEntity =
4828 InitializedEntity::InitializeBase(Context, Base: BaseSpec, IsInheritedVirtualBase: VirtualBaseSpec);
4829 InitializationKind Kind =
4830 InitList ? InitializationKind::CreateDirectList(InitLoc: BaseLoc)
4831 : InitializationKind::CreateDirect(InitLoc: BaseLoc, LParenLoc: InitRange.getBegin(),
4832 RParenLoc: InitRange.getEnd());
4833 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4834 ExprResult BaseInit = InitSeq.Perform(S&: *this, Entity: BaseEntity, Kind, Args, ResultType: nullptr);
4835 if (!BaseInit.isInvalid()) {
4836 // C++11 [class.base.init]p7:
4837 // The initialization of each base and member constitutes a
4838 // full-expression.
4839 BaseInit = ActOnFinishFullExpr(Expr: BaseInit.get(), CC: InitRange.getBegin(),
4840 /*DiscardedValue*/ false);
4841 }
4842
4843 if (BaseInit.isInvalid()) {
4844 BaseInit = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(),
4845 SubExprs: Args, T: BaseType);
4846 if (BaseInit.isInvalid())
4847 return true;
4848 } else {
4849 // If we are in a dependent context, template instantiation will
4850 // perform this type-checking again. Just save the arguments that we
4851 // received in a ParenListExpr.
4852 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4853 // of the information that we have about the base
4854 // initializer. However, deconstructing the ASTs is a dicey process,
4855 // and this approach is far more likely to get the corner cases right.
4856 if (CurContext->isDependentContext())
4857 BaseInit = Init;
4858 }
4859
4860 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4861 BaseSpec->isVirtual(),
4862 InitRange.getBegin(),
4863 BaseInit.getAs<Expr>(),
4864 InitRange.getEnd(), EllipsisLoc);
4865}
4866
4867// Create a static_cast\<T&&>(expr).
4868static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4869 QualType TargetType =
4870 SemaRef.BuildReferenceType(T: E->getType(), /*SpelledAsLValue*/ LValueRef: false,
4871 Loc: SourceLocation(), Entity: DeclarationName());
4872 SourceLocation ExprLoc = E->getBeginLoc();
4873 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4874 T: TargetType, Loc: ExprLoc);
4875
4876 return SemaRef.BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
4877 AngleBrackets: SourceRange(ExprLoc, ExprLoc),
4878 Parens: E->getSourceRange()).get();
4879}
4880
4881/// ImplicitInitializerKind - How an implicit base or member initializer should
4882/// initialize its base or member.
4883enum ImplicitInitializerKind {
4884 IIK_Default,
4885 IIK_Copy,
4886 IIK_Move,
4887 IIK_Inherit
4888};
4889
4890static bool
4891BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4892 ImplicitInitializerKind ImplicitInitKind,
4893 CXXBaseSpecifier *BaseSpec,
4894 bool IsInheritedVirtualBase,
4895 CXXCtorInitializer *&CXXBaseInit) {
4896 InitializedEntity InitEntity
4897 = InitializedEntity::InitializeBase(Context&: SemaRef.Context, Base: BaseSpec,
4898 IsInheritedVirtualBase);
4899
4900 ExprResult BaseInit;
4901
4902 switch (ImplicitInitKind) {
4903 case IIK_Inherit:
4904 case IIK_Default: {
4905 InitializationKind InitKind
4906 = InitializationKind::CreateDefault(InitLoc: Constructor->getLocation());
4907 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4908 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
4909 break;
4910 }
4911
4912 case IIK_Move:
4913 case IIK_Copy: {
4914 bool Moving = ImplicitInitKind == IIK_Move;
4915 ParmVarDecl *Param = Constructor->getParamDecl(0);
4916 QualType ParamType = Param->getType().getNonReferenceType();
4917
4918 Expr *CopyCtorArg =
4919 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4920 SourceLocation(), Param, false,
4921 Constructor->getLocation(), ParamType,
4922 VK_LValue, nullptr);
4923
4924 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: CopyCtorArg));
4925
4926 // Cast to the base class to avoid ambiguities.
4927 QualType ArgTy =
4928 SemaRef.Context.getQualifiedType(T: BaseSpec->getType().getUnqualifiedType(),
4929 Qs: ParamType.getQualifiers());
4930
4931 if (Moving) {
4932 CopyCtorArg = CastForMoving(SemaRef, E: CopyCtorArg);
4933 }
4934
4935 CXXCastPath BasePath;
4936 BasePath.push_back(Elt: BaseSpec);
4937 CopyCtorArg = SemaRef.ImpCastExprToType(E: CopyCtorArg, Type: ArgTy,
4938 CK: CK_UncheckedDerivedToBase,
4939 VK: Moving ? VK_XValue : VK_LValue,
4940 BasePath: &BasePath).get();
4941
4942 InitializationKind InitKind
4943 = InitializationKind::CreateDirect(InitLoc: Constructor->getLocation(),
4944 LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
4945 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4946 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: CopyCtorArg);
4947 break;
4948 }
4949 }
4950
4951 BaseInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: BaseInit);
4952 if (BaseInit.isInvalid())
4953 return true;
4954
4955 CXXBaseInit =
4956 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4957 SemaRef.Context.getTrivialTypeSourceInfo(T: BaseSpec->getType(),
4958 Loc: SourceLocation()),
4959 BaseSpec->isVirtual(),
4960 SourceLocation(),
4961 BaseInit.getAs<Expr>(),
4962 SourceLocation(),
4963 SourceLocation());
4964
4965 return false;
4966}
4967
4968static bool RefersToRValueRef(Expr *MemRef) {
4969 ValueDecl *Referenced = cast<MemberExpr>(Val: MemRef)->getMemberDecl();
4970 return Referenced->getType()->isRValueReferenceType();
4971}
4972
4973static bool
4974BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4975 ImplicitInitializerKind ImplicitInitKind,
4976 FieldDecl *Field, IndirectFieldDecl *Indirect,
4977 CXXCtorInitializer *&CXXMemberInit) {
4978 if (Field->isInvalidDecl())
4979 return true;
4980
4981 SourceLocation Loc = Constructor->getLocation();
4982
4983 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4984 bool Moving = ImplicitInitKind == IIK_Move;
4985 ParmVarDecl *Param = Constructor->getParamDecl(0);
4986 QualType ParamType = Param->getType().getNonReferenceType();
4987
4988 // Suppress copying zero-width bitfields.
4989 if (Field->isZeroLengthBitField())
4990 return false;
4991
4992 Expr *MemberExprBase =
4993 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4994 SourceLocation(), Param, false,
4995 Loc, ParamType, VK_LValue, nullptr);
4996
4997 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: MemberExprBase));
4998
4999 if (Moving) {
5000 MemberExprBase = CastForMoving(SemaRef, E: MemberExprBase);
5001 }
5002
5003 // Build a reference to this field within the parameter.
5004 CXXScopeSpec SS;
5005 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5006 Sema::LookupMemberName);
5007 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Val: Indirect)
5008 : cast<ValueDecl>(Val: Field), AS_public);
5009 MemberLookup.resolveKind();
5010 ExprResult CtorArg
5011 = SemaRef.BuildMemberReferenceExpr(Base: MemberExprBase,
5012 BaseType: ParamType, OpLoc: Loc,
5013 /*IsArrow=*/false,
5014 SS,
5015 /*TemplateKWLoc=*/SourceLocation(),
5016 /*FirstQualifierInScope=*/nullptr,
5017 R&: MemberLookup,
5018 /*TemplateArgs=*/nullptr,
5019 /*S*/nullptr);
5020 if (CtorArg.isInvalid())
5021 return true;
5022
5023 // C++11 [class.copy]p15:
5024 // - if a member m has rvalue reference type T&&, it is direct-initialized
5025 // with static_cast<T&&>(x.m);
5026 if (RefersToRValueRef(MemRef: CtorArg.get())) {
5027 CtorArg = CastForMoving(SemaRef, E: CtorArg.get());
5028 }
5029
5030 InitializedEntity Entity =
5031 Indirect ? InitializedEntity::InitializeMember(Member: Indirect, Parent: nullptr,
5032 /*Implicit*/ true)
5033 : InitializedEntity::InitializeMember(Member: Field, Parent: nullptr,
5034 /*Implicit*/ true);
5035
5036 // Direct-initialize to use the copy constructor.
5037 InitializationKind InitKind =
5038 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5039
5040 Expr *CtorArgE = CtorArg.getAs<Expr>();
5041 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5042 ExprResult MemberInit =
5043 InitSeq.Perform(S&: SemaRef, Entity, Kind: InitKind, Args: MultiExprArg(&CtorArgE, 1));
5044 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5045 if (MemberInit.isInvalid())
5046 return true;
5047
5048 if (Indirect)
5049 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5050 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5051 else
5052 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5053 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5054 return false;
5055 }
5056
5057 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5058 "Unhandled implicit init kind!");
5059
5060 QualType FieldBaseElementType =
5061 SemaRef.Context.getBaseElementType(Field->getType());
5062
5063 if (FieldBaseElementType->isRecordType()) {
5064 InitializedEntity InitEntity =
5065 Indirect ? InitializedEntity::InitializeMember(Member: Indirect, Parent: nullptr,
5066 /*Implicit*/ true)
5067 : InitializedEntity::InitializeMember(Member: Field, Parent: nullptr,
5068 /*Implicit*/ true);
5069 InitializationKind InitKind =
5070 InitializationKind::CreateDefault(InitLoc: Loc);
5071
5072 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5073 ExprResult MemberInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5074
5075 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5076 if (MemberInit.isInvalid())
5077 return true;
5078
5079 if (Indirect)
5080 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5081 Indirect, Loc,
5082 Loc,
5083 MemberInit.get(),
5084 Loc);
5085 else
5086 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5087 Field, Loc, Loc,
5088 MemberInit.get(),
5089 Loc);
5090 return false;
5091 }
5092
5093 if (!Field->getParent()->isUnion()) {
5094 if (FieldBaseElementType->isReferenceType()) {
5095 SemaRef.Diag(Constructor->getLocation(),
5096 diag::err_uninitialized_member_in_ctor)
5097 << (int)Constructor->isImplicit()
5098 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5099 << 0 << Field->getDeclName();
5100 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5101 return true;
5102 }
5103
5104 if (FieldBaseElementType.isConstQualified()) {
5105 SemaRef.Diag(Constructor->getLocation(),
5106 diag::err_uninitialized_member_in_ctor)
5107 << (int)Constructor->isImplicit()
5108 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5109 << 1 << Field->getDeclName();
5110 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5111 return true;
5112 }
5113 }
5114
5115 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5116 // ARC and Weak:
5117 // Default-initialize Objective-C pointers to NULL.
5118 CXXMemberInit
5119 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5120 Loc, Loc,
5121 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5122 Loc);
5123 return false;
5124 }
5125
5126 // Nothing to initialize.
5127 CXXMemberInit = nullptr;
5128 return false;
5129}
5130
5131namespace {
5132struct BaseAndFieldInfo {
5133 Sema &S;
5134 CXXConstructorDecl *Ctor;
5135 bool AnyErrorsInInits;
5136 ImplicitInitializerKind IIK;
5137 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5138 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5139 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5140
5141 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5142 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5143 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5144 if (Ctor->getInheritedConstructor())
5145 IIK = IIK_Inherit;
5146 else if (Generated && Ctor->isCopyConstructor())
5147 IIK = IIK_Copy;
5148 else if (Generated && Ctor->isMoveConstructor())
5149 IIK = IIK_Move;
5150 else
5151 IIK = IIK_Default;
5152 }
5153
5154 bool isImplicitCopyOrMove() const {
5155 switch (IIK) {
5156 case IIK_Copy:
5157 case IIK_Move:
5158 return true;
5159
5160 case IIK_Default:
5161 case IIK_Inherit:
5162 return false;
5163 }
5164
5165 llvm_unreachable("Invalid ImplicitInitializerKind!");
5166 }
5167
5168 bool addFieldInitializer(CXXCtorInitializer *Init) {
5169 AllToInit.push_back(Elt: Init);
5170
5171 // Check whether this initializer makes the field "used".
5172 if (Init->getInit()->HasSideEffects(Ctx: S.Context))
5173 S.UnusedPrivateFields.remove(Init->getAnyMember());
5174
5175 return false;
5176 }
5177
5178 bool isInactiveUnionMember(FieldDecl *Field) {
5179 RecordDecl *Record = Field->getParent();
5180 if (!Record->isUnion())
5181 return false;
5182
5183 if (FieldDecl *Active =
5184 ActiveUnionMember.lookup(Val: Record->getCanonicalDecl()))
5185 return Active != Field->getCanonicalDecl();
5186
5187 // In an implicit copy or move constructor, ignore any in-class initializer.
5188 if (isImplicitCopyOrMove())
5189 return true;
5190
5191 // If there's no explicit initialization, the field is active only if it
5192 // has an in-class initializer...
5193 if (Field->hasInClassInitializer())
5194 return false;
5195 // ... or it's an anonymous struct or union whose class has an in-class
5196 // initializer.
5197 if (!Field->isAnonymousStructOrUnion())
5198 return true;
5199 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5200 return !FieldRD->hasInClassInitializer();
5201 }
5202
5203 /// Determine whether the given field is, or is within, a union member
5204 /// that is inactive (because there was an initializer given for a different
5205 /// member of the union, or because the union was not initialized at all).
5206 bool isWithinInactiveUnionMember(FieldDecl *Field,
5207 IndirectFieldDecl *Indirect) {
5208 if (!Indirect)
5209 return isInactiveUnionMember(Field);
5210
5211 for (auto *C : Indirect->chain()) {
5212 FieldDecl *Field = dyn_cast<FieldDecl>(Val: C);
5213 if (Field && isInactiveUnionMember(Field))
5214 return true;
5215 }
5216 return false;
5217 }
5218};
5219}
5220
5221/// Determine whether the given type is an incomplete or zero-lenfgth
5222/// array type.
5223static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5224 if (T->isIncompleteArrayType())
5225 return true;
5226
5227 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5228 if (ArrayT->isZeroSize())
5229 return true;
5230
5231 T = ArrayT->getElementType();
5232 }
5233
5234 return false;
5235}
5236
5237static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5238 FieldDecl *Field,
5239 IndirectFieldDecl *Indirect = nullptr) {
5240 if (Field->isInvalidDecl())
5241 return false;
5242
5243 // Overwhelmingly common case: we have a direct initializer for this field.
5244 if (CXXCtorInitializer *Init =
5245 Info.AllBaseFields.lookup(Val: Field->getCanonicalDecl()))
5246 return Info.addFieldInitializer(Init);
5247
5248 // C++11 [class.base.init]p8:
5249 // if the entity is a non-static data member that has a
5250 // brace-or-equal-initializer and either
5251 // -- the constructor's class is a union and no other variant member of that
5252 // union is designated by a mem-initializer-id or
5253 // -- the constructor's class is not a union, and, if the entity is a member
5254 // of an anonymous union, no other member of that union is designated by
5255 // a mem-initializer-id,
5256 // the entity is initialized as specified in [dcl.init].
5257 //
5258 // We also apply the same rules to handle anonymous structs within anonymous
5259 // unions.
5260 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5261 return false;
5262
5263 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5264 ExprResult DIE =
5265 SemaRef.BuildCXXDefaultInitExpr(Loc: Info.Ctor->getLocation(), Field);
5266 if (DIE.isInvalid())
5267 return true;
5268
5269 auto Entity = InitializedEntity::InitializeMember(Member: Field, Parent: nullptr, Implicit: true);
5270 SemaRef.checkInitializerLifetime(Entity, Init: DIE.get());
5271
5272 CXXCtorInitializer *Init;
5273 if (Indirect)
5274 Init = new (SemaRef.Context)
5275 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5276 SourceLocation(), DIE.get(), SourceLocation());
5277 else
5278 Init = new (SemaRef.Context)
5279 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5280 SourceLocation(), DIE.get(), SourceLocation());
5281 return Info.addFieldInitializer(Init);
5282 }
5283
5284 // Don't initialize incomplete or zero-length arrays.
5285 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5286 return false;
5287
5288 // Don't try to build an implicit initializer if there were semantic
5289 // errors in any of the initializers (and therefore we might be
5290 // missing some that the user actually wrote).
5291 if (Info.AnyErrorsInInits)
5292 return false;
5293
5294 CXXCtorInitializer *Init = nullptr;
5295 if (BuildImplicitMemberInitializer(SemaRef&: Info.S, Constructor: Info.Ctor, ImplicitInitKind: Info.IIK, Field,
5296 Indirect, CXXMemberInit&: Init))
5297 return true;
5298
5299 if (!Init)
5300 return false;
5301
5302 return Info.addFieldInitializer(Init);
5303}
5304
5305bool
5306Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5307 CXXCtorInitializer *Initializer) {
5308 assert(Initializer->isDelegatingInitializer());
5309 Constructor->setNumCtorInitializers(1);
5310 CXXCtorInitializer **initializer =
5311 new (Context) CXXCtorInitializer*[1];
5312 memcpy(dest: initializer, src: &Initializer, n: sizeof (CXXCtorInitializer*));
5313 Constructor->setCtorInitializers(initializer);
5314
5315 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: Constructor->getParent())) {
5316 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5317 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5318 }
5319
5320 DelegatingCtorDecls.push_back(LocalValue: Constructor);
5321
5322 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5323
5324 return false;
5325}
5326
5327static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,
5328 CXXRecordDecl *Class) {
5329 if (Class->isInvalidDecl())
5330 return nullptr;
5331 if (Class->hasIrrelevantDestructor())
5332 return nullptr;
5333
5334 // Dtor might still be missing, e.g because it's invalid.
5335 return S.LookupDestructor(Class);
5336}
5337
5338static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,
5339 FieldDecl *Field) {
5340 if (Field->isInvalidDecl())
5341 return;
5342
5343 // Don't destroy incomplete or zero-length arrays.
5344 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5345 return;
5346
5347 QualType FieldType = S.Context.getBaseElementType(Field->getType());
5348
5349 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5350 if (!FieldClassDecl)
5351 return;
5352
5353 // The destructor for an implicit anonymous union member is never invoked.
5354 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5355 return;
5356
5357 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5358 if (!Dtor)
5359 return;
5360
5361 S.CheckDestructorAccess(Field->getLocation(), Dtor,
5362 S.PDiag(diag::err_access_dtor_field)
5363 << Field->getDeclName() << FieldType);
5364
5365 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5366 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5367}
5368
5369static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,
5370 CXXRecordDecl *ClassDecl) {
5371 if (ClassDecl->isDependentContext())
5372 return;
5373
5374 // We only potentially invoke the destructors of potentially constructed
5375 // subobjects.
5376 bool VisitVirtualBases = !ClassDecl->isAbstract();
5377
5378 // If the destructor exists and has already been marked used in the MS ABI,
5379 // then virtual base destructors have already been checked and marked used.
5380 // Skip checking them again to avoid duplicate diagnostics.
5381 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5382 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5383 if (Dtor && Dtor->isUsed())
5384 VisitVirtualBases = false;
5385 }
5386
5387 llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;
5388
5389 // Bases.
5390 for (const auto &Base : ClassDecl->bases()) {
5391 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5392 if (!BaseClassDecl)
5393 continue;
5394
5395 // Remember direct virtual bases.
5396 if (Base.isVirtual()) {
5397 if (!VisitVirtualBases)
5398 continue;
5399 DirectVirtualBases.insert(Ptr: BaseClassDecl);
5400 }
5401
5402 auto *Dtor = LookupDestructorIfRelevant(S, Class: BaseClassDecl);
5403 if (!Dtor)
5404 continue;
5405
5406 // FIXME: caret should be on the start of the class name
5407 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5408 S.PDiag(diag::err_access_dtor_base)
5409 << Base.getType() << Base.getSourceRange(),
5410 S.Context.getTypeDeclType(ClassDecl));
5411
5412 S.MarkFunctionReferenced(Location, Dtor);
5413 S.DiagnoseUseOfDecl(Dtor, Location);
5414 }
5415
5416 if (VisitVirtualBases)
5417 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5418 DirectVirtualBases: &DirectVirtualBases);
5419}
5420
5421bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5422 ArrayRef<CXXCtorInitializer *> Initializers) {
5423 if (Constructor->isDependentContext()) {
5424 // Just store the initializers as written, they will be checked during
5425 // instantiation.
5426 if (!Initializers.empty()) {
5427 Constructor->setNumCtorInitializers(Initializers.size());
5428 CXXCtorInitializer **baseOrMemberInitializers =
5429 new (Context) CXXCtorInitializer*[Initializers.size()];
5430 memcpy(dest: baseOrMemberInitializers, src: Initializers.data(),
5431 n: Initializers.size() * sizeof(CXXCtorInitializer*));
5432 Constructor->setCtorInitializers(baseOrMemberInitializers);
5433 }
5434
5435 // Let template instantiation know whether we had errors.
5436 if (AnyErrors)
5437 Constructor->setInvalidDecl();
5438
5439 return false;
5440 }
5441
5442 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5443
5444 // We need to build the initializer AST according to order of construction
5445 // and not what user specified in the Initializers list.
5446 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5447 if (!ClassDecl)
5448 return true;
5449
5450 bool HadError = false;
5451
5452 for (unsigned i = 0; i < Initializers.size(); i++) {
5453 CXXCtorInitializer *Member = Initializers[i];
5454
5455 if (Member->isBaseInitializer())
5456 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5457 else {
5458 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5459
5460 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5461 for (auto *C : F->chain()) {
5462 FieldDecl *FD = dyn_cast<FieldDecl>(Val: C);
5463 if (FD && FD->getParent()->isUnion())
5464 Info.ActiveUnionMember.insert(std::make_pair(
5465 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5466 }
5467 } else if (FieldDecl *FD = Member->getMember()) {
5468 if (FD->getParent()->isUnion())
5469 Info.ActiveUnionMember.insert(std::make_pair(
5470 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5471 }
5472 }
5473 }
5474
5475 // Keep track of the direct virtual bases.
5476 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5477 for (auto &I : ClassDecl->bases()) {
5478 if (I.isVirtual())
5479 DirectVBases.insert(&I);
5480 }
5481
5482 // Push virtual bases before others.
5483 for (auto &VBase : ClassDecl->vbases()) {
5484 if (CXXCtorInitializer *Value
5485 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5486 // [class.base.init]p7, per DR257:
5487 // A mem-initializer where the mem-initializer-id names a virtual base
5488 // class is ignored during execution of a constructor of any class that
5489 // is not the most derived class.
5490 if (ClassDecl->isAbstract()) {
5491 // FIXME: Provide a fixit to remove the base specifier. This requires
5492 // tracking the location of the associated comma for a base specifier.
5493 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5494 << VBase.getType() << ClassDecl;
5495 DiagnoseAbstractType(ClassDecl);
5496 }
5497
5498 Info.AllToInit.push_back(Value);
5499 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5500 // [class.base.init]p8, per DR257:
5501 // If a given [...] base class is not named by a mem-initializer-id
5502 // [...] and the entity is not a virtual base class of an abstract
5503 // class, then [...] the entity is default-initialized.
5504 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5505 CXXCtorInitializer *CXXBaseInit;
5506 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5507 &VBase, IsInheritedVirtualBase,
5508 CXXBaseInit)) {
5509 HadError = true;
5510 continue;
5511 }
5512
5513 Info.AllToInit.push_back(CXXBaseInit);
5514 }
5515 }
5516
5517 // Non-virtual bases.
5518 for (auto &Base : ClassDecl->bases()) {
5519 // Virtuals are in the virtual base list and already constructed.
5520 if (Base.isVirtual())
5521 continue;
5522
5523 if (CXXCtorInitializer *Value
5524 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5525 Info.AllToInit.push_back(Value);
5526 } else if (!AnyErrors) {
5527 CXXCtorInitializer *CXXBaseInit;
5528 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5529 &Base, /*IsInheritedVirtualBase=*/false,
5530 CXXBaseInit)) {
5531 HadError = true;
5532 continue;
5533 }
5534
5535 Info.AllToInit.push_back(CXXBaseInit);
5536 }
5537 }
5538
5539 // Fields.
5540 for (auto *Mem : ClassDecl->decls()) {
5541 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5542 // C++ [class.bit]p2:
5543 // A declaration for a bit-field that omits the identifier declares an
5544 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5545 // initialized.
5546 if (F->isUnnamedBitField())
5547 continue;
5548
5549 // If we're not generating the implicit copy/move constructor, then we'll
5550 // handle anonymous struct/union fields based on their individual
5551 // indirect fields.
5552 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5553 continue;
5554
5555 if (CollectFieldInitializer(*this, Info, F))
5556 HadError = true;
5557 continue;
5558 }
5559
5560 // Beyond this point, we only consider default initialization.
5561 if (Info.isImplicitCopyOrMove())
5562 continue;
5563
5564 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5565 if (F->getType()->isIncompleteArrayType()) {
5566 assert(ClassDecl->hasFlexibleArrayMember() &&
5567 "Incomplete array type is not valid");
5568 continue;
5569 }
5570
5571 // Initialize each field of an anonymous struct individually.
5572 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5573 HadError = true;
5574
5575 continue;
5576 }
5577 }
5578
5579 unsigned NumInitializers = Info.AllToInit.size();
5580 if (NumInitializers > 0) {
5581 Constructor->setNumCtorInitializers(NumInitializers);
5582 CXXCtorInitializer **baseOrMemberInitializers =
5583 new (Context) CXXCtorInitializer*[NumInitializers];
5584 memcpy(dest: baseOrMemberInitializers, src: Info.AllToInit.data(),
5585 n: NumInitializers * sizeof(CXXCtorInitializer*));
5586 Constructor->setCtorInitializers(baseOrMemberInitializers);
5587
5588 SourceLocation Location = Constructor->getLocation();
5589
5590 // Constructors implicitly reference the base and member
5591 // destructors.
5592
5593 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5594 FieldDecl *Field = Initializer->getAnyMember();
5595 if (!Field)
5596 continue;
5597
5598 // C++ [class.base.init]p12:
5599 // In a non-delegating constructor, the destructor for each
5600 // potentially constructed subobject of class type is potentially
5601 // invoked.
5602 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5603 }
5604
5605 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5606 }
5607
5608 return HadError;
5609}
5610
5611static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5612 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5613 const RecordDecl *RD = RT->getDecl();
5614 if (RD->isAnonymousStructOrUnion()) {
5615 for (auto *Field : RD->fields())
5616 PopulateKeysForFields(Field, IdealInits);
5617 return;
5618 }
5619 }
5620 IdealInits.push_back(Elt: Field->getCanonicalDecl());
5621}
5622
5623static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5624 return Context.getCanonicalType(T: BaseType).getTypePtr();
5625}
5626
5627static const void *GetKeyForMember(ASTContext &Context,
5628 CXXCtorInitializer *Member) {
5629 if (!Member->isAnyMemberInitializer())
5630 return GetKeyForBase(Context, BaseType: QualType(Member->getBaseClass(), 0));
5631
5632 return Member->getAnyMember()->getCanonicalDecl();
5633}
5634
5635static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5636 const CXXCtorInitializer *Previous,
5637 const CXXCtorInitializer *Current) {
5638 if (Previous->isAnyMemberInitializer())
5639 Diag << 0 << Previous->getAnyMember();
5640 else
5641 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5642
5643 if (Current->isAnyMemberInitializer())
5644 Diag << 0 << Current->getAnyMember();
5645 else
5646 Diag << 1 << Current->getTypeSourceInfo()->getType();
5647}
5648
5649static void DiagnoseBaseOrMemInitializerOrder(
5650 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5651 ArrayRef<CXXCtorInitializer *> Inits) {
5652 if (Constructor->getDeclContext()->isDependentContext())
5653 return;
5654
5655 // Don't check initializers order unless the warning is enabled at the
5656 // location of at least one initializer.
5657 bool ShouldCheckOrder = false;
5658 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5659 CXXCtorInitializer *Init = Inits[InitIndex];
5660 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5661 Init->getSourceLocation())) {
5662 ShouldCheckOrder = true;
5663 break;
5664 }
5665 }
5666 if (!ShouldCheckOrder)
5667 return;
5668
5669 // Build the list of bases and members in the order that they'll
5670 // actually be initialized. The explicit initializers should be in
5671 // this same order but may be missing things.
5672 SmallVector<const void*, 32> IdealInitKeys;
5673
5674 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5675
5676 // 1. Virtual bases.
5677 for (const auto &VBase : ClassDecl->vbases())
5678 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5679
5680 // 2. Non-virtual bases.
5681 for (const auto &Base : ClassDecl->bases()) {
5682 if (Base.isVirtual())
5683 continue;
5684 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5685 }
5686
5687 // 3. Direct fields.
5688 for (auto *Field : ClassDecl->fields()) {
5689 if (Field->isUnnamedBitField())
5690 continue;
5691
5692 PopulateKeysForFields(Field, IdealInitKeys);
5693 }
5694
5695 unsigned NumIdealInits = IdealInitKeys.size();
5696 unsigned IdealIndex = 0;
5697
5698 // Track initializers that are in an incorrect order for either a warning or
5699 // note if multiple ones occur.
5700 SmallVector<unsigned> WarnIndexes;
5701 // Correlates the index of an initializer in the init-list to the index of
5702 // the field/base in the class.
5703 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5704
5705 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5706 const void *InitKey = GetKeyForMember(Context&: SemaRef.Context, Member: Inits[InitIndex]);
5707
5708 // Scan forward to try to find this initializer in the idealized
5709 // initializers list.
5710 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5711 if (InitKey == IdealInitKeys[IdealIndex])
5712 break;
5713
5714 // If we didn't find this initializer, it must be because we
5715 // scanned past it on a previous iteration. That can only
5716 // happen if we're out of order; emit a warning.
5717 if (IdealIndex == NumIdealInits && InitIndex) {
5718 WarnIndexes.push_back(Elt: InitIndex);
5719
5720 // Move back to the initializer's location in the ideal list.
5721 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5722 if (InitKey == IdealInitKeys[IdealIndex])
5723 break;
5724
5725 assert(IdealIndex < NumIdealInits &&
5726 "initializer not found in initializer list");
5727 }
5728 CorrelatedInitOrder.emplace_back(Args&: IdealIndex, Args&: InitIndex);
5729 }
5730
5731 if (WarnIndexes.empty())
5732 return;
5733
5734 // Sort based on the ideal order, first in the pair.
5735 llvm::sort(C&: CorrelatedInitOrder, Comp: llvm::less_first());
5736
5737 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5738 // emit the diagnostic before we can try adding notes.
5739 {
5740 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5741 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5742 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5743 : diag::warn_some_initializers_out_of_order);
5744
5745 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5746 if (CorrelatedInitOrder[I].second == I)
5747 continue;
5748 // Ideally we would be using InsertFromRange here, but clang doesn't
5749 // appear to handle InsertFromRange correctly when the source range is
5750 // modified by another fix-it.
5751 D << FixItHint::CreateReplacement(
5752 RemoveRange: Inits[I]->getSourceRange(),
5753 Code: Lexer::getSourceText(
5754 Range: CharSourceRange::getTokenRange(
5755 R: Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5756 SM: SemaRef.getSourceManager(), LangOpts: SemaRef.getLangOpts()));
5757 }
5758
5759 // If there is only 1 item out of order, the warning expects the name and
5760 // type of each being added to it.
5761 if (WarnIndexes.size() == 1) {
5762 AddInitializerToDiag(Diag: D, Previous: Inits[WarnIndexes.front() - 1],
5763 Current: Inits[WarnIndexes.front()]);
5764 return;
5765 }
5766 }
5767 // More than 1 item to warn, create notes letting the user know which ones
5768 // are bad.
5769 for (unsigned WarnIndex : WarnIndexes) {
5770 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5771 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5772 diag::note_initializer_out_of_order);
5773 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5774 D << PrevInit->getSourceRange();
5775 }
5776}
5777
5778namespace {
5779bool CheckRedundantInit(Sema &S,
5780 CXXCtorInitializer *Init,
5781 CXXCtorInitializer *&PrevInit) {
5782 if (!PrevInit) {
5783 PrevInit = Init;
5784 return false;
5785 }
5786
5787 if (FieldDecl *Field = Init->getAnyMember())
5788 S.Diag(Init->getSourceLocation(),
5789 diag::err_multiple_mem_initialization)
5790 << Field->getDeclName()
5791 << Init->getSourceRange();
5792 else {
5793 const Type *BaseClass = Init->getBaseClass();
5794 assert(BaseClass && "neither field nor base");
5795 S.Diag(Init->getSourceLocation(),
5796 diag::err_multiple_base_initialization)
5797 << QualType(BaseClass, 0)
5798 << Init->getSourceRange();
5799 }
5800 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5801 << 0 << PrevInit->getSourceRange();
5802
5803 return true;
5804}
5805
5806typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5807typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5808
5809bool CheckRedundantUnionInit(Sema &S,
5810 CXXCtorInitializer *Init,
5811 RedundantUnionMap &Unions) {
5812 FieldDecl *Field = Init->getAnyMember();
5813 RecordDecl *Parent = Field->getParent();
5814 NamedDecl *Child = Field;
5815
5816 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5817 if (Parent->isUnion()) {
5818 UnionEntry &En = Unions[Parent];
5819 if (En.first && En.first != Child) {
5820 S.Diag(Init->getSourceLocation(),
5821 diag::err_multiple_mem_union_initialization)
5822 << Field->getDeclName()
5823 << Init->getSourceRange();
5824 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5825 << 0 << En.second->getSourceRange();
5826 return true;
5827 }
5828 if (!En.first) {
5829 En.first = Child;
5830 En.second = Init;
5831 }
5832 if (!Parent->isAnonymousStructOrUnion())
5833 return false;
5834 }
5835
5836 Child = Parent;
5837 Parent = cast<RecordDecl>(Parent->getDeclContext());
5838 }
5839
5840 return false;
5841}
5842} // namespace
5843
5844void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5845 SourceLocation ColonLoc,
5846 ArrayRef<CXXCtorInitializer*> MemInits,
5847 bool AnyErrors) {
5848 if (!ConstructorDecl)
5849 return;
5850
5851 AdjustDeclIfTemplate(Decl&: ConstructorDecl);
5852
5853 CXXConstructorDecl *Constructor
5854 = dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl);
5855
5856 if (!Constructor) {
5857 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5858 return;
5859 }
5860
5861 // Mapping for the duplicate initializers check.
5862 // For member initializers, this is keyed with a FieldDecl*.
5863 // For base initializers, this is keyed with a Type*.
5864 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5865
5866 // Mapping for the inconsistent anonymous-union initializers check.
5867 RedundantUnionMap MemberUnions;
5868
5869 bool HadError = false;
5870 for (unsigned i = 0; i < MemInits.size(); i++) {
5871 CXXCtorInitializer *Init = MemInits[i];
5872
5873 // Set the source order index.
5874 Init->setSourceOrder(i);
5875
5876 if (Init->isAnyMemberInitializer()) {
5877 const void *Key = GetKeyForMember(Context, Member: Init);
5878 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]) ||
5879 CheckRedundantUnionInit(S&: *this, Init, Unions&: MemberUnions))
5880 HadError = true;
5881 } else if (Init->isBaseInitializer()) {
5882 const void *Key = GetKeyForMember(Context, Member: Init);
5883 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]))
5884 HadError = true;
5885 } else {
5886 assert(Init->isDelegatingInitializer());
5887 // This must be the only initializer
5888 if (MemInits.size() != 1) {
5889 Diag(Init->getSourceLocation(),
5890 diag::err_delegating_initializer_alone)
5891 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5892 // We will treat this as being the only initializer.
5893 }
5894 SetDelegatingInitializer(Constructor, Initializer: MemInits[i]);
5895 // Return immediately as the initializer is set.
5896 return;
5897 }
5898 }
5899
5900 if (HadError)
5901 return;
5902
5903 DiagnoseBaseOrMemInitializerOrder(SemaRef&: *this, Constructor, Inits: MemInits);
5904
5905 SetCtorInitializers(Constructor, AnyErrors, Initializers: MemInits);
5906
5907 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5908}
5909
5910void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5911 CXXRecordDecl *ClassDecl) {
5912 // Ignore dependent contexts. Also ignore unions, since their members never
5913 // have destructors implicitly called.
5914 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5915 return;
5916
5917 // FIXME: all the access-control diagnostics are positioned on the
5918 // field/base declaration. That's probably good; that said, the
5919 // user might reasonably want to know why the destructor is being
5920 // emitted, and we currently don't say.
5921
5922 // Non-static data members.
5923 for (auto *Field : ClassDecl->fields()) {
5924 MarkFieldDestructorReferenced(*this, Location, Field);
5925 }
5926
5927 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl);
5928}
5929
5930void Sema::MarkVirtualBaseDestructorsReferenced(
5931 SourceLocation Location, CXXRecordDecl *ClassDecl,
5932 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5933 // Virtual bases.
5934 for (const auto &VBase : ClassDecl->vbases()) {
5935 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5936 if (!BaseClassDecl)
5937 continue;
5938
5939 // Ignore already visited direct virtual bases.
5940 if (DirectVirtualBases && DirectVirtualBases->count(Ptr: BaseClassDecl))
5941 continue;
5942
5943 auto *Dtor = LookupDestructorIfRelevant(S&: *this, Class: BaseClassDecl);
5944 if (!Dtor)
5945 continue;
5946
5947 if (CheckDestructorAccess(
5948 ClassDecl->getLocation(), Dtor,
5949 PDiag(diag::err_access_dtor_vbase)
5950 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5951 Context.getTypeDeclType(ClassDecl)) ==
5952 AR_accessible) {
5953 CheckDerivedToBaseConversion(
5954 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5955 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5956 SourceRange(), DeclarationName(), nullptr);
5957 }
5958
5959 MarkFunctionReferenced(Location, Dtor);
5960 DiagnoseUseOfDecl(Dtor, Location);
5961 }
5962}
5963
5964void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5965 if (!CDtorDecl)
5966 return;
5967
5968 if (CXXConstructorDecl *Constructor
5969 = dyn_cast<CXXConstructorDecl>(Val: CDtorDecl)) {
5970 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5971 !ClassDecl || ClassDecl->isInvalidDecl()) {
5972 return;
5973 }
5974 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5975 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5976 }
5977}
5978
5979bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5980 if (!getLangOpts().CPlusPlus)
5981 return false;
5982
5983 const auto *RD = Context.getBaseElementType(QT: T)->getAsCXXRecordDecl();
5984 if (!RD)
5985 return false;
5986
5987 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5988 // class template specialization here, but doing so breaks a lot of code.
5989
5990 // We can't answer whether something is abstract until it has a
5991 // definition. If it's currently being defined, we'll walk back
5992 // over all the declarations when we have a full definition.
5993 const CXXRecordDecl *Def = RD->getDefinition();
5994 if (!Def || Def->isBeingDefined())
5995 return false;
5996
5997 return RD->isAbstract();
5998}
5999
6000bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6001 TypeDiagnoser &Diagnoser) {
6002 if (!isAbstractType(Loc, T))
6003 return false;
6004
6005 T = Context.getBaseElementType(QT: T);
6006 Diagnoser.diagnose(S&: *this, Loc, T);
6007 DiagnoseAbstractType(RD: T->getAsCXXRecordDecl());
6008 return true;
6009}
6010
6011void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6012 // Check if we've already emitted the list of pure virtual functions
6013 // for this class.
6014 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(Ptr: RD))
6015 return;
6016
6017 // If the diagnostic is suppressed, don't emit the notes. We're only
6018 // going to emit them once, so try to attach them to a diagnostic we're
6019 // actually going to show.
6020 if (Diags.isLastDiagnosticIgnored())
6021 return;
6022
6023 CXXFinalOverriderMap FinalOverriders;
6024 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
6025
6026 // Keep a set of seen pure methods so we won't diagnose the same method
6027 // more than once.
6028 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6029
6030 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
6031 MEnd = FinalOverriders.end();
6032 M != MEnd;
6033 ++M) {
6034 for (OverridingMethods::iterator SO = M->second.begin(),
6035 SOEnd = M->second.end();
6036 SO != SOEnd; ++SO) {
6037 // C++ [class.abstract]p4:
6038 // A class is abstract if it contains or inherits at least one
6039 // pure virtual function for which the final overrider is pure
6040 // virtual.
6041
6042 //
6043 if (SO->second.size() != 1)
6044 continue;
6045
6046 if (!SO->second.front().Method->isPureVirtual())
6047 continue;
6048
6049 if (!SeenPureMethods.insert(Ptr: SO->second.front().Method).second)
6050 continue;
6051
6052 Diag(SO->second.front().Method->getLocation(),
6053 diag::note_pure_virtual_function)
6054 << SO->second.front().Method->getDeclName() << RD->getDeclName();
6055 }
6056 }
6057
6058 if (!PureVirtualClassDiagSet)
6059 PureVirtualClassDiagSet.reset(p: new RecordDeclSetTy);
6060 PureVirtualClassDiagSet->insert(Ptr: RD);
6061}
6062
6063namespace {
6064struct AbstractUsageInfo {
6065 Sema &S;
6066 CXXRecordDecl *Record;
6067 CanQualType AbstractType;
6068 bool Invalid;
6069
6070 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6071 : S(S), Record(Record),
6072 AbstractType(S.Context.getCanonicalType(
6073 S.Context.getTypeDeclType(Record))),
6074 Invalid(false) {}
6075
6076 void DiagnoseAbstractType() {
6077 if (Invalid) return;
6078 S.DiagnoseAbstractType(RD: Record);
6079 Invalid = true;
6080 }
6081
6082 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6083};
6084
6085struct CheckAbstractUsage {
6086 AbstractUsageInfo &Info;
6087 const NamedDecl *Ctx;
6088
6089 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6090 : Info(Info), Ctx(Ctx) {}
6091
6092 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6093 switch (TL.getTypeLocClass()) {
6094#define ABSTRACT_TYPELOC(CLASS, PARENT)
6095#define TYPELOC(CLASS, PARENT) \
6096 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6097#include "clang/AST/TypeLocNodes.def"
6098 }
6099 }
6100
6101 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6102 Visit(TL: TL.getReturnLoc(), Sel: Sema::AbstractReturnType);
6103 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6104 if (!TL.getParam(I))
6105 continue;
6106
6107 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6108 if (TSI) Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractParamType);
6109 }
6110 }
6111
6112 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6113 Visit(TL: TL.getElementLoc(), Sel: Sema::AbstractArrayType);
6114 }
6115
6116 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6117 // Visit the type parameters from a permissive context.
6118 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6119 TemplateArgumentLoc TAL = TL.getArgLoc(i: I);
6120 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6121 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6122 Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6123 // TODO: other template argument types?
6124 }
6125 }
6126
6127 // Visit pointee types from a permissive context.
6128#define CheckPolymorphic(Type) \
6129 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6130 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6131 }
6132 CheckPolymorphic(PointerTypeLoc)
6133 CheckPolymorphic(ReferenceTypeLoc)
6134 CheckPolymorphic(MemberPointerTypeLoc)
6135 CheckPolymorphic(BlockPointerTypeLoc)
6136 CheckPolymorphic(AtomicTypeLoc)
6137
6138 /// Handle all the types we haven't given a more specific
6139 /// implementation for above.
6140 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6141 // Every other kind of type that we haven't called out already
6142 // that has an inner type is either (1) sugar or (2) contains that
6143 // inner type in some way as a subobject.
6144 if (TypeLoc Next = TL.getNextTypeLoc())
6145 return Visit(TL: Next, Sel);
6146
6147 // If there's no inner type and we're in a permissive context,
6148 // don't diagnose.
6149 if (Sel == Sema::AbstractNone) return;
6150
6151 // Check whether the type matches the abstract type.
6152 QualType T = TL.getType();
6153 if (T->isArrayType()) {
6154 Sel = Sema::AbstractArrayType;
6155 T = Info.S.Context.getBaseElementType(QT: T);
6156 }
6157 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
6158 if (CT != Info.AbstractType) return;
6159
6160 // It matched; do some magic.
6161 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6162 if (Sel == Sema::AbstractArrayType) {
6163 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6164 << T << TL.getSourceRange();
6165 } else {
6166 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6167 << Sel << T << TL.getSourceRange();
6168 }
6169 Info.DiagnoseAbstractType();
6170 }
6171};
6172
6173void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6174 Sema::AbstractDiagSelID Sel) {
6175 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6176}
6177
6178}
6179
6180/// Check for invalid uses of an abstract type in a function declaration.
6181static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6182 FunctionDecl *FD) {
6183 // Only definitions are required to refer to complete and
6184 // non-abstract types.
6185 if (!FD->doesThisDeclarationHaveABody())
6186 return;
6187
6188 // For safety's sake, just ignore it if we don't have type source
6189 // information. This should never happen for non-implicit methods,
6190 // but...
6191 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6192 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6193}
6194
6195/// Check for invalid uses of an abstract type in a variable0 declaration.
6196static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6197 VarDecl *VD) {
6198 // No need to do the check on definitions, which require that
6199 // the type is complete.
6200 if (VD->isThisDeclarationADefinition())
6201 return;
6202
6203 Info.CheckType(D: VD, TL: VD->getTypeSourceInfo()->getTypeLoc(),
6204 Sel: Sema::AbstractVariableType);
6205}
6206
6207/// Check for invalid uses of an abstract type within a class definition.
6208static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6209 CXXRecordDecl *RD) {
6210 for (auto *D : RD->decls()) {
6211 if (D->isImplicit()) continue;
6212
6213 // Step through friends to the befriended declaration.
6214 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6215 D = FD->getFriendDecl();
6216 if (!D) continue;
6217 }
6218
6219 // Functions and function templates.
6220 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6221 CheckAbstractClassUsage(Info, FD);
6222 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6223 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6224
6225 // Fields and static variables.
6226 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6227 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6228 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6229 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6230 CheckAbstractClassUsage(Info, VD);
6231 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6232 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6233
6234 // Nested classes and class templates.
6235 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6236 CheckAbstractClassUsage(Info, RD);
6237 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6238 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6239 }
6240 }
6241}
6242
6243static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6244 Attr *ClassAttr = getDLLAttr(Class);
6245 if (!ClassAttr)
6246 return;
6247
6248 assert(ClassAttr->getKind() == attr::DLLExport);
6249
6250 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6251
6252 if (TSK == TSK_ExplicitInstantiationDeclaration)
6253 // Don't go any further if this is just an explicit instantiation
6254 // declaration.
6255 return;
6256
6257 // Add a context note to explain how we got to any diagnostics produced below.
6258 struct MarkingClassDllexported {
6259 Sema &S;
6260 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6261 SourceLocation AttrLoc)
6262 : S(S) {
6263 Sema::CodeSynthesisContext Ctx;
6264 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6265 Ctx.PointOfInstantiation = AttrLoc;
6266 Ctx.Entity = Class;
6267 S.pushCodeSynthesisContext(Ctx);
6268 }
6269 ~MarkingClassDllexported() {
6270 S.popCodeSynthesisContext();
6271 }
6272 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6273
6274 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6275 S.MarkVTableUsed(Loc: Class->getLocation(), Class, DefinitionRequired: true);
6276
6277 for (Decl *Member : Class->decls()) {
6278 // Skip members that were not marked exported.
6279 if (!Member->hasAttr<DLLExportAttr>())
6280 continue;
6281
6282 // Defined static variables that are members of an exported base
6283 // class must be marked export too.
6284 auto *VD = dyn_cast<VarDecl>(Member);
6285 if (VD && VD->getStorageClass() == SC_Static &&
6286 TSK == TSK_ImplicitInstantiation)
6287 S.MarkVariableReferenced(VD->getLocation(), VD);
6288
6289 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6290 if (!MD)
6291 continue;
6292
6293 if (MD->isUserProvided()) {
6294 // Instantiate non-default class member functions ...
6295
6296 // .. except for certain kinds of template specializations.
6297 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6298 continue;
6299
6300 // If this is an MS ABI dllexport default constructor, instantiate any
6301 // default arguments.
6302 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6303 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6304 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6305 S.InstantiateDefaultCtorDefaultArgs(CD);
6306 }
6307 }
6308
6309 S.MarkFunctionReferenced(Class->getLocation(), MD);
6310
6311 // The function will be passed to the consumer when its definition is
6312 // encountered.
6313 } else if (MD->isExplicitlyDefaulted()) {
6314 // Synthesize and instantiate explicitly defaulted methods.
6315 S.MarkFunctionReferenced(Class->getLocation(), MD);
6316
6317 if (TSK != TSK_ExplicitInstantiationDefinition) {
6318 // Except for explicit instantiation defs, we will not see the
6319 // definition again later, so pass it to the consumer now.
6320 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6321 }
6322 } else if (!MD->isTrivial() ||
6323 MD->isCopyAssignmentOperator() ||
6324 MD->isMoveAssignmentOperator()) {
6325 // Synthesize and instantiate non-trivial implicit methods, and the copy
6326 // and move assignment operators. The latter are exported even if they
6327 // are trivial, because the address of an operator can be taken and
6328 // should compare equal across libraries.
6329 S.MarkFunctionReferenced(Class->getLocation(), MD);
6330
6331 // There is no later point when we will see the definition of this
6332 // function, so pass it to the consumer now.
6333 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6334 }
6335 }
6336}
6337
6338static void checkForMultipleExportedDefaultConstructors(Sema &S,
6339 CXXRecordDecl *Class) {
6340 // Only the MS ABI has default constructor closures, so we don't need to do
6341 // this semantic checking anywhere else.
6342 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6343 return;
6344
6345 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6346 for (Decl *Member : Class->decls()) {
6347 // Look for exported default constructors.
6348 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6349 if (!CD || !CD->isDefaultConstructor())
6350 continue;
6351 auto *Attr = CD->getAttr<DLLExportAttr>();
6352 if (!Attr)
6353 continue;
6354
6355 // If the class is non-dependent, mark the default arguments as ODR-used so
6356 // that we can properly codegen the constructor closure.
6357 if (!Class->isDependentContext()) {
6358 for (ParmVarDecl *PD : CD->parameters()) {
6359 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6360 S.DiscardCleanupsInEvaluationContext();
6361 }
6362 }
6363
6364 if (LastExportedDefaultCtor) {
6365 S.Diag(LastExportedDefaultCtor->getLocation(),
6366 diag::err_attribute_dll_ambiguous_default_ctor)
6367 << Class;
6368 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6369 << CD->getDeclName();
6370 return;
6371 }
6372 LastExportedDefaultCtor = CD;
6373 }
6374}
6375
6376static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6377 CXXRecordDecl *Class) {
6378 bool ErrorReported = false;
6379 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6380 ClassTemplateDecl *TD) {
6381 if (ErrorReported)
6382 return;
6383 S.Diag(TD->getLocation(),
6384 diag::err_cuda_device_builtin_surftex_cls_template)
6385 << /*surface*/ 0 << TD;
6386 ErrorReported = true;
6387 };
6388
6389 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6390 if (!TD) {
6391 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6392 if (!SD) {
6393 S.Diag(Class->getLocation(),
6394 diag::err_cuda_device_builtin_surftex_ref_decl)
6395 << /*surface*/ 0 << Class;
6396 S.Diag(Class->getLocation(),
6397 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6398 << Class;
6399 return;
6400 }
6401 TD = SD->getSpecializedTemplate();
6402 }
6403
6404 TemplateParameterList *Params = TD->getTemplateParameters();
6405 unsigned N = Params->size();
6406
6407 if (N != 2) {
6408 reportIllegalClassTemplate(S, TD);
6409 S.Diag(TD->getLocation(),
6410 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6411 << TD << 2;
6412 }
6413 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6414 reportIllegalClassTemplate(S, TD);
6415 S.Diag(TD->getLocation(),
6416 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6417 << TD << /*1st*/ 0 << /*type*/ 0;
6418 }
6419 if (N > 1) {
6420 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6421 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6422 reportIllegalClassTemplate(S, TD);
6423 S.Diag(TD->getLocation(),
6424 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6425 << TD << /*2nd*/ 1 << /*integer*/ 1;
6426 }
6427 }
6428}
6429
6430static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6431 CXXRecordDecl *Class) {
6432 bool ErrorReported = false;
6433 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6434 ClassTemplateDecl *TD) {
6435 if (ErrorReported)
6436 return;
6437 S.Diag(TD->getLocation(),
6438 diag::err_cuda_device_builtin_surftex_cls_template)
6439 << /*texture*/ 1 << TD;
6440 ErrorReported = true;
6441 };
6442
6443 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6444 if (!TD) {
6445 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6446 if (!SD) {
6447 S.Diag(Class->getLocation(),
6448 diag::err_cuda_device_builtin_surftex_ref_decl)
6449 << /*texture*/ 1 << Class;
6450 S.Diag(Class->getLocation(),
6451 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6452 << Class;
6453 return;
6454 }
6455 TD = SD->getSpecializedTemplate();
6456 }
6457
6458 TemplateParameterList *Params = TD->getTemplateParameters();
6459 unsigned N = Params->size();
6460
6461 if (N != 3) {
6462 reportIllegalClassTemplate(S, TD);
6463 S.Diag(TD->getLocation(),
6464 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6465 << TD << 3;
6466 }
6467 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6468 reportIllegalClassTemplate(S, TD);
6469 S.Diag(TD->getLocation(),
6470 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6471 << TD << /*1st*/ 0 << /*type*/ 0;
6472 }
6473 if (N > 1) {
6474 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6475 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6476 reportIllegalClassTemplate(S, TD);
6477 S.Diag(TD->getLocation(),
6478 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6479 << TD << /*2nd*/ 1 << /*integer*/ 1;
6480 }
6481 }
6482 if (N > 2) {
6483 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 2));
6484 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6485 reportIllegalClassTemplate(S, TD);
6486 S.Diag(TD->getLocation(),
6487 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6488 << TD << /*3rd*/ 2 << /*integer*/ 1;
6489 }
6490 }
6491}
6492
6493void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6494 // Mark any compiler-generated routines with the implicit code_seg attribute.
6495 for (auto *Method : Class->methods()) {
6496 if (Method->isUserProvided())
6497 continue;
6498 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6499 Method->addAttr(A);
6500 }
6501}
6502
6503void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6504 Attr *ClassAttr = getDLLAttr(Class);
6505
6506 // MSVC inherits DLL attributes to partial class template specializations.
6507 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6508 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Class)) {
6509 if (Attr *TemplateAttr =
6510 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6511 auto *A = cast<InheritableAttr>(Val: TemplateAttr->clone(C&: getASTContext()));
6512 A->setInherited(true);
6513 ClassAttr = A;
6514 }
6515 }
6516 }
6517
6518 if (!ClassAttr)
6519 return;
6520
6521 // MSVC allows imported or exported template classes that have UniqueExternal
6522 // linkage. This occurs when the template class has been instantiated with
6523 // a template parameter which itself has internal linkage.
6524 // We drop the attribute to avoid exporting or importing any members.
6525 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6526 Context.getTargetInfo().getTriple().isPS()) &&
6527 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6528 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6529 return;
6530 }
6531
6532 if (!Class->isExternallyVisible()) {
6533 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6534 << Class << ClassAttr;
6535 return;
6536 }
6537
6538 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6539 !ClassAttr->isInherited()) {
6540 // Diagnose dll attributes on members of class with dll attribute.
6541 for (Decl *Member : Class->decls()) {
6542 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6543 continue;
6544 InheritableAttr *MemberAttr = getDLLAttr(Member);
6545 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6546 continue;
6547
6548 Diag(MemberAttr->getLocation(),
6549 diag::err_attribute_dll_member_of_dll_class)
6550 << MemberAttr << ClassAttr;
6551 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6552 Member->setInvalidDecl();
6553 }
6554 }
6555
6556 if (Class->getDescribedClassTemplate())
6557 // Don't inherit dll attribute until the template is instantiated.
6558 return;
6559
6560 // The class is either imported or exported.
6561 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6562
6563 // Check if this was a dllimport attribute propagated from a derived class to
6564 // a base class template specialization. We don't apply these attributes to
6565 // static data members.
6566 const bool PropagatedImport =
6567 !ClassExported &&
6568 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6569
6570 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6571
6572 // Ignore explicit dllexport on explicit class template instantiation
6573 // declarations, except in MinGW mode.
6574 if (ClassExported && !ClassAttr->isInherited() &&
6575 TSK == TSK_ExplicitInstantiationDeclaration &&
6576 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6577 Class->dropAttr<DLLExportAttr>();
6578 return;
6579 }
6580
6581 // Force declaration of implicit members so they can inherit the attribute.
6582 ForceDeclarationOfImplicitMembers(Class);
6583
6584 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6585 // seem to be true in practice?
6586
6587 for (Decl *Member : Class->decls()) {
6588 VarDecl *VD = dyn_cast<VarDecl>(Member);
6589 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6590
6591 // Only methods and static fields inherit the attributes.
6592 if (!VD && !MD)
6593 continue;
6594
6595 if (MD) {
6596 // Don't process deleted methods.
6597 if (MD->isDeleted())
6598 continue;
6599
6600 if (MD->isInlined()) {
6601 // MinGW does not import or export inline methods. But do it for
6602 // template instantiations.
6603 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6604 TSK != TSK_ExplicitInstantiationDeclaration &&
6605 TSK != TSK_ExplicitInstantiationDefinition)
6606 continue;
6607
6608 // MSVC versions before 2015 don't export the move assignment operators
6609 // and move constructor, so don't attempt to import/export them if
6610 // we have a definition.
6611 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6612 if ((MD->isMoveAssignmentOperator() ||
6613 (Ctor && Ctor->isMoveConstructor())) &&
6614 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6615 continue;
6616
6617 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6618 // operator is exported anyway.
6619 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6620 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6621 continue;
6622 }
6623 }
6624
6625 // Don't apply dllimport attributes to static data members of class template
6626 // instantiations when the attribute is propagated from a derived class.
6627 if (VD && PropagatedImport)
6628 continue;
6629
6630 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6631 continue;
6632
6633 if (!getDLLAttr(Member)) {
6634 InheritableAttr *NewAttr = nullptr;
6635
6636 // Do not export/import inline function when -fno-dllexport-inlines is
6637 // passed. But add attribute for later local static var check.
6638 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6639 TSK != TSK_ExplicitInstantiationDeclaration &&
6640 TSK != TSK_ExplicitInstantiationDefinition) {
6641 if (ClassExported) {
6642 NewAttr = ::new (getASTContext())
6643 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6644 } else {
6645 NewAttr = ::new (getASTContext())
6646 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6647 }
6648 } else {
6649 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6650 }
6651
6652 NewAttr->setInherited(true);
6653 Member->addAttr(NewAttr);
6654
6655 if (MD) {
6656 // Propagate DLLAttr to friend re-declarations of MD that have already
6657 // been constructed.
6658 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6659 FD = FD->getPreviousDecl()) {
6660 if (FD->getFriendObjectKind() == Decl::FOK_None)
6661 continue;
6662 assert(!getDLLAttr(FD) &&
6663 "friend re-decl should not already have a DLLAttr");
6664 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6665 NewAttr->setInherited(true);
6666 FD->addAttr(NewAttr);
6667 }
6668 }
6669 }
6670 }
6671
6672 if (ClassExported)
6673 DelayedDllExportClasses.push_back(Elt: Class);
6674}
6675
6676void Sema::propagateDLLAttrToBaseClassTemplate(
6677 CXXRecordDecl *Class, Attr *ClassAttr,
6678 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6679 if (getDLLAttr(
6680 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6681 // If the base class template has a DLL attribute, don't try to change it.
6682 return;
6683 }
6684
6685 auto TSK = BaseTemplateSpec->getSpecializationKind();
6686 if (!getDLLAttr(BaseTemplateSpec) &&
6687 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6688 TSK == TSK_ImplicitInstantiation)) {
6689 // The template hasn't been instantiated yet (or it has, but only as an
6690 // explicit instantiation declaration or implicit instantiation, which means
6691 // we haven't codegenned any members yet), so propagate the attribute.
6692 auto *NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6693 NewAttr->setInherited(true);
6694 BaseTemplateSpec->addAttr(NewAttr);
6695
6696 // If this was an import, mark that we propagated it from a derived class to
6697 // a base class template specialization.
6698 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6699 ImportAttr->setPropagatedToBaseTemplate();
6700
6701 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6702 // needs to be run again to work see the new attribute. Otherwise this will
6703 // get run whenever the template is instantiated.
6704 if (TSK != TSK_Undeclared)
6705 checkClassLevelDLLAttribute(BaseTemplateSpec);
6706
6707 return;
6708 }
6709
6710 if (getDLLAttr(BaseTemplateSpec)) {
6711 // The template has already been specialized or instantiated with an
6712 // attribute, explicitly or through propagation. We should not try to change
6713 // it.
6714 return;
6715 }
6716
6717 // The template was previously instantiated or explicitly specialized without
6718 // a dll attribute, It's too late for us to add an attribute, so warn that
6719 // this is unsupported.
6720 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6721 << BaseTemplateSpec->isExplicitSpecialization();
6722 Diag(ClassAttr->getLocation(), diag::note_attribute);
6723 if (BaseTemplateSpec->isExplicitSpecialization()) {
6724 Diag(BaseTemplateSpec->getLocation(),
6725 diag::note_template_class_explicit_specialization_was_here)
6726 << BaseTemplateSpec;
6727 } else {
6728 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6729 diag::note_template_class_instantiation_was_here)
6730 << BaseTemplateSpec;
6731 }
6732}
6733
6734Sema::DefaultedFunctionKind
6735Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6736 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
6737 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
6738 if (Ctor->isDefaultConstructor())
6739 return CXXSpecialMemberKind::DefaultConstructor;
6740
6741 if (Ctor->isCopyConstructor())
6742 return CXXSpecialMemberKind::CopyConstructor;
6743
6744 if (Ctor->isMoveConstructor())
6745 return CXXSpecialMemberKind::MoveConstructor;
6746 }
6747
6748 if (MD->isCopyAssignmentOperator())
6749 return CXXSpecialMemberKind::CopyAssignment;
6750
6751 if (MD->isMoveAssignmentOperator())
6752 return CXXSpecialMemberKind::MoveAssignment;
6753
6754 if (isa<CXXDestructorDecl>(Val: FD))
6755 return CXXSpecialMemberKind::Destructor;
6756 }
6757
6758 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6759 case OO_EqualEqual:
6760 return DefaultedComparisonKind::Equal;
6761
6762 case OO_ExclaimEqual:
6763 return DefaultedComparisonKind::NotEqual;
6764
6765 case OO_Spaceship:
6766 // No point allowing this if <=> doesn't exist in the current language mode.
6767 if (!getLangOpts().CPlusPlus20)
6768 break;
6769 return DefaultedComparisonKind::ThreeWay;
6770
6771 case OO_Less:
6772 case OO_LessEqual:
6773 case OO_Greater:
6774 case OO_GreaterEqual:
6775 // No point allowing this if <=> doesn't exist in the current language mode.
6776 if (!getLangOpts().CPlusPlus20)
6777 break;
6778 return DefaultedComparisonKind::Relational;
6779
6780 default:
6781 break;
6782 }
6783
6784 // Not defaultable.
6785 return DefaultedFunctionKind();
6786}
6787
6788static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6789 SourceLocation DefaultLoc) {
6790 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6791 if (DFK.isComparison())
6792 return S.DefineDefaultedComparison(Loc: DefaultLoc, FD, DCK: DFK.asComparison());
6793
6794 switch (DFK.asSpecialMember()) {
6795 case CXXSpecialMemberKind::DefaultConstructor:
6796 S.DefineImplicitDefaultConstructor(CurrentLocation: DefaultLoc,
6797 Constructor: cast<CXXConstructorDecl>(Val: FD));
6798 break;
6799 case CXXSpecialMemberKind::CopyConstructor:
6800 S.DefineImplicitCopyConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6801 break;
6802 case CXXSpecialMemberKind::CopyAssignment:
6803 S.DefineImplicitCopyAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6804 break;
6805 case CXXSpecialMemberKind::Destructor:
6806 S.DefineImplicitDestructor(CurrentLocation: DefaultLoc, Destructor: cast<CXXDestructorDecl>(Val: FD));
6807 break;
6808 case CXXSpecialMemberKind::MoveConstructor:
6809 S.DefineImplicitMoveConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6810 break;
6811 case CXXSpecialMemberKind::MoveAssignment:
6812 S.DefineImplicitMoveAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6813 break;
6814 case CXXSpecialMemberKind::Invalid:
6815 llvm_unreachable("Invalid special member.");
6816 }
6817}
6818
6819/// Determine whether a type is permitted to be passed or returned in
6820/// registers, per C++ [class.temporary]p3.
6821static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6822 TargetInfo::CallingConvKind CCK) {
6823 if (D->isDependentType() || D->isInvalidDecl())
6824 return false;
6825
6826 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6827 // The PS4 platform ABI follows the behavior of Clang 3.2.
6828 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6829 return !D->hasNonTrivialDestructorForCall() &&
6830 !D->hasNonTrivialCopyConstructorForCall();
6831
6832 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6833 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6834 bool DtorIsTrivialForCall = false;
6835
6836 // If a class has at least one eligible, trivial copy constructor, it
6837 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6838 //
6839 // Note: This permits classes with non-trivial copy or move ctors to be
6840 // passed in registers, so long as they *also* have a trivial copy ctor,
6841 // which is non-conforming.
6842 if (D->needsImplicitCopyConstructor()) {
6843 if (!D->defaultedCopyConstructorIsDeleted()) {
6844 if (D->hasTrivialCopyConstructor())
6845 CopyCtorIsTrivial = true;
6846 if (D->hasTrivialCopyConstructorForCall())
6847 CopyCtorIsTrivialForCall = true;
6848 }
6849 } else {
6850 for (const CXXConstructorDecl *CD : D->ctors()) {
6851 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6852 !CD->isIneligibleOrNotSelected()) {
6853 if (CD->isTrivial())
6854 CopyCtorIsTrivial = true;
6855 if (CD->isTrivialForCall())
6856 CopyCtorIsTrivialForCall = true;
6857 }
6858 }
6859 }
6860
6861 if (D->needsImplicitDestructor()) {
6862 if (!D->defaultedDestructorIsDeleted() &&
6863 D->hasTrivialDestructorForCall())
6864 DtorIsTrivialForCall = true;
6865 } else if (const auto *DD = D->getDestructor()) {
6866 if (!DD->isDeleted() && DD->isTrivialForCall())
6867 DtorIsTrivialForCall = true;
6868 }
6869
6870 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6871 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6872 return true;
6873
6874 // If a class has a destructor, we'd really like to pass it indirectly
6875 // because it allows us to elide copies. Unfortunately, MSVC makes that
6876 // impossible for small types, which it will pass in a single register or
6877 // stack slot. Most objects with dtors are large-ish, so handle that early.
6878 // We can't call out all large objects as being indirect because there are
6879 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6880 // how we pass large POD types.
6881
6882 // Note: This permits small classes with nontrivial destructors to be
6883 // passed in registers, which is non-conforming.
6884 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6885 uint64_t TypeSize = isAArch64 ? 128 : 64;
6886
6887 if (CopyCtorIsTrivial &&
6888 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6889 return true;
6890 return false;
6891 }
6892
6893 // Per C++ [class.temporary]p3, the relevant condition is:
6894 // each copy constructor, move constructor, and destructor of X is
6895 // either trivial or deleted, and X has at least one non-deleted copy
6896 // or move constructor
6897 bool HasNonDeletedCopyOrMove = false;
6898
6899 if (D->needsImplicitCopyConstructor() &&
6900 !D->defaultedCopyConstructorIsDeleted()) {
6901 if (!D->hasTrivialCopyConstructorForCall())
6902 return false;
6903 HasNonDeletedCopyOrMove = true;
6904 }
6905
6906 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6907 !D->defaultedMoveConstructorIsDeleted()) {
6908 if (!D->hasTrivialMoveConstructorForCall())
6909 return false;
6910 HasNonDeletedCopyOrMove = true;
6911 }
6912
6913 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6914 !D->hasTrivialDestructorForCall())
6915 return false;
6916
6917 for (const CXXMethodDecl *MD : D->methods()) {
6918 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6919 continue;
6920
6921 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6922 if (CD && CD->isCopyOrMoveConstructor())
6923 HasNonDeletedCopyOrMove = true;
6924 else if (!isa<CXXDestructorDecl>(Val: MD))
6925 continue;
6926
6927 if (!MD->isTrivialForCall())
6928 return false;
6929 }
6930
6931 return HasNonDeletedCopyOrMove;
6932}
6933
6934/// Report an error regarding overriding, along with any relevant
6935/// overridden methods.
6936///
6937/// \param DiagID the primary error to report.
6938/// \param MD the overriding method.
6939static bool
6940ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6941 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6942 bool IssuedDiagnostic = false;
6943 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6944 if (Report(O)) {
6945 if (!IssuedDiagnostic) {
6946 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6947 IssuedDiagnostic = true;
6948 }
6949 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6950 }
6951 }
6952 return IssuedDiagnostic;
6953}
6954
6955void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6956 if (!Record)
6957 return;
6958
6959 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6960 AbstractUsageInfo Info(*this, Record);
6961 CheckAbstractClassUsage(Info, RD: Record);
6962 }
6963
6964 // If this is not an aggregate type and has no user-declared constructor,
6965 // complain about any non-static data members of reference or const scalar
6966 // type, since they will never get initializers.
6967 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6968 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6969 !Record->isLambda()) {
6970 bool Complained = false;
6971 for (const auto *F : Record->fields()) {
6972 if (F->hasInClassInitializer() || F->isUnnamedBitField())
6973 continue;
6974
6975 if (F->getType()->isReferenceType() ||
6976 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6977 if (!Complained) {
6978 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6979 << Record->getTagKind() << Record;
6980 Complained = true;
6981 }
6982
6983 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6984 << F->getType()->isReferenceType()
6985 << F->getDeclName();
6986 }
6987 }
6988 }
6989
6990 if (Record->getIdentifier()) {
6991 // C++ [class.mem]p13:
6992 // If T is the name of a class, then each of the following shall have a
6993 // name different from T:
6994 // - every member of every anonymous union that is a member of class T.
6995 //
6996 // C++ [class.mem]p14:
6997 // In addition, if class T has a user-declared constructor (12.1), every
6998 // non-static data member of class T shall have a name different from T.
6999 DeclContext::lookup_result R = Record->lookup(Name: Record->getDeclName());
7000 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7001 ++I) {
7002 NamedDecl *D = (*I)->getUnderlyingDecl();
7003 if (((isa<FieldDecl>(Val: D) || isa<UnresolvedUsingValueDecl>(Val: D)) &&
7004 Record->hasUserDeclaredConstructor()) ||
7005 isa<IndirectFieldDecl>(Val: D)) {
7006 Diag((*I)->getLocation(), diag::err_member_name_of_class)
7007 << D->getDeclName();
7008 break;
7009 }
7010 }
7011 }
7012
7013 // Warn if the class has virtual methods but non-virtual public destructor.
7014 if (Record->isPolymorphic() && !Record->isDependentType()) {
7015 CXXDestructorDecl *dtor = Record->getDestructor();
7016 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7017 !Record->hasAttr<FinalAttr>())
7018 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7019 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
7020 }
7021
7022 if (Record->isAbstract()) {
7023 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7024 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7025 << FA->isSpelledAsSealed();
7026 DiagnoseAbstractType(RD: Record);
7027 }
7028 }
7029
7030 // Warn if the class has a final destructor but is not itself marked final.
7031 if (!Record->hasAttr<FinalAttr>()) {
7032 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7033 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7034 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7035 << FA->isSpelledAsSealed()
7036 << FixItHint::CreateInsertion(
7037 getLocForEndOfToken(Record->getLocation()),
7038 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7039 Diag(Record->getLocation(),
7040 diag::note_final_dtor_non_final_class_silence)
7041 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
7042 }
7043 }
7044 }
7045
7046 // See if trivial_abi has to be dropped.
7047 if (Record->hasAttr<TrivialABIAttr>())
7048 checkIllFormedTrivialABIStruct(RD&: *Record);
7049
7050 // Set HasTrivialSpecialMemberForCall if the record has attribute
7051 // "trivial_abi".
7052 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7053
7054 if (HasTrivialABI)
7055 Record->setHasTrivialSpecialMemberForCall();
7056
7057 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7058 // We check these last because they can depend on the properties of the
7059 // primary comparison functions (==, <=>).
7060 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7061
7062 // Perform checks that can't be done until we know all the properties of a
7063 // member function (whether it's defaulted, deleted, virtual, overriding,
7064 // ...).
7065 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7066 // A static function cannot override anything.
7067 if (MD->getStorageClass() == SC_Static) {
7068 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7069 [](const CXXMethodDecl *) { return true; }))
7070 return;
7071 }
7072
7073 // A deleted function cannot override a non-deleted function and vice
7074 // versa.
7075 if (ReportOverrides(*this,
7076 MD->isDeleted() ? diag::err_deleted_override
7077 : diag::err_non_deleted_override,
7078 MD, [&](const CXXMethodDecl *V) {
7079 return MD->isDeleted() != V->isDeleted();
7080 })) {
7081 if (MD->isDefaulted() && MD->isDeleted())
7082 // Explain why this defaulted function was deleted.
7083 DiagnoseDeletedDefaultedFunction(MD);
7084 return;
7085 }
7086
7087 // A consteval function cannot override a non-consteval function and vice
7088 // versa.
7089 if (ReportOverrides(*this,
7090 MD->isConsteval() ? diag::err_consteval_override
7091 : diag::err_non_consteval_override,
7092 MD, [&](const CXXMethodDecl *V) {
7093 return MD->isConsteval() != V->isConsteval();
7094 })) {
7095 if (MD->isDefaulted() && MD->isDeleted())
7096 // Explain why this defaulted function was deleted.
7097 DiagnoseDeletedDefaultedFunction(MD);
7098 return;
7099 }
7100 };
7101
7102 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7103 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7104 return false;
7105
7106 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7107 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7108 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7109 DefaultedSecondaryComparisons.push_back(Elt: FD);
7110 return true;
7111 }
7112
7113 CheckExplicitlyDefaultedFunction(S, MD: FD);
7114 return false;
7115 };
7116
7117 if (!Record->isInvalidDecl() &&
7118 Record->hasAttr<VTablePointerAuthenticationAttr>())
7119 checkIncorrectVTablePointerAuthenticationAttribute(RD&: *Record);
7120
7121 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7122 // Check whether the explicitly-defaulted members are valid.
7123 bool Incomplete = CheckForDefaultedFunction(M);
7124
7125 // Skip the rest of the checks for a member of a dependent class.
7126 if (Record->isDependentType())
7127 return;
7128
7129 // For an explicitly defaulted or deleted special member, we defer
7130 // determining triviality until the class is complete. That time is now!
7131 CXXSpecialMemberKind CSM = getSpecialMember(MD: M);
7132 if (!M->isImplicit() && !M->isUserProvided()) {
7133 if (CSM != CXXSpecialMemberKind::Invalid) {
7134 M->setTrivial(SpecialMemberIsTrivial(MD: M, CSM));
7135 // Inform the class that we've finished declaring this member.
7136 Record->finishedDefaultedOrDeletedMember(MD: M);
7137 M->setTrivialForCall(
7138 HasTrivialABI ||
7139 SpecialMemberIsTrivial(MD: M, CSM,
7140 TAH: TrivialABIHandling::ConsiderTrivialABI));
7141 Record->setTrivialForCallFlags(M);
7142 }
7143 }
7144
7145 // Set triviality for the purpose of calls if this is a user-provided
7146 // copy/move constructor or destructor.
7147 if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7148 CSM == CXXSpecialMemberKind::MoveConstructor ||
7149 CSM == CXXSpecialMemberKind::Destructor) &&
7150 M->isUserProvided()) {
7151 M->setTrivialForCall(HasTrivialABI);
7152 Record->setTrivialForCallFlags(M);
7153 }
7154
7155 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7156 M->hasAttr<DLLExportAttr>()) {
7157 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7158 M->isTrivial() &&
7159 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7160 CSM == CXXSpecialMemberKind::CopyConstructor ||
7161 CSM == CXXSpecialMemberKind::Destructor))
7162 M->dropAttr<DLLExportAttr>();
7163
7164 if (M->hasAttr<DLLExportAttr>()) {
7165 // Define after any fields with in-class initializers have been parsed.
7166 DelayedDllExportMemberFunctions.push_back(Elt: M);
7167 }
7168 }
7169
7170 bool EffectivelyConstexprDestructor = true;
7171 // Avoid triggering vtable instantiation due to a dtor that is not
7172 // "effectively constexpr" for better compatibility.
7173 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7174 if (isa<CXXDestructorDecl>(Val: M)) {
7175 auto Check = [](QualType T, auto &&Check) -> bool {
7176 const CXXRecordDecl *RD =
7177 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7178 if (!RD || !RD->isCompleteDefinition())
7179 return true;
7180
7181 if (!RD->hasConstexprDestructor())
7182 return false;
7183
7184 QualType CanUnqualT = T.getCanonicalType().getUnqualifiedType();
7185 for (const CXXBaseSpecifier &B : RD->bases())
7186 if (B.getType().getCanonicalType().getUnqualifiedType() !=
7187 CanUnqualT &&
7188 !Check(B.getType(), Check))
7189 return false;
7190 for (const FieldDecl *FD : RD->fields())
7191 if (FD->getType().getCanonicalType().getUnqualifiedType() !=
7192 CanUnqualT &&
7193 !Check(FD->getType(), Check))
7194 return false;
7195 return true;
7196 };
7197 EffectivelyConstexprDestructor =
7198 Check(QualType(Record->getTypeForDecl(), 0), Check);
7199 }
7200
7201 // Define defaulted constexpr virtual functions that override a base class
7202 // function right away.
7203 // FIXME: We can defer doing this until the vtable is marked as used.
7204 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7205 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7206 EffectivelyConstexprDestructor)
7207 DefineDefaultedFunction(*this, M, M->getLocation());
7208
7209 if (!Incomplete)
7210 CheckCompletedMemberFunction(M);
7211 };
7212
7213 // Check the destructor before any other member function. We need to
7214 // determine whether it's trivial in order to determine whether the claas
7215 // type is a literal type, which is a prerequisite for determining whether
7216 // other special member functions are valid and whether they're implicitly
7217 // 'constexpr'.
7218 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7219 CompleteMemberFunction(Dtor);
7220
7221 bool HasMethodWithOverrideControl = false,
7222 HasOverridingMethodWithoutOverrideControl = false;
7223 for (auto *D : Record->decls()) {
7224 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7225 // FIXME: We could do this check for dependent types with non-dependent
7226 // bases.
7227 if (!Record->isDependentType()) {
7228 // See if a method overloads virtual methods in a base
7229 // class without overriding any.
7230 if (!M->isStatic())
7231 DiagnoseHiddenVirtualMethods(M);
7232
7233 if (M->hasAttr<OverrideAttr>()) {
7234 HasMethodWithOverrideControl = true;
7235 } else if (M->size_overridden_methods() > 0) {
7236 HasOverridingMethodWithoutOverrideControl = true;
7237 } else {
7238 // Warn on newly-declared virtual methods in `final` classes
7239 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7240 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7241 << M;
7242 }
7243 }
7244 }
7245
7246 if (!isa<CXXDestructorDecl>(M))
7247 CompleteMemberFunction(M);
7248 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7249 CheckForDefaultedFunction(
7250 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7251 }
7252 }
7253
7254 if (HasOverridingMethodWithoutOverrideControl) {
7255 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7256 for (auto *M : Record->methods())
7257 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7258 }
7259
7260 // Check the defaulted secondary comparisons after any other member functions.
7261 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7262 CheckExplicitlyDefaultedFunction(S, MD: FD);
7263
7264 // If this is a member function, we deferred checking it until now.
7265 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
7266 CheckCompletedMemberFunction(MD);
7267 }
7268
7269 // ms_struct is a request to use the same ABI rules as MSVC. Check
7270 // whether this class uses any C++ features that are implemented
7271 // completely differently in MSVC, and if so, emit a diagnostic.
7272 // That diagnostic defaults to an error, but we allow projects to
7273 // map it down to a warning (or ignore it). It's a fairly common
7274 // practice among users of the ms_struct pragma to mass-annotate
7275 // headers, sweeping up a bunch of types that the project doesn't
7276 // really rely on MSVC-compatible layout for. We must therefore
7277 // support "ms_struct except for C++ stuff" as a secondary ABI.
7278 // Don't emit this diagnostic if the feature was enabled as a
7279 // language option (as opposed to via a pragma or attribute), as
7280 // the option -mms-bitfields otherwise essentially makes it impossible
7281 // to build C++ code, unless this diagnostic is turned off.
7282 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7283 (Record->isPolymorphic() || Record->getNumBases())) {
7284 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7285 }
7286
7287 checkClassLevelDLLAttribute(Class: Record);
7288 checkClassLevelCodeSegAttribute(Class: Record);
7289
7290 bool ClangABICompat4 =
7291 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7292 TargetInfo::CallingConvKind CCK =
7293 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7294 bool CanPass = canPassInRegisters(S&: *this, D: Record, CCK);
7295
7296 // Do not change ArgPassingRestrictions if it has already been set to
7297 // RecordArgPassingKind::CanNeverPassInRegs.
7298 if (Record->getArgPassingRestrictions() !=
7299 RecordArgPassingKind::CanNeverPassInRegs)
7300 Record->setArgPassingRestrictions(
7301 CanPass ? RecordArgPassingKind::CanPassInRegs
7302 : RecordArgPassingKind::CannotPassInRegs);
7303
7304 // If canPassInRegisters returns true despite the record having a non-trivial
7305 // destructor, the record is destructed in the callee. This happens only when
7306 // the record or one of its subobjects has a field annotated with trivial_abi
7307 // or a field qualified with ObjC __strong/__weak.
7308 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7309 Record->setParamDestroyedInCallee(true);
7310 else if (Record->hasNonTrivialDestructor())
7311 Record->setParamDestroyedInCallee(CanPass);
7312
7313 if (getLangOpts().ForceEmitVTables) {
7314 // If we want to emit all the vtables, we need to mark it as used. This
7315 // is especially required for cases like vtable assumption loads.
7316 MarkVTableUsed(Loc: Record->getInnerLocStart(), Class: Record);
7317 }
7318
7319 if (getLangOpts().CUDA) {
7320 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7321 checkCUDADeviceBuiltinSurfaceClassTemplate(S&: *this, Class: Record);
7322 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7323 checkCUDADeviceBuiltinTextureClassTemplate(S&: *this, Class: Record);
7324 }
7325
7326 llvm::SmallDenseMap<OverloadedOperatorKind,
7327 llvm::SmallVector<const FunctionDecl *, 2>, 4>
7328 TypeAwareDecls{{OO_New, {}},
7329 {OO_Array_New, {}},
7330 {OO_Delete, {}},
7331 {OO_Array_New, {}}};
7332 for (auto *D : Record->decls()) {
7333 const FunctionDecl *FnDecl = D->getAsFunction();
7334 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7335 continue;
7336 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7337 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7338 }
7339 auto CheckMismatchedTypeAwareAllocators =
7340 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7341 OverloadedOperatorKind DeleteKind) {
7342 auto &NewDecls = TypeAwareDecls[NewKind];
7343 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7344 if (NewDecls.empty() == DeleteDecls.empty())
7345 return;
7346 DeclarationName FoundOperator =
7347 Context.DeclarationNames.getCXXOperatorName(
7348 Op: NewDecls.empty() ? DeleteKind : NewKind);
7349 DeclarationName MissingOperator =
7350 Context.DeclarationNames.getCXXOperatorName(
7351 Op: NewDecls.empty() ? NewKind : DeleteKind);
7352 Diag(Record->getLocation(),
7353 diag::err_type_aware_allocator_missing_matching_operator)
7354 << FoundOperator << Context.getRecordType(Record)
7355 << MissingOperator;
7356 for (auto MD : NewDecls)
7357 Diag(MD->getLocation(),
7358 diag::note_unmatched_type_aware_allocator_declared)
7359 << MD;
7360 for (auto MD : DeleteDecls)
7361 Diag(MD->getLocation(),
7362 diag::note_unmatched_type_aware_allocator_declared)
7363 << MD;
7364 };
7365 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7366 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7367}
7368
7369/// Look up the special member function that would be called by a special
7370/// member function for a subobject of class type.
7371///
7372/// \param Class The class type of the subobject.
7373/// \param CSM The kind of special member function.
7374/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7375/// \param ConstRHS True if this is a copy operation with a const object
7376/// on its RHS, that is, if the argument to the outer special member
7377/// function is 'const' and this is not a field marked 'mutable'.
7378static Sema::SpecialMemberOverloadResult
7379lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7380 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7381 bool ConstRHS) {
7382 unsigned LHSQuals = 0;
7383 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7384 CSM == CXXSpecialMemberKind::MoveAssignment)
7385 LHSQuals = FieldQuals;
7386
7387 unsigned RHSQuals = FieldQuals;
7388 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7389 CSM == CXXSpecialMemberKind::Destructor)
7390 RHSQuals = 0;
7391 else if (ConstRHS)
7392 RHSQuals |= Qualifiers::Const;
7393
7394 return S.LookupSpecialMember(D: Class, SM: CSM,
7395 ConstArg: RHSQuals & Qualifiers::Const,
7396 VolatileArg: RHSQuals & Qualifiers::Volatile,
7397 RValueThis: false,
7398 ConstThis: LHSQuals & Qualifiers::Const,
7399 VolatileThis: LHSQuals & Qualifiers::Volatile);
7400}
7401
7402class Sema::InheritedConstructorInfo {
7403 Sema &S;
7404 SourceLocation UseLoc;
7405
7406 /// A mapping from the base classes through which the constructor was
7407 /// inherited to the using shadow declaration in that base class (or a null
7408 /// pointer if the constructor was declared in that base class).
7409 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7410 InheritedFromBases;
7411
7412public:
7413 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7414 ConstructorUsingShadowDecl *Shadow)
7415 : S(S), UseLoc(UseLoc) {
7416 bool DiagnosedMultipleConstructedBases = false;
7417 CXXRecordDecl *ConstructedBase = nullptr;
7418 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7419
7420 // Find the set of such base class subobjects and check that there's a
7421 // unique constructed subobject.
7422 for (auto *D : Shadow->redecls()) {
7423 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7424 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7425 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7426
7427 InheritedFromBases.insert(
7428 std::make_pair(DNominatedBase->getCanonicalDecl(),
7429 DShadow->getNominatedBaseClassShadowDecl()));
7430 if (DShadow->constructsVirtualBase())
7431 InheritedFromBases.insert(
7432 std::make_pair(DConstructedBase->getCanonicalDecl(),
7433 DShadow->getConstructedBaseClassShadowDecl()));
7434 else
7435 assert(DNominatedBase == DConstructedBase);
7436
7437 // [class.inhctor.init]p2:
7438 // If the constructor was inherited from multiple base class subobjects
7439 // of type B, the program is ill-formed.
7440 if (!ConstructedBase) {
7441 ConstructedBase = DConstructedBase;
7442 ConstructedBaseIntroducer = D->getIntroducer();
7443 } else if (ConstructedBase != DConstructedBase &&
7444 !Shadow->isInvalidDecl()) {
7445 if (!DiagnosedMultipleConstructedBases) {
7446 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7447 << Shadow->getTargetDecl();
7448 S.Diag(ConstructedBaseIntroducer->getLocation(),
7449 diag::note_ambiguous_inherited_constructor_using)
7450 << ConstructedBase;
7451 DiagnosedMultipleConstructedBases = true;
7452 }
7453 S.Diag(D->getIntroducer()->getLocation(),
7454 diag::note_ambiguous_inherited_constructor_using)
7455 << DConstructedBase;
7456 }
7457 }
7458
7459 if (DiagnosedMultipleConstructedBases)
7460 Shadow->setInvalidDecl();
7461 }
7462
7463 /// Find the constructor to use for inherited construction of a base class,
7464 /// and whether that base class constructor inherits the constructor from a
7465 /// virtual base class (in which case it won't actually invoke it).
7466 std::pair<CXXConstructorDecl *, bool>
7467 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7468 auto It = InheritedFromBases.find(Val: Base->getCanonicalDecl());
7469 if (It == InheritedFromBases.end())
7470 return std::make_pair(x: nullptr, y: false);
7471
7472 // This is an intermediary class.
7473 if (It->second)
7474 return std::make_pair(
7475 x: S.findInheritingConstructor(Loc: UseLoc, BaseCtor: Ctor, DerivedShadow: It->second),
7476 y: It->second->constructsVirtualBase());
7477
7478 // This is the base class from which the constructor was inherited.
7479 return std::make_pair(x&: Ctor, y: false);
7480 }
7481};
7482
7483/// Is the special member function which would be selected to perform the
7484/// specified operation on the specified class type a constexpr constructor?
7485static bool specialMemberIsConstexpr(
7486 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7487 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7488 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7489 // Suppress duplicate constraint checking here, in case a constraint check
7490 // caused us to decide to do this. Any truely recursive checks will get
7491 // caught during these checks anyway.
7492 Sema::SatisfactionStackResetRAII SSRAII{S};
7493
7494 // If we're inheriting a constructor, see if we need to call it for this base
7495 // class.
7496 if (InheritedCtor) {
7497 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7498 auto BaseCtor =
7499 Inherited->findConstructorForBase(Base: ClassDecl, Ctor: InheritedCtor).first;
7500 if (BaseCtor)
7501 return BaseCtor->isConstexpr();
7502 }
7503
7504 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7505 return ClassDecl->hasConstexprDefaultConstructor();
7506 if (CSM == CXXSpecialMemberKind::Destructor)
7507 return ClassDecl->hasConstexprDestructor();
7508
7509 Sema::SpecialMemberOverloadResult SMOR =
7510 lookupCallFromSpecialMember(S, Class: ClassDecl, CSM, FieldQuals: Quals, ConstRHS);
7511 if (!SMOR.getMethod())
7512 // A constructor we wouldn't select can't be "involved in initializing"
7513 // anything.
7514 return true;
7515 return SMOR.getMethod()->isConstexpr();
7516}
7517
7518/// Determine whether the specified special member function would be constexpr
7519/// if it were implicitly defined.
7520static bool defaultedSpecialMemberIsConstexpr(
7521 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7522 CXXConstructorDecl *InheritedCtor = nullptr,
7523 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7524 if (!S.getLangOpts().CPlusPlus11)
7525 return false;
7526
7527 // C++11 [dcl.constexpr]p4:
7528 // In the definition of a constexpr constructor [...]
7529 bool Ctor = true;
7530 switch (CSM) {
7531 case CXXSpecialMemberKind::DefaultConstructor:
7532 if (Inherited)
7533 break;
7534 // Since default constructor lookup is essentially trivial (and cannot
7535 // involve, for instance, template instantiation), we compute whether a
7536 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7537 //
7538 // This is important for performance; we need to know whether the default
7539 // constructor is constexpr to determine whether the type is a literal type.
7540 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7541
7542 case CXXSpecialMemberKind::CopyConstructor:
7543 case CXXSpecialMemberKind::MoveConstructor:
7544 // For copy or move constructors, we need to perform overload resolution.
7545 break;
7546
7547 case CXXSpecialMemberKind::CopyAssignment:
7548 case CXXSpecialMemberKind::MoveAssignment:
7549 if (!S.getLangOpts().CPlusPlus14)
7550 return false;
7551 // In C++1y, we need to perform overload resolution.
7552 Ctor = false;
7553 break;
7554
7555 case CXXSpecialMemberKind::Destructor:
7556 return ClassDecl->defaultedDestructorIsConstexpr();
7557
7558 case CXXSpecialMemberKind::Invalid:
7559 return false;
7560 }
7561
7562 // -- if the class is a non-empty union, or for each non-empty anonymous
7563 // union member of a non-union class, exactly one non-static data member
7564 // shall be initialized; [DR1359]
7565 //
7566 // If we squint, this is guaranteed, since exactly one non-static data member
7567 // will be initialized (if the constructor isn't deleted), we just don't know
7568 // which one.
7569 if (Ctor && ClassDecl->isUnion())
7570 return CSM == CXXSpecialMemberKind::DefaultConstructor
7571 ? ClassDecl->hasInClassInitializer() ||
7572 !ClassDecl->hasVariantMembers()
7573 : true;
7574
7575 // -- the class shall not have any virtual base classes;
7576 if (Ctor && ClassDecl->getNumVBases())
7577 return false;
7578
7579 // C++1y [class.copy]p26:
7580 // -- [the class] is a literal type, and
7581 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7582 return false;
7583
7584 // -- every constructor involved in initializing [...] base class
7585 // sub-objects shall be a constexpr constructor;
7586 // -- the assignment operator selected to copy/move each direct base
7587 // class is a constexpr function, and
7588 if (!S.getLangOpts().CPlusPlus23) {
7589 for (const auto &B : ClassDecl->bases()) {
7590 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7591 if (!BaseType)
7592 continue;
7593 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(Val: BaseType->getDecl());
7594 if (!specialMemberIsConstexpr(S, ClassDecl: BaseClassDecl, CSM, Quals: 0, ConstRHS: ConstArg,
7595 InheritedCtor, Inherited))
7596 return false;
7597 }
7598 }
7599
7600 // -- every constructor involved in initializing non-static data members
7601 // [...] shall be a constexpr constructor;
7602 // -- every non-static data member and base class sub-object shall be
7603 // initialized
7604 // -- for each non-static data member of X that is of class type (or array
7605 // thereof), the assignment operator selected to copy/move that member is
7606 // a constexpr function
7607 if (!S.getLangOpts().CPlusPlus23) {
7608 for (const auto *F : ClassDecl->fields()) {
7609 if (F->isInvalidDecl())
7610 continue;
7611 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7612 F->hasInClassInitializer())
7613 continue;
7614 QualType BaseType = S.Context.getBaseElementType(F->getType());
7615 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7616 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7617 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7618 BaseType.getCVRQualifiers(),
7619 ConstArg && !F->isMutable()))
7620 return false;
7621 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7622 return false;
7623 }
7624 }
7625 }
7626
7627 // All OK, it's constexpr!
7628 return true;
7629}
7630
7631namespace {
7632/// RAII object to register a defaulted function as having its exception
7633/// specification computed.
7634struct ComputingExceptionSpec {
7635 Sema &S;
7636
7637 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7638 : S(S) {
7639 Sema::CodeSynthesisContext Ctx;
7640 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7641 Ctx.PointOfInstantiation = Loc;
7642 Ctx.Entity = FD;
7643 S.pushCodeSynthesisContext(Ctx);
7644 }
7645 ~ComputingExceptionSpec() {
7646 S.popCodeSynthesisContext();
7647 }
7648};
7649}
7650
7651static Sema::ImplicitExceptionSpecification
7652ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7653 CXXMethodDecl *MD,
7654 CXXSpecialMemberKind CSM,
7655 Sema::InheritedConstructorInfo *ICI);
7656
7657static Sema::ImplicitExceptionSpecification
7658ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7659 FunctionDecl *FD,
7660 Sema::DefaultedComparisonKind DCK);
7661
7662static Sema::ImplicitExceptionSpecification
7663computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7664 auto DFK = S.getDefaultedFunctionKind(FD);
7665 if (DFK.isSpecialMember())
7666 return ComputeDefaultedSpecialMemberExceptionSpec(
7667 S, Loc, MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), ICI: nullptr);
7668 if (DFK.isComparison())
7669 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7670 DCK: DFK.asComparison());
7671
7672 auto *CD = cast<CXXConstructorDecl>(Val: FD);
7673 assert(CD->getInheritedConstructor() &&
7674 "only defaulted functions and inherited constructors have implicit "
7675 "exception specs");
7676 Sema::InheritedConstructorInfo ICI(
7677 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7678 return ComputeDefaultedSpecialMemberExceptionSpec(
7679 S, Loc, CD, CXXSpecialMemberKind::DefaultConstructor, &ICI);
7680}
7681
7682static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7683 CXXMethodDecl *MD) {
7684 FunctionProtoType::ExtProtoInfo EPI;
7685
7686 // Build an exception specification pointing back at this member.
7687 EPI.ExceptionSpec.Type = EST_Unevaluated;
7688 EPI.ExceptionSpec.SourceDecl = MD;
7689
7690 // Set the calling convention to the default for C++ instance methods.
7691 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7692 cc: S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7693 /*IsCXXMethod=*/true));
7694 return EPI;
7695}
7696
7697void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7698 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7699 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7700 return;
7701
7702 // Evaluate the exception specification.
7703 auto IES = computeImplicitExceptionSpec(S&: *this, Loc, FD);
7704 auto ESI = IES.getExceptionSpec();
7705
7706 // Update the type of the special member to use it.
7707 UpdateExceptionSpec(FD, ESI);
7708}
7709
7710void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7711 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7712
7713 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7714 if (!DefKind) {
7715 assert(FD->getDeclContext()->isDependentContext());
7716 return;
7717 }
7718
7719 if (DefKind.isComparison()) {
7720 auto PT = FD->getParamDecl(i: 0)->getType();
7721 if (const CXXRecordDecl *RD =
7722 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7723 for (FieldDecl *Field : RD->fields()) {
7724 UnusedPrivateFields.remove(Field);
7725 }
7726 }
7727 }
7728
7729 if (DefKind.isSpecialMember()
7730 ? CheckExplicitlyDefaultedSpecialMember(MD: cast<CXXMethodDecl>(Val: FD),
7731 CSM: DefKind.asSpecialMember(),
7732 DefaultLoc: FD->getDefaultLoc())
7733 : CheckExplicitlyDefaultedComparison(S, MD: FD, DCK: DefKind.asComparison()))
7734 FD->setInvalidDecl();
7735}
7736
7737bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7738 CXXSpecialMemberKind CSM,
7739 SourceLocation DefaultLoc) {
7740 CXXRecordDecl *RD = MD->getParent();
7741
7742 assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7743 "not an explicitly-defaulted special member");
7744
7745 // Defer all checking for special members of a dependent type.
7746 if (RD->isDependentType())
7747 return false;
7748
7749 // Whether this was the first-declared instance of the constructor.
7750 // This affects whether we implicitly add an exception spec and constexpr.
7751 bool First = MD == MD->getCanonicalDecl();
7752
7753 bool HadError = false;
7754
7755 // C++11 [dcl.fct.def.default]p1:
7756 // A function that is explicitly defaulted shall
7757 // -- be a special member function [...] (checked elsewhere),
7758 // -- have the same type (except for ref-qualifiers, and except that a
7759 // copy operation can take a non-const reference) as an implicit
7760 // declaration, and
7761 // -- not have default arguments.
7762 // C++2a changes the second bullet to instead delete the function if it's
7763 // defaulted on its first declaration, unless it's "an assignment operator,
7764 // and its return type differs or its parameter type is not a reference".
7765 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7766 bool ShouldDeleteForTypeMismatch = false;
7767 unsigned ExpectedParams = 1;
7768 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7769 CSM == CXXSpecialMemberKind::Destructor)
7770 ExpectedParams = 0;
7771 if (MD->getNumExplicitParams() != ExpectedParams) {
7772 // This checks for default arguments: a copy or move constructor with a
7773 // default argument is classified as a default constructor, and assignment
7774 // operations and destructors can't have default arguments.
7775 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7776 << CSM << MD->getSourceRange();
7777 HadError = true;
7778 } else if (MD->isVariadic()) {
7779 if (DeleteOnTypeMismatch)
7780 ShouldDeleteForTypeMismatch = true;
7781 else {
7782 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7783 << CSM << MD->getSourceRange();
7784 HadError = true;
7785 }
7786 }
7787
7788 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7789
7790 bool CanHaveConstParam = false;
7791 if (CSM == CXXSpecialMemberKind::CopyConstructor)
7792 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7793 else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7794 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7795
7796 QualType ReturnType = Context.VoidTy;
7797 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7798 CSM == CXXSpecialMemberKind::MoveAssignment) {
7799 // Check for return type matching.
7800 ReturnType = Type->getReturnType();
7801 QualType ThisType = MD->getFunctionObjectParameterType();
7802
7803 QualType DeclType = Context.getTypeDeclType(RD);
7804 DeclType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
7805 NamedType: DeclType, OwnedTagDecl: nullptr);
7806 DeclType = Context.getAddrSpaceQualType(
7807 T: DeclType, AddressSpace: ThisType.getQualifiers().getAddressSpace());
7808 QualType ExpectedReturnType = Context.getLValueReferenceType(T: DeclType);
7809
7810 if (!Context.hasSameType(T1: ReturnType, T2: ExpectedReturnType)) {
7811 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7812 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7813 << ExpectedReturnType;
7814 HadError = true;
7815 }
7816
7817 // A defaulted special member cannot have cv-qualifiers.
7818 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7819 if (DeleteOnTypeMismatch)
7820 ShouldDeleteForTypeMismatch = true;
7821 else {
7822 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7823 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7824 << getLangOpts().CPlusPlus14;
7825 HadError = true;
7826 }
7827 }
7828 // [C++23][dcl.fct.def.default]/p2.2
7829 // if F2 has an implicit object parameter of type “reference to C”,
7830 // F1 may be an explicit object member function whose explicit object
7831 // parameter is of (possibly different) type “reference to C”,
7832 // in which case the type of F1 would differ from the type of F2
7833 // in that the type of F1 has an additional parameter;
7834 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7835 ? MD->getParamDecl(0)->getType()
7836 : QualType();
7837 if (!ExplicitObjectParameter.isNull() &&
7838 (!ExplicitObjectParameter->isReferenceType() ||
7839 !Context.hasSameType(T1: ExplicitObjectParameter.getNonReferenceType(),
7840 T2: Context.getRecordType(RD)))) {
7841 if (DeleteOnTypeMismatch)
7842 ShouldDeleteForTypeMismatch = true;
7843 else {
7844 Diag(MD->getLocation(),
7845 diag::err_defaulted_special_member_explicit_object_mismatch)
7846 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7847 << MD->getSourceRange();
7848 HadError = true;
7849 }
7850 }
7851 }
7852
7853 // Check for parameter type matching.
7854 QualType ArgType =
7855 ExpectedParams
7856 ? Type->getParamType(i: MD->isExplicitObjectMemberFunction() ? 1 : 0)
7857 : QualType();
7858 bool HasConstParam = false;
7859 if (ExpectedParams && ArgType->isReferenceType()) {
7860 // Argument must be reference to possibly-const T.
7861 QualType ReferentType = ArgType->getPointeeType();
7862 HasConstParam = ReferentType.isConstQualified();
7863
7864 if (ReferentType.isVolatileQualified()) {
7865 if (DeleteOnTypeMismatch)
7866 ShouldDeleteForTypeMismatch = true;
7867 else {
7868 Diag(MD->getLocation(),
7869 diag::err_defaulted_special_member_volatile_param)
7870 << CSM;
7871 HadError = true;
7872 }
7873 }
7874
7875 if (HasConstParam && !CanHaveConstParam) {
7876 if (DeleteOnTypeMismatch)
7877 ShouldDeleteForTypeMismatch = true;
7878 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7879 CSM == CXXSpecialMemberKind::CopyAssignment) {
7880 Diag(MD->getLocation(),
7881 diag::err_defaulted_special_member_copy_const_param)
7882 << (CSM == CXXSpecialMemberKind::CopyAssignment);
7883 // FIXME: Explain why this special member can't be const.
7884 HadError = true;
7885 } else {
7886 Diag(MD->getLocation(),
7887 diag::err_defaulted_special_member_move_const_param)
7888 << (CSM == CXXSpecialMemberKind::MoveAssignment);
7889 HadError = true;
7890 }
7891 }
7892 } else if (ExpectedParams) {
7893 // A copy assignment operator can take its argument by value, but a
7894 // defaulted one cannot.
7895 assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
7896 "unexpected non-ref argument");
7897 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7898 HadError = true;
7899 }
7900
7901 // C++11 [dcl.fct.def.default]p2:
7902 // An explicitly-defaulted function may be declared constexpr only if it
7903 // would have been implicitly declared as constexpr,
7904 // Do not apply this rule to members of class templates, since core issue 1358
7905 // makes such functions always instantiate to constexpr functions. For
7906 // functions which cannot be constexpr (for non-constructors in C++11 and for
7907 // destructors in C++14 and C++17), this is checked elsewhere.
7908 //
7909 // FIXME: This should not apply if the member is deleted.
7910 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: RD, CSM,
7911 ConstArg: HasConstParam);
7912
7913 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7914 // If the instantiated template specialization of a constexpr function
7915 // template or member function of a class template would fail to satisfy
7916 // the requirements for a constexpr function or constexpr constructor, that
7917 // specialization is still a constexpr function or constexpr constructor,
7918 // even though a call to such a function cannot appear in a constant
7919 // expression.
7920 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7921 Constexpr = true;
7922
7923 if ((getLangOpts().CPlusPlus20 ||
7924 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(Val: MD)
7925 : isa<CXXConstructorDecl>(Val: MD))) &&
7926 MD->isConstexpr() && !Constexpr &&
7927 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7928 if (!MD->isConsteval() && RD->getNumVBases()) {
7929 Diag(MD->getBeginLoc(),
7930 diag::err_incorrect_defaulted_constexpr_with_vb)
7931 << CSM;
7932 for (const auto &I : RD->vbases())
7933 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7934 } else {
7935 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7936 << CSM << MD->isConsteval();
7937 }
7938 HadError = true;
7939 // FIXME: Explain why the special member can't be constexpr.
7940 }
7941
7942 if (First) {
7943 // C++2a [dcl.fct.def.default]p3:
7944 // If a function is explicitly defaulted on its first declaration, it is
7945 // implicitly considered to be constexpr if the implicit declaration
7946 // would be.
7947 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7948 ? ConstexprSpecKind::Consteval
7949 : ConstexprSpecKind::Constexpr)
7950 : ConstexprSpecKind::Unspecified);
7951
7952 if (!Type->hasExceptionSpec()) {
7953 // C++2a [except.spec]p3:
7954 // If a declaration of a function does not have a noexcept-specifier
7955 // [and] is defaulted on its first declaration, [...] the exception
7956 // specification is as specified below
7957 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7958 EPI.ExceptionSpec.Type = EST_Unevaluated;
7959 EPI.ExceptionSpec.SourceDecl = MD;
7960 MD->setType(
7961 Context.getFunctionType(ResultTy: ReturnType, Args: Type->getParamTypes(), EPI));
7962 }
7963 }
7964
7965 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7966 if (First) {
7967 SetDeclDeleted(dcl: MD, DelLoc: MD->getLocation());
7968 if (!inTemplateInstantiation() && !HadError) {
7969 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7970 if (ShouldDeleteForTypeMismatch) {
7971 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7972 } else if (ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr,
7973 /*Diagnose*/ true) &&
7974 DefaultLoc.isValid()) {
7975 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7976 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7977 }
7978 }
7979 if (ShouldDeleteForTypeMismatch && !HadError) {
7980 Diag(MD->getLocation(),
7981 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7982 << CSM;
7983 }
7984 } else {
7985 // C++11 [dcl.fct.def.default]p4:
7986 // [For a] user-provided explicitly-defaulted function [...] if such a
7987 // function is implicitly defined as deleted, the program is ill-formed.
7988 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7989 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7990 ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, /*Diagnose*/true);
7991 HadError = true;
7992 }
7993 }
7994
7995 return HadError;
7996}
7997
7998namespace {
7999/// Helper class for building and checking a defaulted comparison.
8000///
8001/// Defaulted functions are built in two phases:
8002///
8003/// * First, the set of operations that the function will perform are
8004/// identified, and some of them are checked. If any of the checked
8005/// operations is invalid in certain ways, the comparison function is
8006/// defined as deleted and no body is built.
8007/// * Then, if the function is not defined as deleted, the body is built.
8008///
8009/// This is accomplished by performing two visitation steps over the eventual
8010/// body of the function.
8011template<typename Derived, typename ResultList, typename Result,
8012 typename Subobject>
8013class DefaultedComparisonVisitor {
8014public:
8015 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
8016
8017 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8018 DefaultedComparisonKind DCK)
8019 : S(S), RD(RD), FD(FD), DCK(DCK) {
8020 if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
8021 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8022 // UnresolvedSet to avoid this copy.
8023 Fns.assign(I: Info->getUnqualifiedLookups().begin(),
8024 E: Info->getUnqualifiedLookups().end());
8025 }
8026 }
8027
8028 ResultList visit() {
8029 // The type of an lvalue naming a parameter of this function.
8030 QualType ParamLvalType =
8031 FD->getParamDecl(i: 0)->getType().getNonReferenceType();
8032
8033 ResultList Results;
8034
8035 switch (DCK) {
8036 case DefaultedComparisonKind::None:
8037 llvm_unreachable("not a defaulted comparison");
8038
8039 case DefaultedComparisonKind::Equal:
8040 case DefaultedComparisonKind::ThreeWay:
8041 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8042 return Results;
8043
8044 case DefaultedComparisonKind::NotEqual:
8045 case DefaultedComparisonKind::Relational:
8046 Results.add(getDerived().visitExpandedSubobject(
8047 ParamLvalType, getDerived().getCompleteObject()));
8048 return Results;
8049 }
8050 llvm_unreachable("");
8051 }
8052
8053protected:
8054 Derived &getDerived() { return static_cast<Derived&>(*this); }
8055
8056 /// Visit the expanded list of subobjects of the given type, as specified in
8057 /// C++2a [class.compare.default].
8058 ///
8059 /// \return \c true if the ResultList object said we're done, \c false if not.
8060 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8061 Qualifiers Quals) {
8062 // C++2a [class.compare.default]p4:
8063 // The direct base class subobjects of C
8064 for (CXXBaseSpecifier &Base : Record->bases())
8065 if (Results.add(getDerived().visitSubobject(
8066 S.Context.getQualifiedType(T: Base.getType(), Qs: Quals),
8067 getDerived().getBase(&Base))))
8068 return true;
8069
8070 // followed by the non-static data members of C
8071 for (FieldDecl *Field : Record->fields()) {
8072 // C++23 [class.bit]p2:
8073 // Unnamed bit-fields are not members ...
8074 if (Field->isUnnamedBitField())
8075 continue;
8076 // Recursively expand anonymous structs.
8077 if (Field->isAnonymousStructOrUnion()) {
8078 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8079 Quals))
8080 return true;
8081 continue;
8082 }
8083
8084 // Figure out the type of an lvalue denoting this field.
8085 Qualifiers FieldQuals = Quals;
8086 if (Field->isMutable())
8087 FieldQuals.removeConst();
8088 QualType FieldType =
8089 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8090
8091 if (Results.add(getDerived().visitSubobject(
8092 FieldType, getDerived().getField(Field))))
8093 return true;
8094 }
8095
8096 // form a list of subobjects.
8097 return false;
8098 }
8099
8100 Result visitSubobject(QualType Type, Subobject Subobj) {
8101 // In that list, any subobject of array type is recursively expanded
8102 const ArrayType *AT = S.Context.getAsArrayType(T: Type);
8103 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(Val: AT))
8104 return getDerived().visitSubobjectArray(CAT->getElementType(),
8105 CAT->getSize(), Subobj);
8106 return getDerived().visitExpandedSubobject(Type, Subobj);
8107 }
8108
8109 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8110 Subobject Subobj) {
8111 return getDerived().visitSubobject(Type, Subobj);
8112 }
8113
8114protected:
8115 Sema &S;
8116 CXXRecordDecl *RD;
8117 FunctionDecl *FD;
8118 DefaultedComparisonKind DCK;
8119 UnresolvedSet<16> Fns;
8120};
8121
8122/// Information about a defaulted comparison, as determined by
8123/// DefaultedComparisonAnalyzer.
8124struct DefaultedComparisonInfo {
8125 bool Deleted = false;
8126 bool Constexpr = true;
8127 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8128
8129 static DefaultedComparisonInfo deleted() {
8130 DefaultedComparisonInfo Deleted;
8131 Deleted.Deleted = true;
8132 return Deleted;
8133 }
8134
8135 bool add(const DefaultedComparisonInfo &R) {
8136 Deleted |= R.Deleted;
8137 Constexpr &= R.Constexpr;
8138 Category = commonComparisonType(A: Category, B: R.Category);
8139 return Deleted;
8140 }
8141};
8142
8143/// An element in the expanded list of subobjects of a defaulted comparison, as
8144/// specified in C++2a [class.compare.default]p4.
8145struct DefaultedComparisonSubobject {
8146 enum { CompleteObject, Member, Base } Kind;
8147 NamedDecl *Decl;
8148 SourceLocation Loc;
8149};
8150
8151/// A visitor over the notional body of a defaulted comparison that determines
8152/// whether that body would be deleted or constexpr.
8153class DefaultedComparisonAnalyzer
8154 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8155 DefaultedComparisonInfo,
8156 DefaultedComparisonInfo,
8157 DefaultedComparisonSubobject> {
8158public:
8159 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8160
8161private:
8162 DiagnosticKind Diagnose;
8163
8164public:
8165 using Base = DefaultedComparisonVisitor;
8166 using Result = DefaultedComparisonInfo;
8167 using Subobject = DefaultedComparisonSubobject;
8168
8169 friend Base;
8170
8171 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8172 DefaultedComparisonKind DCK,
8173 DiagnosticKind Diagnose = NoDiagnostics)
8174 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8175
8176 Result visit() {
8177 if ((DCK == DefaultedComparisonKind::Equal ||
8178 DCK == DefaultedComparisonKind::ThreeWay) &&
8179 RD->hasVariantMembers()) {
8180 // C++2a [class.compare.default]p2 [P2002R0]:
8181 // A defaulted comparison operator function for class C is defined as
8182 // deleted if [...] C has variant members.
8183 if (Diagnose == ExplainDeleted) {
8184 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8185 << FD << RD->isUnion() << RD;
8186 }
8187 return Result::deleted();
8188 }
8189
8190 return Base::visit();
8191 }
8192
8193private:
8194 Subobject getCompleteObject() {
8195 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8196 }
8197
8198 Subobject getBase(CXXBaseSpecifier *Base) {
8199 return Subobject{.Kind: Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8200 .Loc: Base->getBaseTypeLoc()};
8201 }
8202
8203 Subobject getField(FieldDecl *Field) {
8204 return Subobject{Subobject::Member, Field, Field->getLocation()};
8205 }
8206
8207 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8208 // C++2a [class.compare.default]p2 [P2002R0]:
8209 // A defaulted <=> or == operator function for class C is defined as
8210 // deleted if any non-static data member of C is of reference type
8211 if (Type->isReferenceType()) {
8212 if (Diagnose == ExplainDeleted) {
8213 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8214 << FD << RD;
8215 }
8216 return Result::deleted();
8217 }
8218
8219 // [...] Let xi be an lvalue denoting the ith element [...]
8220 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8221 Expr *Args[] = {&Xi, &Xi};
8222
8223 // All operators start by trying to apply that same operator recursively.
8224 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8225 assert(OO != OO_None && "not an overloaded operator!");
8226 return visitBinaryOperator(OO, Args, Subobj);
8227 }
8228
8229 Result
8230 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8231 Subobject Subobj,
8232 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8233 // Note that there is no need to consider rewritten candidates here if
8234 // we've already found there is no viable 'operator<=>' candidate (and are
8235 // considering synthesizing a '<=>' from '==' and '<').
8236 OverloadCandidateSet CandidateSet(
8237 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8238 OverloadCandidateSet::OperatorRewriteInfo(
8239 OO, FD->getLocation(),
8240 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8241
8242 /// C++2a [class.compare.default]p1 [P2002R0]:
8243 /// [...] the defaulted function itself is never a candidate for overload
8244 /// resolution [...]
8245 CandidateSet.exclude(FD);
8246
8247 if (Args[0]->getType()->isOverloadableType())
8248 S.LookupOverloadedBinOp(CandidateSet, Op: OO, Fns, Args);
8249 else
8250 // FIXME: We determine whether this is a valid expression by checking to
8251 // see if there's a viable builtin operator candidate for it. That isn't
8252 // really what the rules ask us to do, but should give the right results.
8253 S.AddBuiltinOperatorCandidates(Op: OO, OpLoc: FD->getLocation(), Args, CandidateSet);
8254
8255 Result R;
8256
8257 OverloadCandidateSet::iterator Best;
8258 switch (CandidateSet.BestViableFunction(S, Loc: FD->getLocation(), Best)) {
8259 case OR_Success: {
8260 // C++2a [class.compare.secondary]p2 [P2002R0]:
8261 // The operator function [...] is defined as deleted if [...] the
8262 // candidate selected by overload resolution is not a rewritten
8263 // candidate.
8264 if ((DCK == DefaultedComparisonKind::NotEqual ||
8265 DCK == DefaultedComparisonKind::Relational) &&
8266 !Best->RewriteKind) {
8267 if (Diagnose == ExplainDeleted) {
8268 if (Best->Function) {
8269 S.Diag(Best->Function->getLocation(),
8270 diag::note_defaulted_comparison_not_rewritten_callee)
8271 << FD;
8272 } else {
8273 assert(Best->Conversions.size() == 2 &&
8274 Best->Conversions[0].isUserDefined() &&
8275 "non-user-defined conversion from class to built-in "
8276 "comparison");
8277 S.Diag(Best->Conversions[0]
8278 .UserDefined.FoundConversionFunction.getDecl()
8279 ->getLocation(),
8280 diag::note_defaulted_comparison_not_rewritten_conversion)
8281 << FD;
8282 }
8283 }
8284 return Result::deleted();
8285 }
8286
8287 // Throughout C++2a [class.compare]: if overload resolution does not
8288 // result in a usable function, the candidate function is defined as
8289 // deleted. This requires that we selected an accessible function.
8290 //
8291 // Note that this only considers the access of the function when named
8292 // within the type of the subobject, and not the access path for any
8293 // derived-to-base conversion.
8294 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8295 if (ArgClass && Best->FoundDecl.getDecl() &&
8296 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8297 QualType ObjectType = Subobj.Kind == Subobject::Member
8298 ? Args[0]->getType()
8299 : S.Context.getRecordType(RD);
8300 if (!S.isMemberAccessibleForDeletion(
8301 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8302 Diagnose == ExplainDeleted
8303 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8304 << FD << Subobj.Kind << Subobj.Decl
8305 : S.PDiag()))
8306 return Result::deleted();
8307 }
8308
8309 bool NeedsDeducing =
8310 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8311
8312 if (FunctionDecl *BestFD = Best->Function) {
8313 // C++2a [class.compare.default]p3 [P2002R0]:
8314 // A defaulted comparison function is constexpr-compatible if
8315 // [...] no overlod resolution performed [...] results in a
8316 // non-constexpr function.
8317 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8318 // If it's not constexpr, explain why not.
8319 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8320 if (Subobj.Kind != Subobject::CompleteObject)
8321 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8322 << Subobj.Kind << Subobj.Decl;
8323 S.Diag(BestFD->getLocation(),
8324 diag::note_defaulted_comparison_not_constexpr_here);
8325 // Bail out after explaining; we don't want any more notes.
8326 return Result::deleted();
8327 }
8328 R.Constexpr &= BestFD->isConstexpr();
8329
8330 if (NeedsDeducing) {
8331 // If any callee has an undeduced return type, deduce it now.
8332 // FIXME: It's not clear how a failure here should be handled. For
8333 // now, we produce an eager diagnostic, because that is forward
8334 // compatible with most (all?) other reasonable options.
8335 if (BestFD->getReturnType()->isUndeducedType() &&
8336 S.DeduceReturnType(FD: BestFD, Loc: FD->getLocation(),
8337 /*Diagnose=*/false)) {
8338 // Don't produce a duplicate error when asked to explain why the
8339 // comparison is deleted: we diagnosed that when initially checking
8340 // the defaulted operator.
8341 if (Diagnose == NoDiagnostics) {
8342 S.Diag(
8343 FD->getLocation(),
8344 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8345 << Subobj.Kind << Subobj.Decl;
8346 S.Diag(
8347 Subobj.Loc,
8348 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8349 << Subobj.Kind << Subobj.Decl;
8350 S.Diag(BestFD->getLocation(),
8351 diag::note_defaulted_comparison_cannot_deduce_callee)
8352 << Subobj.Kind << Subobj.Decl;
8353 }
8354 return Result::deleted();
8355 }
8356 auto *Info = S.Context.CompCategories.lookupInfoForType(
8357 Ty: BestFD->getCallResultType());
8358 if (!Info) {
8359 if (Diagnose == ExplainDeleted) {
8360 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8361 << Subobj.Kind << Subobj.Decl
8362 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8363 S.Diag(BestFD->getLocation(),
8364 diag::note_defaulted_comparison_cannot_deduce_callee)
8365 << Subobj.Kind << Subobj.Decl;
8366 }
8367 return Result::deleted();
8368 }
8369 R.Category = Info->Kind;
8370 }
8371 } else {
8372 QualType T = Best->BuiltinParamTypes[0];
8373 assert(T == Best->BuiltinParamTypes[1] &&
8374 "builtin comparison for different types?");
8375 assert(Best->BuiltinParamTypes[2].isNull() &&
8376 "invalid builtin comparison");
8377
8378 // FIXME: If the type we deduced is a vector type, we mark the
8379 // comparison as deleted because we don't yet support this.
8380 if (isa<VectorType>(Val: T)) {
8381 if (Diagnose == ExplainDeleted) {
8382 S.Diag(FD->getLocation(),
8383 diag::note_defaulted_comparison_vector_types)
8384 << FD;
8385 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8386 }
8387 return Result::deleted();
8388 }
8389
8390 if (NeedsDeducing) {
8391 std::optional<ComparisonCategoryType> Cat =
8392 getComparisonCategoryForBuiltinCmp(T);
8393 assert(Cat && "no category for builtin comparison?");
8394 R.Category = *Cat;
8395 }
8396 }
8397
8398 // Note that we might be rewriting to a different operator. That call is
8399 // not considered until we come to actually build the comparison function.
8400 break;
8401 }
8402
8403 case OR_Ambiguous:
8404 if (Diagnose == ExplainDeleted) {
8405 unsigned Kind = 0;
8406 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8407 Kind = OO == OO_EqualEqual ? 1 : 2;
8408 CandidateSet.NoteCandidates(
8409 PartialDiagnosticAt(
8410 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8411 << FD << Kind << Subobj.Kind << Subobj.Decl),
8412 S, OCD_AmbiguousCandidates, Args);
8413 }
8414 R = Result::deleted();
8415 break;
8416
8417 case OR_Deleted:
8418 if (Diagnose == ExplainDeleted) {
8419 if ((DCK == DefaultedComparisonKind::NotEqual ||
8420 DCK == DefaultedComparisonKind::Relational) &&
8421 !Best->RewriteKind) {
8422 S.Diag(Best->Function->getLocation(),
8423 diag::note_defaulted_comparison_not_rewritten_callee)
8424 << FD;
8425 } else {
8426 S.Diag(Subobj.Loc,
8427 diag::note_defaulted_comparison_calls_deleted)
8428 << FD << Subobj.Kind << Subobj.Decl;
8429 S.NoteDeletedFunction(FD: Best->Function);
8430 }
8431 }
8432 R = Result::deleted();
8433 break;
8434
8435 case OR_No_Viable_Function:
8436 // If there's no usable candidate, we're done unless we can rewrite a
8437 // '<=>' in terms of '==' and '<'.
8438 if (OO == OO_Spaceship &&
8439 S.Context.CompCategories.lookupInfoForType(Ty: FD->getReturnType())) {
8440 // For any kind of comparison category return type, we need a usable
8441 // '==' and a usable '<'.
8442 if (!R.add(R: visitBinaryOperator(OO: OO_EqualEqual, Args, Subobj,
8443 SpaceshipCandidates: &CandidateSet)))
8444 R.add(R: visitBinaryOperator(OO: OO_Less, Args, Subobj, SpaceshipCandidates: &CandidateSet));
8445 break;
8446 }
8447
8448 if (Diagnose == ExplainDeleted) {
8449 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8450 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8451 << Subobj.Kind << Subobj.Decl;
8452
8453 // For a three-way comparison, list both the candidates for the
8454 // original operator and the candidates for the synthesized operator.
8455 if (SpaceshipCandidates) {
8456 SpaceshipCandidates->NoteCandidates(
8457 S, Args,
8458 SpaceshipCandidates->CompleteCandidates(S, OCD: OCD_AllCandidates,
8459 Args, OpLoc: FD->getLocation()));
8460 S.Diag(Subobj.Loc,
8461 diag::note_defaulted_comparison_no_viable_function_synthesized)
8462 << (OO == OO_EqualEqual ? 0 : 1);
8463 }
8464
8465 CandidateSet.NoteCandidates(
8466 S, Args,
8467 CandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
8468 OpLoc: FD->getLocation()));
8469 }
8470 R = Result::deleted();
8471 break;
8472 }
8473
8474 return R;
8475 }
8476};
8477
8478/// A list of statements.
8479struct StmtListResult {
8480 bool IsInvalid = false;
8481 llvm::SmallVector<Stmt*, 16> Stmts;
8482
8483 bool add(const StmtResult &S) {
8484 IsInvalid |= S.isInvalid();
8485 if (IsInvalid)
8486 return true;
8487 Stmts.push_back(Elt: S.get());
8488 return false;
8489 }
8490};
8491
8492/// A visitor over the notional body of a defaulted comparison that synthesizes
8493/// the actual body.
8494class DefaultedComparisonSynthesizer
8495 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8496 StmtListResult, StmtResult,
8497 std::pair<ExprResult, ExprResult>> {
8498 SourceLocation Loc;
8499 unsigned ArrayDepth = 0;
8500
8501public:
8502 using Base = DefaultedComparisonVisitor;
8503 using ExprPair = std::pair<ExprResult, ExprResult>;
8504
8505 friend Base;
8506
8507 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8508 DefaultedComparisonKind DCK,
8509 SourceLocation BodyLoc)
8510 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8511
8512 /// Build a suitable function body for this defaulted comparison operator.
8513 StmtResult build() {
8514 Sema::CompoundScopeRAII CompoundScope(S);
8515
8516 StmtListResult Stmts = visit();
8517 if (Stmts.IsInvalid)
8518 return StmtError();
8519
8520 ExprResult RetVal;
8521 switch (DCK) {
8522 case DefaultedComparisonKind::None:
8523 llvm_unreachable("not a defaulted comparison");
8524
8525 case DefaultedComparisonKind::Equal: {
8526 // C++2a [class.eq]p3:
8527 // [...] compar[e] the corresponding elements [...] until the first
8528 // index i where xi == yi yields [...] false. If no such index exists,
8529 // V is true. Otherwise, V is false.
8530 //
8531 // Join the comparisons with '&&'s and return the result. Use a right
8532 // fold (traversing the conditions right-to-left), because that
8533 // short-circuits more naturally.
8534 auto OldStmts = std::move(Stmts.Stmts);
8535 Stmts.Stmts.clear();
8536 ExprResult CmpSoFar;
8537 // Finish a particular comparison chain.
8538 auto FinishCmp = [&] {
8539 if (Expr *Prior = CmpSoFar.get()) {
8540 // Convert the last expression to 'return ...;'
8541 if (RetVal.isUnset() && Stmts.Stmts.empty())
8542 RetVal = CmpSoFar;
8543 // Convert any prior comparison to 'if (!(...)) return false;'
8544 else if (Stmts.add(S: buildIfNotCondReturnFalse(Cond: Prior)))
8545 return true;
8546 CmpSoFar = ExprResult();
8547 }
8548 return false;
8549 };
8550 for (Stmt *EAsStmt : llvm::reverse(C&: OldStmts)) {
8551 Expr *E = dyn_cast<Expr>(Val: EAsStmt);
8552 if (!E) {
8553 // Found an array comparison.
8554 if (FinishCmp() || Stmts.add(S: EAsStmt))
8555 return StmtError();
8556 continue;
8557 }
8558
8559 if (CmpSoFar.isUnset()) {
8560 CmpSoFar = E;
8561 continue;
8562 }
8563 CmpSoFar = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_LAnd, LHSExpr: E, RHSExpr: CmpSoFar.get());
8564 if (CmpSoFar.isInvalid())
8565 return StmtError();
8566 }
8567 if (FinishCmp())
8568 return StmtError();
8569 std::reverse(first: Stmts.Stmts.begin(), last: Stmts.Stmts.end());
8570 // If no such index exists, V is true.
8571 if (RetVal.isUnset())
8572 RetVal = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_true);
8573 break;
8574 }
8575
8576 case DefaultedComparisonKind::ThreeWay: {
8577 // Per C++2a [class.spaceship]p3, as a fallback add:
8578 // return static_cast<R>(std::strong_ordering::equal);
8579 QualType StrongOrdering = S.CheckComparisonCategoryType(
8580 Kind: ComparisonCategoryType::StrongOrdering, Loc,
8581 Usage: Sema::ComparisonCategoryUsage::DefaultedOperator);
8582 if (StrongOrdering.isNull())
8583 return StmtError();
8584 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(Ty: StrongOrdering)
8585 .getValueInfo(ValueKind: ComparisonCategoryResult::Equal)
8586 ->VD;
8587 RetVal = getDecl(EqualVD);
8588 if (RetVal.isInvalid())
8589 return StmtError();
8590 RetVal = buildStaticCastToR(E: RetVal.get());
8591 break;
8592 }
8593
8594 case DefaultedComparisonKind::NotEqual:
8595 case DefaultedComparisonKind::Relational:
8596 RetVal = cast<Expr>(Val: Stmts.Stmts.pop_back_val());
8597 break;
8598 }
8599
8600 // Build the final return statement.
8601 if (RetVal.isInvalid())
8602 return StmtError();
8603 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: RetVal.get());
8604 if (ReturnStmt.isInvalid())
8605 return StmtError();
8606 Stmts.Stmts.push_back(Elt: ReturnStmt.get());
8607
8608 return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts.Stmts, /*IsStmtExpr=*/isStmtExpr: false);
8609 }
8610
8611private:
8612 ExprResult getDecl(ValueDecl *VD) {
8613 return S.BuildDeclarationNameExpr(
8614 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8615 }
8616
8617 ExprResult getParam(unsigned I) {
8618 ParmVarDecl *PD = FD->getParamDecl(i: I);
8619 return getDecl(PD);
8620 }
8621
8622 ExprPair getCompleteObject() {
8623 unsigned Param = 0;
8624 ExprResult LHS;
8625 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
8626 MD && MD->isImplicitObjectMemberFunction()) {
8627 // LHS is '*this'.
8628 LHS = S.ActOnCXXThis(Loc);
8629 if (!LHS.isInvalid())
8630 LHS = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: LHS.get());
8631 } else {
8632 LHS = getParam(I: Param++);
8633 }
8634 ExprResult RHS = getParam(I: Param++);
8635 assert(Param == FD->getNumParams());
8636 return {LHS, RHS};
8637 }
8638
8639 ExprPair getBase(CXXBaseSpecifier *Base) {
8640 ExprPair Obj = getCompleteObject();
8641 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8642 return {ExprError(), ExprError()};
8643 CXXCastPath Path = {Base};
8644 const auto CastToBase = [&](Expr *E) {
8645 QualType ToType = S.Context.getQualifiedType(
8646 T: Base->getType(), Qs: E->getType().getQualifiers());
8647 return S.ImpCastExprToType(E, Type: ToType, CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path);
8648 };
8649 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8650 }
8651
8652 ExprPair getField(FieldDecl *Field) {
8653 ExprPair Obj = getCompleteObject();
8654 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8655 return {ExprError(), ExprError()};
8656
8657 DeclAccessPair Found = DeclAccessPair::make(D: Field, AS: Field->getAccess());
8658 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8659 return {S.BuildFieldReferenceExpr(BaseExpr: Obj.first.get(), /*IsArrow=*/false, OpLoc: Loc,
8660 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo),
8661 S.BuildFieldReferenceExpr(BaseExpr: Obj.second.get(), /*IsArrow=*/false, OpLoc: Loc,
8662 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo)};
8663 }
8664
8665 // FIXME: When expanding a subobject, register a note in the code synthesis
8666 // stack to say which subobject we're comparing.
8667
8668 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8669 if (Cond.isInvalid())
8670 return StmtError();
8671
8672 ExprResult NotCond = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_LNot, InputExpr: Cond.get());
8673 if (NotCond.isInvalid())
8674 return StmtError();
8675
8676 ExprResult False = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_false);
8677 assert(!False.isInvalid() && "should never fail");
8678 StmtResult ReturnFalse = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: False.get());
8679 if (ReturnFalse.isInvalid())
8680 return StmtError();
8681
8682 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt: nullptr,
8683 Cond: S.ActOnCondition(S: nullptr, Loc, SubExpr: NotCond.get(),
8684 CK: Sema::ConditionKind::Boolean),
8685 RParenLoc: Loc, ThenVal: ReturnFalse.get(), ElseLoc: SourceLocation(), ElseVal: nullptr);
8686 }
8687
8688 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8689 ExprPair Subobj) {
8690 QualType SizeType = S.Context.getSizeType();
8691 Size = Size.zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
8692
8693 // Build 'size_t i$n = 0'.
8694 IdentifierInfo *IterationVarName = nullptr;
8695 {
8696 SmallString<8> Str;
8697 llvm::raw_svector_ostream OS(Str);
8698 OS << "i" << ArrayDepth;
8699 IterationVarName = &S.Context.Idents.get(Name: OS.str());
8700 }
8701 VarDecl *IterationVar = VarDecl::Create(
8702 C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: IterationVarName, T: SizeType,
8703 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), S: SC_None);
8704 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
8705 IterationVar->setInit(
8706 IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
8707 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8708
8709 auto IterRef = [&] {
8710 ExprResult Ref = S.BuildDeclarationNameExpr(
8711 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8712 IterationVar);
8713 assert(!Ref.isInvalid() && "can't reference our own variable?");
8714 return Ref.get();
8715 };
8716
8717 // Build 'i$n != Size'.
8718 ExprResult Cond = S.CreateBuiltinBinOp(
8719 OpLoc: Loc, Opc: BO_NE, LHSExpr: IterRef(),
8720 RHSExpr: IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc));
8721 assert(!Cond.isInvalid() && "should never fail");
8722
8723 // Build '++i$n'.
8724 ExprResult Inc = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_PreInc, InputExpr: IterRef());
8725 assert(!Inc.isInvalid() && "should never fail");
8726
8727 // Build 'a[i$n]' and 'b[i$n]'.
8728 auto Index = [&](ExprResult E) {
8729 if (E.isInvalid())
8730 return ExprError();
8731 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8732 };
8733 Subobj.first = Index(Subobj.first);
8734 Subobj.second = Index(Subobj.second);
8735
8736 // Compare the array elements.
8737 ++ArrayDepth;
8738 StmtResult Substmt = visitSubobject(Type, Subobj);
8739 --ArrayDepth;
8740
8741 if (Substmt.isInvalid())
8742 return StmtError();
8743
8744 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8745 // For outer levels or for an 'operator<=>' we already have a suitable
8746 // statement that returns as necessary.
8747 if (Expr *ElemCmp = dyn_cast<Expr>(Val: Substmt.get())) {
8748 assert(DCK == DefaultedComparisonKind::Equal &&
8749 "should have non-expression statement");
8750 Substmt = buildIfNotCondReturnFalse(Cond: ElemCmp);
8751 if (Substmt.isInvalid())
8752 return StmtError();
8753 }
8754
8755 // Build 'for (...) ...'
8756 return S.ActOnForStmt(ForLoc: Loc, LParenLoc: Loc, First: Init,
8757 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Cond.get(),
8758 CK: Sema::ConditionKind::Boolean),
8759 Third: S.MakeFullDiscardedValueExpr(Arg: Inc.get()), RParenLoc: Loc,
8760 Body: Substmt.get());
8761 }
8762
8763 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8764 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8765 return StmtError();
8766
8767 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8768 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8769 ExprResult Op;
8770 if (Type->isOverloadableType())
8771 Op = S.CreateOverloadedBinOp(OpLoc: Loc, Opc, Fns, LHS: Obj.first.get(),
8772 RHS: Obj.second.get(), /*PerformADL=*/RequiresADL: true,
8773 /*AllowRewrittenCandidates=*/true, DefaultedFn: FD);
8774 else
8775 Op = S.CreateBuiltinBinOp(OpLoc: Loc, Opc, LHSExpr: Obj.first.get(), RHSExpr: Obj.second.get());
8776 if (Op.isInvalid())
8777 return StmtError();
8778
8779 switch (DCK) {
8780 case DefaultedComparisonKind::None:
8781 llvm_unreachable("not a defaulted comparison");
8782
8783 case DefaultedComparisonKind::Equal:
8784 // Per C++2a [class.eq]p2, each comparison is individually contextually
8785 // converted to bool.
8786 Op = S.PerformContextuallyConvertToBool(From: Op.get());
8787 if (Op.isInvalid())
8788 return StmtError();
8789 return Op.get();
8790
8791 case DefaultedComparisonKind::ThreeWay: {
8792 // Per C++2a [class.spaceship]p3, form:
8793 // if (R cmp = static_cast<R>(op); cmp != 0)
8794 // return cmp;
8795 QualType R = FD->getReturnType();
8796 Op = buildStaticCastToR(E: Op.get());
8797 if (Op.isInvalid())
8798 return StmtError();
8799
8800 // R cmp = ...;
8801 IdentifierInfo *Name = &S.Context.Idents.get(Name: "cmp");
8802 VarDecl *VD =
8803 VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: Name, T: R,
8804 TInfo: S.Context.getTrivialTypeSourceInfo(T: R, Loc), S: SC_None);
8805 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8806 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8807
8808 // cmp != 0
8809 ExprResult VDRef = getDecl(VD);
8810 if (VDRef.isInvalid())
8811 return StmtError();
8812 llvm::APInt ZeroVal(S.Context.getIntWidth(T: S.Context.IntTy), 0);
8813 Expr *Zero =
8814 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8815 ExprResult Comp;
8816 if (VDRef.get()->getType()->isOverloadableType())
8817 Comp = S.CreateOverloadedBinOp(OpLoc: Loc, Opc: BO_NE, Fns, LHS: VDRef.get(), RHS: Zero, RequiresADL: true,
8818 AllowRewrittenCandidates: true, DefaultedFn: FD);
8819 else
8820 Comp = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_NE, LHSExpr: VDRef.get(), RHSExpr: Zero);
8821 if (Comp.isInvalid())
8822 return StmtError();
8823 Sema::ConditionResult Cond = S.ActOnCondition(
8824 S: nullptr, Loc, SubExpr: Comp.get(), CK: Sema::ConditionKind::Boolean);
8825 if (Cond.isInvalid())
8826 return StmtError();
8827
8828 // return cmp;
8829 VDRef = getDecl(VD);
8830 if (VDRef.isInvalid())
8831 return StmtError();
8832 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: VDRef.get());
8833 if (ReturnStmt.isInvalid())
8834 return StmtError();
8835
8836 // if (...)
8837 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt, Cond,
8838 RParenLoc: Loc, ThenVal: ReturnStmt.get(),
8839 /*ElseLoc=*/SourceLocation(), /*Else=*/ElseVal: nullptr);
8840 }
8841
8842 case DefaultedComparisonKind::NotEqual:
8843 case DefaultedComparisonKind::Relational:
8844 // C++2a [class.compare.secondary]p2:
8845 // Otherwise, the operator function yields x @ y.
8846 return Op.get();
8847 }
8848 llvm_unreachable("");
8849 }
8850
8851 /// Build "static_cast<R>(E)".
8852 ExprResult buildStaticCastToR(Expr *E) {
8853 QualType R = FD->getReturnType();
8854 assert(!R->isUndeducedType() && "type should have been deduced already");
8855
8856 // Don't bother forming a no-op cast in the common case.
8857 if (E->isPRValue() && S.Context.hasSameType(T1: E->getType(), T2: R))
8858 return E;
8859 return S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast,
8860 Ty: S.Context.getTrivialTypeSourceInfo(T: R, Loc), E,
8861 AngleBrackets: SourceRange(Loc, Loc), Parens: SourceRange(Loc, Loc));
8862 }
8863};
8864}
8865
8866/// Perform the unqualified lookups that might be needed to form a defaulted
8867/// comparison function for the given operator.
8868static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8869 UnresolvedSetImpl &Operators,
8870 OverloadedOperatorKind Op) {
8871 auto Lookup = [&](OverloadedOperatorKind OO) {
8872 Self.LookupOverloadedOperatorName(Op: OO, S, Functions&: Operators);
8873 };
8874
8875 // Every defaulted operator looks up itself.
8876 Lookup(Op);
8877 // ... and the rewritten form of itself, if any.
8878 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: Op))
8879 Lookup(ExtraOp);
8880
8881 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8882 // synthesize a three-way comparison from '<' and '=='. In a dependent
8883 // context, we also need to look up '==' in case we implicitly declare a
8884 // defaulted 'operator=='.
8885 if (Op == OO_Spaceship) {
8886 Lookup(OO_ExclaimEqual);
8887 Lookup(OO_Less);
8888 Lookup(OO_EqualEqual);
8889 }
8890}
8891
8892bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8893 DefaultedComparisonKind DCK) {
8894 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8895
8896 // Perform any unqualified lookups we're going to need to default this
8897 // function.
8898 if (S) {
8899 UnresolvedSet<32> Operators;
8900 lookupOperatorsForDefaultedComparison(Self&: *this, S, Operators,
8901 Op: FD->getOverloadedOperator());
8902 FD->setDefaultedOrDeletedInfo(
8903 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
8904 Context, Lookups: Operators.pairs()));
8905 }
8906
8907 // C++2a [class.compare.default]p1:
8908 // A defaulted comparison operator function for some class C shall be a
8909 // non-template function declared in the member-specification of C that is
8910 // -- a non-static const non-volatile member of C having one parameter of
8911 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8912 // -- a friend of C having two parameters of type const C& or two
8913 // parameters of type C.
8914
8915 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8916 bool IsMethod = isa<CXXMethodDecl>(Val: FD);
8917 if (IsMethod) {
8918 auto *MD = cast<CXXMethodDecl>(Val: FD);
8919 assert(!MD->isStatic() && "comparison function cannot be a static member");
8920
8921 if (MD->getRefQualifier() == RQ_RValue) {
8922 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8923
8924 // Remove the ref qualifier to recover.
8925 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8926 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8927 EPI.RefQualifier = RQ_None;
8928 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
8929 Args: FPT->getParamTypes(), EPI));
8930 }
8931
8932 // If we're out-of-class, this is the class we're comparing.
8933 if (!RD)
8934 RD = MD->getParent();
8935 QualType T = MD->getFunctionObjectParameterReferenceType();
8936 if (!T.getNonReferenceType().isConstQualified() &&
8937 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
8938 SourceLocation Loc, InsertLoc;
8939 if (MD->isExplicitObjectMemberFunction()) {
8940 Loc = MD->getParamDecl(0)->getBeginLoc();
8941 InsertLoc = getLocForEndOfToken(
8942 Loc: MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
8943 } else {
8944 Loc = MD->getLocation();
8945 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8946 InsertLoc = Loc.getRParenLoc();
8947 }
8948 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8949 // corresponding defaulted 'operator<=>' already.
8950 if (!MD->isImplicit()) {
8951 Diag(Loc, diag::err_defaulted_comparison_non_const)
8952 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8953 }
8954
8955 // Add the 'const' to the type to recover.
8956 if (MD->isExplicitObjectMemberFunction()) {
8957 assert(T->isLValueReferenceType());
8958 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
8959 T: T.getNonReferenceType().withConst()));
8960 } else {
8961 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8962 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8963 EPI.TypeQuals.addConst();
8964 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
8965 Args: FPT->getParamTypes(), EPI));
8966 }
8967 }
8968
8969 if (MD->isVolatile()) {
8970 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8971
8972 // Remove the 'volatile' from the type to recover.
8973 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8974 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8975 EPI.TypeQuals.removeVolatile();
8976 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
8977 Args: FPT->getParamTypes(), EPI));
8978 }
8979 }
8980
8981 if ((FD->getNumParams() -
8982 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8983 (IsMethod ? 1 : 2)) {
8984 // Let's not worry about using a variadic template pack here -- who would do
8985 // such a thing?
8986 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8987 << int(IsMethod) << int(DCK);
8988 return true;
8989 }
8990
8991 const ParmVarDecl *KnownParm = nullptr;
8992 for (const ParmVarDecl *Param : FD->parameters()) {
8993 QualType ParmTy = Param->getType();
8994 if (!KnownParm) {
8995 auto CTy = ParmTy;
8996 // Is it `T const &`?
8997 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
8998 QualType ExpectedTy;
8999 if (RD)
9000 ExpectedTy = Context.getRecordType(RD);
9001 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9002 CTy = Ref->getPointeeType();
9003 if (RD)
9004 ExpectedTy.addConst();
9005 Ok = true;
9006 }
9007
9008 // Is T a class?
9009 if (RD) {
9010 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
9011 } else {
9012 RD = CTy->getAsCXXRecordDecl();
9013 Ok &= RD != nullptr;
9014 }
9015
9016 if (Ok) {
9017 KnownParm = Param;
9018 } else {
9019 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9020 // corresponding defaulted 'operator<=>' already.
9021 if (!FD->isImplicit()) {
9022 if (RD) {
9023 QualType PlainTy = Context.getRecordType(RD);
9024 QualType RefTy =
9025 Context.getLValueReferenceType(T: PlainTy.withConst());
9026 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9027 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9028 << Param->getSourceRange();
9029 } else {
9030 assert(!IsMethod && "should know expected type for method");
9031 Diag(FD->getLocation(),
9032 diag::err_defaulted_comparison_param_unknown)
9033 << int(DCK) << ParmTy << Param->getSourceRange();
9034 }
9035 }
9036 return true;
9037 }
9038 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9039 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9040 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9041 << ParmTy << Param->getSourceRange();
9042 return true;
9043 }
9044 }
9045
9046 assert(RD && "must have determined class");
9047 if (IsMethod) {
9048 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9049 // In-class, must be a friend decl.
9050 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9051 } else {
9052 // Out of class, require the defaulted comparison to be a friend (of a
9053 // complete type, per CWG2547).
9054 if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
9055 diag::err_defaulted_comparison_not_friend, int(DCK),
9056 int(1)))
9057 return true;
9058
9059 if (llvm::none_of(Range: RD->friends(), P: [&](const FriendDecl *F) {
9060 return declaresSameEntity(F->getFriendDecl(), FD);
9061 })) {
9062 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9063 << int(DCK) << int(0) << RD;
9064 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9065 return true;
9066 }
9067 }
9068
9069 // C++2a [class.eq]p1, [class.rel]p1:
9070 // A [defaulted comparison other than <=>] shall have a declared return
9071 // type bool.
9072 if (DCK != DefaultedComparisonKind::ThreeWay &&
9073 !FD->getDeclaredReturnType()->isDependentType() &&
9074 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9075 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9076 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9077 << FD->getReturnTypeSourceRange();
9078 return true;
9079 }
9080 // C++2a [class.spaceship]p2 [P2002R0]:
9081 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9082 // R shall not contain a placeholder type.
9083 if (QualType RT = FD->getDeclaredReturnType();
9084 DCK == DefaultedComparisonKind::ThreeWay &&
9085 RT->getContainedDeducedType() &&
9086 (!Context.hasSameType(T1: RT, T2: Context.getAutoDeductType()) ||
9087 RT->getContainedAutoType()->isConstrained())) {
9088 Diag(FD->getLocation(),
9089 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9090 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9091 << FD->getReturnTypeSourceRange();
9092 return true;
9093 }
9094
9095 // For a defaulted function in a dependent class, defer all remaining checks
9096 // until instantiation.
9097 if (RD->isDependentType())
9098 return false;
9099
9100 // Determine whether the function should be defined as deleted.
9101 DefaultedComparisonInfo Info =
9102 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9103
9104 bool First = FD == FD->getCanonicalDecl();
9105
9106 if (!First) {
9107 if (Info.Deleted) {
9108 // C++11 [dcl.fct.def.default]p4:
9109 // [For a] user-provided explicitly-defaulted function [...] if such a
9110 // function is implicitly defined as deleted, the program is ill-formed.
9111 //
9112 // This is really just a consequence of the general rule that you can
9113 // only delete a function on its first declaration.
9114 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9115 << FD->isImplicit() << (int)DCK;
9116 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9117 DefaultedComparisonAnalyzer::ExplainDeleted)
9118 .visit();
9119 return true;
9120 }
9121 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9122 // C++20 [class.compare.default]p1:
9123 // [...] A definition of a comparison operator as defaulted that appears
9124 // in a class shall be the first declaration of that function.
9125 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9126 << (int)DCK;
9127 Diag(FD->getCanonicalDecl()->getLocation(),
9128 diag::note_previous_declaration);
9129 return true;
9130 }
9131 }
9132
9133 // If we want to delete the function, then do so; there's nothing else to
9134 // check in that case.
9135 if (Info.Deleted) {
9136 SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation());
9137 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9138 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9139 << (int)DCK;
9140 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9141 DefaultedComparisonAnalyzer::ExplainDeleted)
9142 .visit();
9143 if (FD->getDefaultLoc().isValid())
9144 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9145 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9146 }
9147 return false;
9148 }
9149
9150 // C++2a [class.spaceship]p2:
9151 // The return type is deduced as the common comparison type of R0, R1, ...
9152 if (DCK == DefaultedComparisonKind::ThreeWay &&
9153 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9154 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9155 if (RetLoc.isInvalid())
9156 RetLoc = FD->getBeginLoc();
9157 // FIXME: Should we really care whether we have the complete type and the
9158 // 'enumerator' constants here? A forward declaration seems sufficient.
9159 QualType Cat = CheckComparisonCategoryType(
9160 Kind: Info.Category, Loc: RetLoc, Usage: ComparisonCategoryUsage::DefaultedOperator);
9161 if (Cat.isNull())
9162 return true;
9163 Context.adjustDeducedFunctionResultType(
9164 FD, ResultType: SubstAutoType(TypeWithAuto: FD->getDeclaredReturnType(), Replacement: Cat));
9165 }
9166
9167 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9168 // An explicitly-defaulted function that is not defined as deleted may be
9169 // declared constexpr or consteval only if it is constexpr-compatible.
9170 // C++2a [class.compare.default]p3 [P2002R0]:
9171 // A defaulted comparison function is constexpr-compatible if it satisfies
9172 // the requirements for a constexpr function [...]
9173 // The only relevant requirements are that the parameter and return types are
9174 // literal types. The remaining conditions are checked by the analyzer.
9175 //
9176 // We support P2448R2 in language modes earlier than C++23 as an extension.
9177 // The concept of constexpr-compatible was removed.
9178 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9179 // A function explicitly defaulted on its first declaration is implicitly
9180 // inline, and is implicitly constexpr if it is constexpr-suitable.
9181 // C++23 [dcl.constexpr]p3
9182 // A function is constexpr-suitable if
9183 // - it is not a coroutine, and
9184 // - if the function is a constructor or destructor, its class does not
9185 // have any virtual base classes.
9186 if (FD->isConstexpr()) {
9187 if (!getLangOpts().CPlusPlus23 &&
9188 CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9189 CheckConstexprParameterTypes(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9190 !Info.Constexpr) {
9191 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9192 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9193 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9194 DefaultedComparisonAnalyzer::ExplainConstexpr)
9195 .visit();
9196 }
9197 }
9198
9199 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9200 // If a constexpr-compatible function is explicitly defaulted on its first
9201 // declaration, it is implicitly considered to be constexpr.
9202 // FIXME: Only applying this to the first declaration seems problematic, as
9203 // simple reorderings can affect the meaning of the program.
9204 if (First && !FD->isConstexpr() && Info.Constexpr)
9205 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9206
9207 // C++2a [except.spec]p3:
9208 // If a declaration of a function does not have a noexcept-specifier
9209 // [and] is defaulted on its first declaration, [...] the exception
9210 // specification is as specified below
9211 if (FD->getExceptionSpecType() == EST_None) {
9212 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9213 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9214 EPI.ExceptionSpec.Type = EST_Unevaluated;
9215 EPI.ExceptionSpec.SourceDecl = FD;
9216 FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9217 Args: FPT->getParamTypes(), EPI));
9218 }
9219
9220 return false;
9221}
9222
9223void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9224 FunctionDecl *Spaceship) {
9225 Sema::CodeSynthesisContext Ctx;
9226 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9227 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9228 Ctx.Entity = Spaceship;
9229 pushCodeSynthesisContext(Ctx);
9230
9231 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9232 EqualEqual->setImplicit();
9233
9234 popCodeSynthesisContext();
9235}
9236
9237void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9238 DefaultedComparisonKind DCK) {
9239 assert(FD->isDefaulted() && !FD->isDeleted() &&
9240 !FD->doesThisDeclarationHaveABody());
9241 if (FD->willHaveBody() || FD->isInvalidDecl())
9242 return;
9243
9244 SynthesizedFunctionScope Scope(*this, FD);
9245
9246 // Add a context note for diagnostics produced after this point.
9247 Scope.addContextNote(UseLoc);
9248
9249 {
9250 // Build and set up the function body.
9251 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9252 // the type of the class being compared.
9253 auto PT = FD->getParamDecl(i: 0)->getType();
9254 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9255 SourceLocation BodyLoc =
9256 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9257 StmtResult Body =
9258 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9259 if (Body.isInvalid()) {
9260 FD->setInvalidDecl();
9261 return;
9262 }
9263 FD->setBody(Body.get());
9264 FD->markUsed(Context);
9265 }
9266
9267 // The exception specification is needed because we are defining the
9268 // function. Note that this will reuse the body we just built.
9269 ResolveExceptionSpec(Loc: UseLoc, FPT: FD->getType()->castAs<FunctionProtoType>());
9270
9271 if (ASTMutationListener *L = getASTMutationListener())
9272 L->CompletedImplicitDefinition(D: FD);
9273}
9274
9275static Sema::ImplicitExceptionSpecification
9276ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9277 FunctionDecl *FD,
9278 Sema::DefaultedComparisonKind DCK) {
9279 ComputingExceptionSpec CES(S, FD, Loc);
9280 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9281
9282 if (FD->isInvalidDecl())
9283 return ExceptSpec;
9284
9285 // The common case is that we just defined the comparison function. In that
9286 // case, just look at whether the body can throw.
9287 if (FD->hasBody()) {
9288 ExceptSpec.CalledStmt(S: FD->getBody());
9289 } else {
9290 // Otherwise, build a body so we can check it. This should ideally only
9291 // happen when we're not actually marking the function referenced. (This is
9292 // only really important for efficiency: we don't want to build and throw
9293 // away bodies for comparison functions more than we strictly need to.)
9294
9295 // Pretend to synthesize the function body in an unevaluated context.
9296 // Note that we can't actually just go ahead and define the function here:
9297 // we are not permitted to mark its callees as referenced.
9298 Sema::SynthesizedFunctionScope Scope(S, FD);
9299 EnterExpressionEvaluationContext Context(
9300 S, Sema::ExpressionEvaluationContext::Unevaluated);
9301
9302 CXXRecordDecl *RD =
9303 cast<CXXRecordDecl>(FD->getFriendObjectKind() == Decl::FOK_None
9304 ? FD->getDeclContext()
9305 : FD->getLexicalDeclContext());
9306 SourceLocation BodyLoc =
9307 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9308 StmtResult Body =
9309 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9310 if (!Body.isInvalid())
9311 ExceptSpec.CalledStmt(S: Body.get());
9312
9313 // FIXME: Can we hold onto this body and just transform it to potentially
9314 // evaluated when we're asked to define the function rather than rebuilding
9315 // it? Either that, or we should only build the bits of the body that we
9316 // need (the expressions, not the statements).
9317 }
9318
9319 return ExceptSpec;
9320}
9321
9322void Sema::CheckDelayedMemberExceptionSpecs() {
9323 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9324 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9325
9326 std::swap(LHS&: Overriding, RHS&: DelayedOverridingExceptionSpecChecks);
9327 std::swap(LHS&: Equivalent, RHS&: DelayedEquivalentExceptionSpecChecks);
9328
9329 // Perform any deferred checking of exception specifications for virtual
9330 // destructors.
9331 for (auto &Check : Overriding)
9332 CheckOverridingFunctionExceptionSpec(New: Check.first, Old: Check.second);
9333
9334 // Perform any deferred checking of exception specifications for befriended
9335 // special members.
9336 for (auto &Check : Equivalent)
9337 CheckEquivalentExceptionSpec(Old: Check.second, New: Check.first);
9338}
9339
9340namespace {
9341/// CRTP base class for visiting operations performed by a special member
9342/// function (or inherited constructor).
9343template<typename Derived>
9344struct SpecialMemberVisitor {
9345 Sema &S;
9346 CXXMethodDecl *MD;
9347 CXXSpecialMemberKind CSM;
9348 Sema::InheritedConstructorInfo *ICI;
9349
9350 // Properties of the special member, computed for convenience.
9351 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9352
9353 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9354 Sema::InheritedConstructorInfo *ICI)
9355 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9356 switch (CSM) {
9357 case CXXSpecialMemberKind::DefaultConstructor:
9358 case CXXSpecialMemberKind::CopyConstructor:
9359 case CXXSpecialMemberKind::MoveConstructor:
9360 IsConstructor = true;
9361 break;
9362 case CXXSpecialMemberKind::CopyAssignment:
9363 case CXXSpecialMemberKind::MoveAssignment:
9364 IsAssignment = true;
9365 break;
9366 case CXXSpecialMemberKind::Destructor:
9367 break;
9368 case CXXSpecialMemberKind::Invalid:
9369 llvm_unreachable("invalid special member kind");
9370 }
9371
9372 if (MD->getNumExplicitParams()) {
9373 if (const ReferenceType *RT =
9374 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9375 ConstArg = RT->getPointeeType().isConstQualified();
9376 }
9377 }
9378
9379 Derived &getDerived() { return static_cast<Derived&>(*this); }
9380
9381 /// Is this a "move" special member?
9382 bool isMove() const {
9383 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9384 CSM == CXXSpecialMemberKind::MoveAssignment;
9385 }
9386
9387 /// Look up the corresponding special member in the given class.
9388 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9389 unsigned Quals, bool IsMutable) {
9390 return lookupCallFromSpecialMember(S, Class, CSM, FieldQuals: Quals,
9391 ConstRHS: ConstArg && !IsMutable);
9392 }
9393
9394 /// Look up the constructor for the specified base class to see if it's
9395 /// overridden due to this being an inherited constructor.
9396 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9397 if (!ICI)
9398 return {};
9399 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9400 auto *BaseCtor =
9401 cast<CXXConstructorDecl>(Val: MD)->getInheritedConstructor().getConstructor();
9402 if (auto *MD = ICI->findConstructorForBase(Base: Class, Ctor: BaseCtor).first)
9403 return MD;
9404 return {};
9405 }
9406
9407 /// A base or member subobject.
9408 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9409
9410 /// Get the location to use for a subobject in diagnostics.
9411 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9412 // FIXME: For an indirect virtual base, the direct base leading to
9413 // the indirect virtual base would be a more useful choice.
9414 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Val&: Subobj))
9415 return B->getBaseTypeLoc();
9416 else
9417 return cast<FieldDecl *>(Val&: Subobj)->getLocation();
9418 }
9419
9420 enum BasesToVisit {
9421 /// Visit all non-virtual (direct) bases.
9422 VisitNonVirtualBases,
9423 /// Visit all direct bases, virtual or not.
9424 VisitDirectBases,
9425 /// Visit all non-virtual bases, and all virtual bases if the class
9426 /// is not abstract.
9427 VisitPotentiallyConstructedBases,
9428 /// Visit all direct or virtual bases.
9429 VisitAllBases
9430 };
9431
9432 // Visit the bases and members of the class.
9433 bool visit(BasesToVisit Bases) {
9434 CXXRecordDecl *RD = MD->getParent();
9435
9436 if (Bases == VisitPotentiallyConstructedBases)
9437 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9438
9439 for (auto &B : RD->bases())
9440 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9441 getDerived().visitBase(&B))
9442 return true;
9443
9444 if (Bases == VisitAllBases)
9445 for (auto &B : RD->vbases())
9446 if (getDerived().visitBase(&B))
9447 return true;
9448
9449 for (auto *F : RD->fields())
9450 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9451 getDerived().visitField(F))
9452 return true;
9453
9454 return false;
9455 }
9456};
9457}
9458
9459namespace {
9460struct SpecialMemberDeletionInfo
9461 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9462 bool Diagnose;
9463
9464 SourceLocation Loc;
9465
9466 bool AllFieldsAreConst;
9467
9468 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9469 CXXSpecialMemberKind CSM,
9470 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9471 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9472 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9473
9474 bool inUnion() const { return MD->getParent()->isUnion(); }
9475
9476 CXXSpecialMemberKind getEffectiveCSM() {
9477 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9478 }
9479
9480 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9481
9482 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9483
9484 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9485 bool visitField(FieldDecl *Field) { return shouldDeleteForField(FD: Field); }
9486
9487 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9488 bool shouldDeleteForField(FieldDecl *FD);
9489 bool shouldDeleteForAllConstMembers();
9490
9491 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9492 unsigned Quals);
9493 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9494 Sema::SpecialMemberOverloadResult SMOR,
9495 bool IsDtorCallInCtor);
9496
9497 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9498};
9499}
9500
9501/// Is the given special member inaccessible when used on the given
9502/// sub-object.
9503bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9504 CXXMethodDecl *target) {
9505 /// If we're operating on a base class, the object type is the
9506 /// type of this special member.
9507 QualType objectTy;
9508 AccessSpecifier access = target->getAccess();
9509 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9510 objectTy = S.Context.getTypeDeclType(MD->getParent());
9511 access = CXXRecordDecl::MergeAccess(PathAccess: base->getAccessSpecifier(), DeclAccess: access);
9512
9513 // If we're operating on a field, the object type is the type of the field.
9514 } else {
9515 objectTy = S.Context.getTypeDeclType(target->getParent());
9516 }
9517
9518 return S.isMemberAccessibleForDeletion(
9519 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9520}
9521
9522/// Check whether we should delete a special member due to the implicit
9523/// definition containing a call to a special member of a subobject.
9524bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9525 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9526 bool IsDtorCallInCtor) {
9527 CXXMethodDecl *Decl = SMOR.getMethod();
9528 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9529
9530 int DiagKind = -1;
9531
9532 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9533 DiagKind = !Decl ? 0 : 1;
9534 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9535 DiagKind = 2;
9536 else if (!isAccessible(Subobj, target: Decl))
9537 DiagKind = 3;
9538 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9539 !Decl->isTrivial()) {
9540 // A member of a union must have a trivial corresponding special member.
9541 // As a weird special case, a destructor call from a union's constructor
9542 // must be accessible and non-deleted, but need not be trivial. Such a
9543 // destructor is never actually called, but is semantically checked as
9544 // if it were.
9545 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9546 // [class.default.ctor]p2:
9547 // A defaulted default constructor for class X is defined as deleted if
9548 // - X is a union that has a variant member with a non-trivial default
9549 // constructor and no variant member of X has a default member
9550 // initializer
9551 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9552 if (!RD->hasInClassInitializer())
9553 DiagKind = 4;
9554 } else {
9555 DiagKind = 4;
9556 }
9557 }
9558
9559 if (DiagKind == -1)
9560 return false;
9561
9562 if (Diagnose) {
9563 if (Field) {
9564 S.Diag(Field->getLocation(),
9565 diag::note_deleted_special_member_class_subobject)
9566 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9567 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9568 } else {
9569 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Val&: Subobj);
9570 S.Diag(Base->getBeginLoc(),
9571 diag::note_deleted_special_member_class_subobject)
9572 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9573 << Base->getType() << DiagKind << IsDtorCallInCtor
9574 << /*IsObjCPtr*/ false;
9575 }
9576
9577 if (DiagKind == 1)
9578 S.NoteDeletedFunction(Decl);
9579 // FIXME: Explain inaccessibility if DiagKind == 3.
9580 }
9581
9582 return true;
9583}
9584
9585/// Check whether we should delete a special member function due to having a
9586/// direct or virtual base class or non-static data member of class type M.
9587bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9588 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9589 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9590 bool IsMutable = Field && Field->isMutable();
9591
9592 // C++11 [class.ctor]p5:
9593 // -- any direct or virtual base class, or non-static data member with no
9594 // brace-or-equal-initializer, has class type M (or array thereof) and
9595 // either M has no default constructor or overload resolution as applied
9596 // to M's default constructor results in an ambiguity or in a function
9597 // that is deleted or inaccessible
9598 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9599 // -- a direct or virtual base class B that cannot be copied/moved because
9600 // overload resolution, as applied to B's corresponding special member,
9601 // results in an ambiguity or a function that is deleted or inaccessible
9602 // from the defaulted special member
9603 // C++11 [class.dtor]p5:
9604 // -- any direct or virtual base class [...] has a type with a destructor
9605 // that is deleted or inaccessible
9606 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9607 Field->hasInClassInitializer()) &&
9608 shouldDeleteForSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable),
9609 IsDtorCallInCtor: false))
9610 return true;
9611
9612 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9613 // -- any direct or virtual base class or non-static data member has a
9614 // type with a destructor that is deleted or inaccessible
9615 if (IsConstructor) {
9616 Sema::SpecialMemberOverloadResult SMOR =
9617 S.LookupSpecialMember(D: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false,
9618 VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false);
9619 if (shouldDeleteForSubobjectCall(Subobj, SMOR, IsDtorCallInCtor: true))
9620 return true;
9621 }
9622
9623 return false;
9624}
9625
9626bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9627 FieldDecl *FD, QualType FieldType) {
9628 // The defaulted special functions are defined as deleted if this is a variant
9629 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9630 // type under ARC.
9631 if (!FieldType.hasNonTrivialObjCLifetime())
9632 return false;
9633
9634 // Don't make the defaulted default constructor defined as deleted if the
9635 // member has an in-class initializer.
9636 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9637 FD->hasInClassInitializer())
9638 return false;
9639
9640 if (Diagnose) {
9641 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9642 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9643 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9644 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9645 }
9646
9647 return true;
9648}
9649
9650bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9651 const FieldDecl *FD) {
9652 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9653 // Copy/move constructors/assignment operators are deleted if the field has an
9654 // address-discriminated ptrauth qualifier.
9655 PointerAuthQualifier Q = FieldType.getPointerAuth();
9656
9657 if (!Q || !Q.isAddressDiscriminated())
9658 return false;
9659
9660 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9661 CSM == CXXSpecialMemberKind::Destructor)
9662 return false;
9663
9664 if (Diagnose) {
9665 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9666 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9667 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9668 << /*IsDtorCallInCtor*/ false << 2;
9669 }
9670
9671 return true;
9672}
9673
9674/// Check whether we should delete a special member function due to the class
9675/// having a particular direct or virtual base class.
9676bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9677 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9678 // If program is correct, BaseClass cannot be null, but if it is, the error
9679 // must be reported elsewhere.
9680 if (!BaseClass)
9681 return false;
9682 // If we have an inheriting constructor, check whether we're calling an
9683 // inherited constructor instead of a default constructor.
9684 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
9685 if (auto *BaseCtor = SMOR.getMethod()) {
9686 // Note that we do not check access along this path; other than that,
9687 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9688 // FIXME: Check that the base has a usable destructor! Sink this into
9689 // shouldDeleteForClassSubobject.
9690 if (BaseCtor->isDeleted() && Diagnose) {
9691 S.Diag(Base->getBeginLoc(),
9692 diag::note_deleted_special_member_class_subobject)
9693 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9694 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9695 << /*IsObjCPtr*/ false;
9696 S.NoteDeletedFunction(BaseCtor);
9697 }
9698 return BaseCtor->isDeleted();
9699 }
9700 return shouldDeleteForClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
9701}
9702
9703/// Check whether we should delete a special member function due to the class
9704/// having a particular non-static data member.
9705bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9706 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9707 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9708
9709 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9710 return true;
9711
9712 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9713 return true;
9714
9715 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9716 // For a default constructor, all references must be initialized in-class
9717 // and, if a union, it must have a non-const member.
9718 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9719 if (Diagnose)
9720 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9721 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9722 return true;
9723 }
9724 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9725 // data member of const-qualified type (or array thereof) with no
9726 // brace-or-equal-initializer is not const-default-constructible.
9727 if (!inUnion() && FieldType.isConstQualified() &&
9728 !FD->hasInClassInitializer() &&
9729 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9730 if (Diagnose)
9731 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9732 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9733 return true;
9734 }
9735
9736 if (inUnion() && !FieldType.isConstQualified())
9737 AllFieldsAreConst = false;
9738 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9739 // For a copy constructor, data members must not be of rvalue reference
9740 // type.
9741 if (FieldType->isRValueReferenceType()) {
9742 if (Diagnose)
9743 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9744 << MD->getParent() << FD << FieldType;
9745 return true;
9746 }
9747 } else if (IsAssignment) {
9748 // For an assignment operator, data members must not be of reference type.
9749 if (FieldType->isReferenceType()) {
9750 if (Diagnose)
9751 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9752 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9753 return true;
9754 }
9755 if (!FieldRecord && FieldType.isConstQualified()) {
9756 // C++11 [class.copy]p23:
9757 // -- a non-static data member of const non-class type (or array thereof)
9758 if (Diagnose)
9759 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9760 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9761 return true;
9762 }
9763 }
9764
9765 if (FieldRecord) {
9766 // Some additional restrictions exist on the variant members.
9767 if (!inUnion() && FieldRecord->isUnion() &&
9768 FieldRecord->isAnonymousStructOrUnion()) {
9769 bool AllVariantFieldsAreConst = true;
9770
9771 // FIXME: Handle anonymous unions declared within anonymous unions.
9772 for (auto *UI : FieldRecord->fields()) {
9773 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9774
9775 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9776 return true;
9777
9778 if (shouldDeleteForVariantPtrAuthMember(&*UI))
9779 return true;
9780
9781 if (!UnionFieldType.isConstQualified())
9782 AllVariantFieldsAreConst = false;
9783
9784 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9785 if (UnionFieldRecord &&
9786 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9787 UnionFieldType.getCVRQualifiers()))
9788 return true;
9789 }
9790
9791 // At least one member in each anonymous union must be non-const
9792 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9793 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9794 if (Diagnose)
9795 S.Diag(FieldRecord->getLocation(),
9796 diag::note_deleted_default_ctor_all_const)
9797 << !!ICI << MD->getParent() << /*anonymous union*/1;
9798 return true;
9799 }
9800
9801 // Don't check the implicit member of the anonymous union type.
9802 // This is technically non-conformant but supported, and we have a
9803 // diagnostic for this elsewhere.
9804 return false;
9805 }
9806
9807 if (shouldDeleteForClassSubobject(Class: FieldRecord, Subobj: FD,
9808 Quals: FieldType.getCVRQualifiers()))
9809 return true;
9810 }
9811
9812 return false;
9813}
9814
9815/// C++11 [class.ctor] p5:
9816/// A defaulted default constructor for a class X is defined as deleted if
9817/// X is a union and all of its variant members are of const-qualified type.
9818bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9819 // This is a silly definition, because it gives an empty union a deleted
9820 // default constructor. Don't do that.
9821 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9822 AllFieldsAreConst) {
9823 bool AnyFields = false;
9824 for (auto *F : MD->getParent()->fields())
9825 if ((AnyFields = !F->isUnnamedBitField()))
9826 break;
9827 if (!AnyFields)
9828 return false;
9829 if (Diagnose)
9830 S.Diag(MD->getParent()->getLocation(),
9831 diag::note_deleted_default_ctor_all_const)
9832 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9833 return true;
9834 }
9835 return false;
9836}
9837
9838/// Determine whether a defaulted special member function should be defined as
9839/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9840/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9841bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
9842 CXXSpecialMemberKind CSM,
9843 InheritedConstructorInfo *ICI,
9844 bool Diagnose) {
9845 if (MD->isInvalidDecl())
9846 return false;
9847 CXXRecordDecl *RD = MD->getParent();
9848 assert(!RD->isDependentType() && "do deletion after instantiation");
9849 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9850 RD->isInvalidDecl())
9851 return false;
9852
9853 // C++11 [expr.lambda.prim]p19:
9854 // The closure type associated with a lambda-expression has a
9855 // deleted (8.4.3) default constructor and a deleted copy
9856 // assignment operator.
9857 // C++2a adds back these operators if the lambda has no lambda-capture.
9858 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9859 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9860 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9861 if (Diagnose)
9862 Diag(RD->getLocation(), diag::note_lambda_decl);
9863 return true;
9864 }
9865
9866 // For an anonymous struct or union, the copy and assignment special members
9867 // will never be used, so skip the check. For an anonymous union declared at
9868 // namespace scope, the constructor and destructor are used.
9869 if (CSM != CXXSpecialMemberKind::DefaultConstructor &&
9870 CSM != CXXSpecialMemberKind::Destructor && RD->isAnonymousStructOrUnion())
9871 return false;
9872
9873 // C++11 [class.copy]p7, p18:
9874 // If the class definition declares a move constructor or move assignment
9875 // operator, an implicitly declared copy constructor or copy assignment
9876 // operator is defined as deleted.
9877 if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
9878 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9879 CXXMethodDecl *UserDeclaredMove = nullptr;
9880
9881 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9882 // deletion of the corresponding copy operation, not both copy operations.
9883 // MSVC 2015 has adopted the standards conforming behavior.
9884 bool DeletesOnlyMatchingCopy =
9885 getLangOpts().MSVCCompat &&
9886 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
9887
9888 if (RD->hasUserDeclaredMoveConstructor() &&
9889 (!DeletesOnlyMatchingCopy ||
9890 CSM == CXXSpecialMemberKind::CopyConstructor)) {
9891 if (!Diagnose) return true;
9892
9893 // Find any user-declared move constructor.
9894 for (auto *I : RD->ctors()) {
9895 if (I->isMoveConstructor()) {
9896 UserDeclaredMove = I;
9897 break;
9898 }
9899 }
9900 assert(UserDeclaredMove);
9901 } else if (RD->hasUserDeclaredMoveAssignment() &&
9902 (!DeletesOnlyMatchingCopy ||
9903 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9904 if (!Diagnose) return true;
9905
9906 // Find any user-declared move assignment operator.
9907 for (auto *I : RD->methods()) {
9908 if (I->isMoveAssignmentOperator()) {
9909 UserDeclaredMove = I;
9910 break;
9911 }
9912 }
9913 assert(UserDeclaredMove);
9914 }
9915
9916 if (UserDeclaredMove) {
9917 Diag(UserDeclaredMove->getLocation(),
9918 diag::note_deleted_copy_user_declared_move)
9919 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9920 << UserDeclaredMove->isMoveAssignmentOperator();
9921 return true;
9922 }
9923 }
9924
9925 // Do access control from the special member function
9926 ContextRAII MethodContext(*this, MD);
9927
9928 // C++11 [class.dtor]p5:
9929 // -- for a virtual destructor, lookup of the non-array deallocation function
9930 // results in an ambiguity or in a function that is deleted or inaccessible
9931 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9932 FunctionDecl *OperatorDelete = nullptr;
9933 QualType DeallocType = Context.getRecordType(RD);
9934 DeclarationName Name =
9935 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
9936 ImplicitDeallocationParameters IDP = {
9937 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
9938 AlignedAllocationMode::No, SizedDeallocationMode::No};
9939 if (FindDeallocationFunction(StartLoc: MD->getLocation(), RD: MD->getParent(), Name,
9940 Operator&: OperatorDelete, IDP,
9941 /*Diagnose=*/false)) {
9942 if (Diagnose)
9943 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9944 return true;
9945 }
9946 }
9947
9948 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9949
9950 // Per DR1611, do not consider virtual bases of constructors of abstract
9951 // classes, since we are not going to construct them.
9952 // Per DR1658, do not consider virtual bases of destructors of abstract
9953 // classes either.
9954 // Per DR2180, for assignment operators we only assign (and thus only
9955 // consider) direct bases.
9956 if (SMI.visit(Bases: SMI.IsAssignment ? SMI.VisitDirectBases
9957 : SMI.VisitPotentiallyConstructedBases))
9958 return true;
9959
9960 if (SMI.shouldDeleteForAllConstMembers())
9961 return true;
9962
9963 if (getLangOpts().CUDA) {
9964 // We should delete the special member in CUDA mode if target inference
9965 // failed.
9966 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9967 // is treated as certain special member, which may not reflect what special
9968 // member MD really is. However inferTargetForImplicitSpecialMember
9969 // expects CSM to match MD, therefore recalculate CSM.
9970 assert(ICI || CSM == getSpecialMember(MD));
9971 auto RealCSM = CSM;
9972 if (ICI)
9973 RealCSM = getSpecialMember(MD);
9974
9975 return CUDA().inferTargetForImplicitSpecialMember(ClassDecl: RD, CSM: RealCSM, MemberDecl: MD,
9976 ConstRHS: SMI.ConstArg, Diagnose);
9977 }
9978
9979 return false;
9980}
9981
9982void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9983 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9984 assert(DFK && "not a defaultable function");
9985 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9986
9987 if (DFK.isSpecialMember()) {
9988 ShouldDeleteSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(),
9989 ICI: nullptr, /*Diagnose=*/true);
9990 } else {
9991 DefaultedComparisonAnalyzer(
9992 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9993 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9994 .visit();
9995 }
9996}
9997
9998/// Perform lookup for a special member of the specified kind, and determine
9999/// whether it is trivial. If the triviality can be determined without the
10000/// lookup, skip it. This is intended for use when determining whether a
10001/// special member of a containing object is trivial, and thus does not ever
10002/// perform overload resolution for default constructors.
10003///
10004/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10005/// member that was most likely to be intended to be trivial, if any.
10006///
10007/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10008/// determine whether the special member is trivial.
10009static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
10010 CXXSpecialMemberKind CSM, unsigned Quals,
10011 bool ConstRHS, TrivialABIHandling TAH,
10012 CXXMethodDecl **Selected) {
10013 if (Selected)
10014 *Selected = nullptr;
10015
10016 switch (CSM) {
10017 case CXXSpecialMemberKind::Invalid:
10018 llvm_unreachable("not a special member");
10019
10020 case CXXSpecialMemberKind::DefaultConstructor:
10021 // C++11 [class.ctor]p5:
10022 // A default constructor is trivial if:
10023 // - all the [direct subobjects] have trivial default constructors
10024 //
10025 // Note, no overload resolution is performed in this case.
10026 if (RD->hasTrivialDefaultConstructor())
10027 return true;
10028
10029 if (Selected) {
10030 // If there's a default constructor which could have been trivial, dig it
10031 // out. Otherwise, if there's any user-provided default constructor, point
10032 // to that as an example of why there's not a trivial one.
10033 CXXConstructorDecl *DefCtor = nullptr;
10034 if (RD->needsImplicitDefaultConstructor())
10035 S.DeclareImplicitDefaultConstructor(ClassDecl: RD);
10036 for (auto *CI : RD->ctors()) {
10037 if (!CI->isDefaultConstructor())
10038 continue;
10039 DefCtor = CI;
10040 if (!DefCtor->isUserProvided())
10041 break;
10042 }
10043
10044 *Selected = DefCtor;
10045 }
10046
10047 return false;
10048
10049 case CXXSpecialMemberKind::Destructor:
10050 // C++11 [class.dtor]p5:
10051 // A destructor is trivial if:
10052 // - all the direct [subobjects] have trivial destructors
10053 if (RD->hasTrivialDestructor() ||
10054 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10055 RD->hasTrivialDestructorForCall()))
10056 return true;
10057
10058 if (Selected) {
10059 if (RD->needsImplicitDestructor())
10060 S.DeclareImplicitDestructor(ClassDecl: RD);
10061 *Selected = RD->getDestructor();
10062 }
10063
10064 return false;
10065
10066 case CXXSpecialMemberKind::CopyConstructor:
10067 // C++11 [class.copy]p12:
10068 // A copy constructor is trivial if:
10069 // - the constructor selected to copy each direct [subobject] is trivial
10070 if (RD->hasTrivialCopyConstructor() ||
10071 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10072 RD->hasTrivialCopyConstructorForCall())) {
10073 if (Quals == Qualifiers::Const)
10074 // We must either select the trivial copy constructor or reach an
10075 // ambiguity; no need to actually perform overload resolution.
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, as suggested on cxx-abi-dev, to treat
10082 // cases like B as having a non-trivial copy constructor:
10083 // struct A { template<typename T> A(T&); };
10084 // struct B { mutable A a; };
10085 goto NeedOverloadResolution;
10086
10087 case CXXSpecialMemberKind::CopyAssignment:
10088 // C++11 [class.copy]p25:
10089 // A copy assignment operator is trivial if:
10090 // - the assignment operator selected to copy each direct [subobject] is
10091 // trivial
10092 if (RD->hasTrivialCopyAssignment()) {
10093 if (Quals == Qualifiers::Const)
10094 return true;
10095 } else if (!Selected) {
10096 return false;
10097 }
10098 // In C++98, we are not supposed to perform overload resolution here, but we
10099 // treat that as a language defect.
10100 goto NeedOverloadResolution;
10101
10102 case CXXSpecialMemberKind::MoveConstructor:
10103 case CXXSpecialMemberKind::MoveAssignment:
10104 NeedOverloadResolution:
10105 Sema::SpecialMemberOverloadResult SMOR =
10106 lookupCallFromSpecialMember(S, Class: RD, CSM, FieldQuals: Quals, ConstRHS);
10107
10108 // The standard doesn't describe how to behave if the lookup is ambiguous.
10109 // We treat it as not making the member non-trivial, just like the standard
10110 // mandates for the default constructor. This should rarely matter, because
10111 // the member will also be deleted.
10112 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10113 return true;
10114
10115 if (!SMOR.getMethod()) {
10116 assert(SMOR.getKind() ==
10117 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
10118 return false;
10119 }
10120
10121 // We deliberately don't check if we found a deleted special member. We're
10122 // not supposed to!
10123 if (Selected)
10124 *Selected = SMOR.getMethod();
10125
10126 if (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10127 (CSM == CXXSpecialMemberKind::CopyConstructor ||
10128 CSM == CXXSpecialMemberKind::MoveConstructor))
10129 return SMOR.getMethod()->isTrivialForCall();
10130 return SMOR.getMethod()->isTrivial();
10131 }
10132
10133 llvm_unreachable("unknown special method kind");
10134}
10135
10136static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10137 for (auto *CI : RD->ctors())
10138 if (!CI->isImplicit())
10139 return CI;
10140
10141 // Look for constructor templates.
10142 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10143 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10144 if (CXXConstructorDecl *CD =
10145 dyn_cast<CXXConstructorDecl>(Val: TI->getTemplatedDecl()))
10146 return CD;
10147 }
10148
10149 return nullptr;
10150}
10151
10152/// The kind of subobject we are checking for triviality. The values of this
10153/// enumeration are used in diagnostics.
10154enum TrivialSubobjectKind {
10155 /// The subobject is a base class.
10156 TSK_BaseClass,
10157 /// The subobject is a non-static data member.
10158 TSK_Field,
10159 /// The object is actually the complete object.
10160 TSK_CompleteObject
10161};
10162
10163/// Check whether the special member selected for a given type would be trivial.
10164static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10165 QualType SubType, bool ConstRHS,
10166 CXXSpecialMemberKind CSM,
10167 TrivialSubobjectKind Kind,
10168 TrivialABIHandling TAH, bool Diagnose) {
10169 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10170 if (!SubRD)
10171 return true;
10172
10173 CXXMethodDecl *Selected;
10174 if (findTrivialSpecialMember(S, RD: SubRD, CSM, Quals: SubType.getCVRQualifiers(),
10175 ConstRHS, TAH, Selected: Diagnose ? &Selected : nullptr))
10176 return true;
10177
10178 if (Diagnose) {
10179 if (ConstRHS)
10180 SubType.addConst();
10181
10182 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10183 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10184 << Kind << SubType.getUnqualifiedType();
10185 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
10186 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10187 } else if (!Selected)
10188 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10189 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10190 else if (Selected->isUserProvided()) {
10191 if (Kind == TSK_CompleteObject)
10192 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10193 << Kind << SubType.getUnqualifiedType() << CSM;
10194 else {
10195 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10196 << Kind << SubType.getUnqualifiedType() << CSM;
10197 S.Diag(Selected->getLocation(), diag::note_declared_at);
10198 }
10199 } else {
10200 if (Kind != TSK_CompleteObject)
10201 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10202 << Kind << SubType.getUnqualifiedType() << CSM;
10203
10204 // Explain why the defaulted or deleted special member isn't trivial.
10205 S.SpecialMemberIsTrivial(MD: Selected, CSM,
10206 TAH: TrivialABIHandling::IgnoreTrivialABI, Diagnose);
10207 }
10208 }
10209
10210 return false;
10211}
10212
10213/// Check whether the members of a class type allow a special member to be
10214/// trivial.
10215static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10216 CXXSpecialMemberKind CSM, bool ConstArg,
10217 TrivialABIHandling TAH, bool Diagnose) {
10218 for (const auto *FI : RD->fields()) {
10219 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10220 continue;
10221
10222 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10223
10224 // Pretend anonymous struct or union members are members of this class.
10225 if (FI->isAnonymousStructOrUnion()) {
10226 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10227 CSM, ConstArg, TAH, Diagnose))
10228 return false;
10229 continue;
10230 }
10231
10232 // C++11 [class.ctor]p5:
10233 // A default constructor is trivial if [...]
10234 // -- no non-static data member of its class has a
10235 // brace-or-equal-initializer
10236 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10237 FI->hasInClassInitializer()) {
10238 if (Diagnose)
10239 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10240 << FI;
10241 return false;
10242 }
10243
10244 // Objective C ARC 4.3.5:
10245 // [...] nontrivally ownership-qualified types are [...] not trivially
10246 // default constructible, copy constructible, move constructible, copy
10247 // assignable, move assignable, or destructible [...]
10248 if (FieldType.hasNonTrivialObjCLifetime()) {
10249 if (Diagnose)
10250 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10251 << RD << FieldType.getObjCLifetime();
10252 return false;
10253 }
10254
10255 bool ConstRHS = ConstArg && !FI->isMutable();
10256 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10257 CSM, TSK_Field, TAH, Diagnose))
10258 return false;
10259 }
10260
10261 return true;
10262}
10263
10264void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10265 CXXSpecialMemberKind CSM) {
10266 QualType Ty = Context.getRecordType(RD);
10267
10268 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10269 CSM == CXXSpecialMemberKind::CopyAssignment);
10270 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10271 TSK_CompleteObject,
10272 TrivialABIHandling::IgnoreTrivialABI,
10273 /*Diagnose*/ true);
10274}
10275
10276bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10277 TrivialABIHandling TAH, bool Diagnose) {
10278 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10279 "not special enough");
10280
10281 CXXRecordDecl *RD = MD->getParent();
10282
10283 bool ConstArg = false;
10284
10285 // C++11 [class.copy]p12, p25: [DR1593]
10286 // A [special member] is trivial if [...] its parameter-type-list is
10287 // equivalent to the parameter-type-list of an implicit declaration [...]
10288 switch (CSM) {
10289 case CXXSpecialMemberKind::DefaultConstructor:
10290 case CXXSpecialMemberKind::Destructor:
10291 // Trivial default constructors and destructors cannot have parameters.
10292 break;
10293
10294 case CXXSpecialMemberKind::CopyConstructor:
10295 case CXXSpecialMemberKind::CopyAssignment: {
10296 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10297 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10298
10299 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10300 // if they are not user-provided and their parameter-type-list is equivalent
10301 // to the parameter-type-list of an implicit declaration. This maintains the
10302 // behavior before dr2171 was implemented.
10303 //
10304 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10305 // trivial, if they are not user-provided, regardless of the qualifiers on
10306 // the reference type.
10307 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10308 LangOptions::ClangABI::Ver14;
10309 if (!RT ||
10310 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10311 ClangABICompat14)) {
10312 if (Diagnose)
10313 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10314 << Param0->getSourceRange() << Param0->getType()
10315 << Context.getLValueReferenceType(
10316 Context.getRecordType(RD).withConst());
10317 return false;
10318 }
10319
10320 ConstArg = RT->getPointeeType().isConstQualified();
10321 break;
10322 }
10323
10324 case CXXSpecialMemberKind::MoveConstructor:
10325 case CXXSpecialMemberKind::MoveAssignment: {
10326 // Trivial move operations always have non-cv-qualified parameters.
10327 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10328 const RValueReferenceType *RT =
10329 Param0->getType()->getAs<RValueReferenceType>();
10330 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10331 if (Diagnose)
10332 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10333 << Param0->getSourceRange() << Param0->getType()
10334 << Context.getRValueReferenceType(Context.getRecordType(RD));
10335 return false;
10336 }
10337 break;
10338 }
10339
10340 case CXXSpecialMemberKind::Invalid:
10341 llvm_unreachable("not a special member");
10342 }
10343
10344 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10345 if (Diagnose)
10346 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
10347 diag::note_nontrivial_default_arg)
10348 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
10349 return false;
10350 }
10351 if (MD->isVariadic()) {
10352 if (Diagnose)
10353 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10354 return false;
10355 }
10356
10357 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10358 // A copy/move [constructor or assignment operator] is trivial if
10359 // -- the [member] selected to copy/move each direct base class subobject
10360 // is trivial
10361 //
10362 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10363 // A [default constructor or destructor] is trivial if
10364 // -- all the direct base classes have trivial [default constructors or
10365 // destructors]
10366 for (const auto &BI : RD->bases())
10367 if (!checkTrivialSubobjectCall(S&: *this, SubobjLoc: BI.getBeginLoc(), SubType: BI.getType(),
10368 ConstRHS: ConstArg, CSM, Kind: TSK_BaseClass, TAH, Diagnose))
10369 return false;
10370
10371 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10372 // A copy/move [constructor or assignment operator] for a class X is
10373 // trivial if
10374 // -- for each non-static data member of X that is of class type (or array
10375 // thereof), the constructor selected to copy/move that member is
10376 // trivial
10377 //
10378 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10379 // A [default constructor or destructor] is trivial if
10380 // -- for all of the non-static data members of its class that are of class
10381 // type (or array thereof), each such class has a trivial [default
10382 // constructor or destructor]
10383 if (!checkTrivialClassMembers(S&: *this, RD, CSM, ConstArg, TAH, Diagnose))
10384 return false;
10385
10386 // C++11 [class.dtor]p5:
10387 // A destructor is trivial if [...]
10388 // -- the destructor is not virtual
10389 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10390 if (Diagnose)
10391 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10392 return false;
10393 }
10394
10395 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10396 // A [special member] for class X is trivial if [...]
10397 // -- class X has no virtual functions and no virtual base classes
10398 if (CSM != CXXSpecialMemberKind::Destructor &&
10399 MD->getParent()->isDynamicClass()) {
10400 if (!Diagnose)
10401 return false;
10402
10403 if (RD->getNumVBases()) {
10404 // Check for virtual bases. We already know that the corresponding
10405 // member in all bases is trivial, so vbases must all be direct.
10406 CXXBaseSpecifier &BS = *RD->vbases_begin();
10407 assert(BS.isVirtual());
10408 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10409 return false;
10410 }
10411
10412 // Must have a virtual method.
10413 for (const auto *MI : RD->methods()) {
10414 if (MI->isVirtual()) {
10415 SourceLocation MLoc = MI->getBeginLoc();
10416 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10417 return false;
10418 }
10419 }
10420
10421 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10422 }
10423
10424 // Looks like it's trivial!
10425 return true;
10426}
10427
10428namespace {
10429struct FindHiddenVirtualMethod {
10430 Sema *S;
10431 CXXMethodDecl *Method;
10432 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10433 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10434
10435private:
10436 /// Check whether any most overridden method from MD in Methods
10437 static bool CheckMostOverridenMethods(
10438 const CXXMethodDecl *MD,
10439 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10440 if (MD->size_overridden_methods() == 0)
10441 return Methods.count(Ptr: MD->getCanonicalDecl());
10442 for (const CXXMethodDecl *O : MD->overridden_methods())
10443 if (CheckMostOverridenMethods(MD: O, Methods))
10444 return true;
10445 return false;
10446 }
10447
10448public:
10449 /// Member lookup function that determines whether a given C++
10450 /// method overloads virtual methods in a base class without overriding any,
10451 /// to be used with CXXRecordDecl::lookupInBases().
10452 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10453 RecordDecl *BaseRecord =
10454 Specifier->getType()->castAs<RecordType>()->getDecl();
10455
10456 DeclarationName Name = Method->getDeclName();
10457 assert(Name.getNameKind() == DeclarationName::Identifier);
10458
10459 bool foundSameNameMethod = false;
10460 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10461 for (Path.Decls = BaseRecord->lookup(Name).begin();
10462 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10463 NamedDecl *D = *Path.Decls;
10464 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
10465 MD = MD->getCanonicalDecl();
10466 foundSameNameMethod = true;
10467 // Interested only in hidden virtual methods.
10468 if (!MD->isVirtual())
10469 continue;
10470 // If the method we are checking overrides a method from its base
10471 // don't warn about the other overloaded methods. Clang deviates from
10472 // GCC by only diagnosing overloads of inherited virtual functions that
10473 // do not override any other virtual functions in the base. GCC's
10474 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10475 // function from a base class. These cases may be better served by a
10476 // warning (not specific to virtual functions) on call sites when the
10477 // call would select a different function from the base class, were it
10478 // visible.
10479 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10480 if (!S->IsOverload(Method, MD, false))
10481 return true;
10482 // Collect the overload only if its hidden.
10483 if (!CheckMostOverridenMethods(MD, Methods: OverridenAndUsingBaseMethods))
10484 overloadedMethods.push_back(Elt: MD);
10485 }
10486 }
10487
10488 if (foundSameNameMethod)
10489 OverloadedMethods.append(in_start: overloadedMethods.begin(),
10490 in_end: overloadedMethods.end());
10491 return foundSameNameMethod;
10492 }
10493};
10494} // end anonymous namespace
10495
10496/// Add the most overridden methods from MD to Methods
10497static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10498 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10499 if (MD->size_overridden_methods() == 0)
10500 Methods.insert(Ptr: MD->getCanonicalDecl());
10501 else
10502 for (const CXXMethodDecl *O : MD->overridden_methods())
10503 AddMostOverridenMethods(MD: O, Methods);
10504}
10505
10506void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10507 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10508 if (!MD->getDeclName().isIdentifier())
10509 return;
10510
10511 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10512 /*bool RecordPaths=*/false,
10513 /*bool DetectVirtual=*/false);
10514 FindHiddenVirtualMethod FHVM;
10515 FHVM.Method = MD;
10516 FHVM.S = this;
10517
10518 // Keep the base methods that were overridden or introduced in the subclass
10519 // by 'using' in a set. A base method not in this set is hidden.
10520 CXXRecordDecl *DC = MD->getParent();
10521 DeclContext::lookup_result R = DC->lookup(Name: MD->getDeclName());
10522 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10523 NamedDecl *ND = *I;
10524 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(Val: *I))
10525 ND = shad->getTargetDecl();
10526 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ND))
10527 AddMostOverridenMethods(MD, Methods&: FHVM.OverridenAndUsingBaseMethods);
10528 }
10529
10530 if (DC->lookupInBases(BaseMatches: FHVM, Paths))
10531 OverloadedMethods = FHVM.OverloadedMethods;
10532}
10533
10534void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10535 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10536 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10537 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10538 PartialDiagnostic PD = PDiag(
10539 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10540 HandleFunctionTypeMismatch(PDiag&: PD, FromType: MD->getType(), ToType: overloadedMD->getType());
10541 Diag(overloadedMD->getLocation(), PD);
10542 }
10543}
10544
10545void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10546 if (MD->isInvalidDecl())
10547 return;
10548
10549 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10550 return;
10551
10552 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10553 FindHiddenVirtualMethods(MD, OverloadedMethods);
10554 if (!OverloadedMethods.empty()) {
10555 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10556 << MD << (OverloadedMethods.size() > 1);
10557
10558 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10559 }
10560}
10561
10562void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10563 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10564 // No diagnostics if this is a template instantiation.
10565 if (!isTemplateInstantiation(Kind: RD.getTemplateSpecializationKind())) {
10566 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10567 diag::ext_cannot_use_trivial_abi) << &RD;
10568 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10569 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10570 }
10571 RD.dropAttr<TrivialABIAttr>();
10572 };
10573
10574 // Ill-formed if the struct has virtual functions.
10575 if (RD.isPolymorphic()) {
10576 PrintDiagAndRemoveAttr(1);
10577 return;
10578 }
10579
10580 for (const auto &B : RD.bases()) {
10581 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10582 // virtual base.
10583 if (!B.getType()->isDependentType() &&
10584 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10585 PrintDiagAndRemoveAttr(2);
10586 return;
10587 }
10588
10589 if (B.isVirtual()) {
10590 PrintDiagAndRemoveAttr(3);
10591 return;
10592 }
10593 }
10594
10595 for (const auto *FD : RD.fields()) {
10596 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10597 // non-trivial for the purpose of calls.
10598 QualType FT = FD->getType();
10599 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10600 PrintDiagAndRemoveAttr(4);
10601 return;
10602 }
10603
10604 // Ill-formed if the field is an address-discriminated value.
10605 if (FT.hasAddressDiscriminatedPointerAuth()) {
10606 PrintDiagAndRemoveAttr(6);
10607 return;
10608 }
10609
10610 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10611 if (!RT->isDependentType() &&
10612 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10613 PrintDiagAndRemoveAttr(5);
10614 return;
10615 }
10616 }
10617
10618 if (IsCXXTriviallyRelocatableType(RD))
10619 return;
10620
10621 // Ill-formed if the copy and move constructors are deleted.
10622 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10623 // If the type is dependent, then assume it might have
10624 // implicit copy or move ctor because we won't know yet at this point.
10625 if (RD.isDependentType())
10626 return true;
10627 if (RD.needsImplicitCopyConstructor() &&
10628 !RD.defaultedCopyConstructorIsDeleted())
10629 return true;
10630 if (RD.needsImplicitMoveConstructor() &&
10631 !RD.defaultedMoveConstructorIsDeleted())
10632 return true;
10633 for (const CXXConstructorDecl *CD : RD.ctors())
10634 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10635 return true;
10636 return false;
10637 };
10638
10639 if (!HasNonDeletedCopyOrMoveConstructor()) {
10640 PrintDiagAndRemoveAttr(0);
10641 return;
10642 }
10643}
10644
10645void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
10646 CXXRecordDecl &RD) {
10647 if (RequireCompleteType(RD.getLocation(), Context.getRecordType(&RD),
10648 diag::err_incomplete_type_vtable_pointer_auth))
10649 return;
10650
10651 const CXXRecordDecl *PrimaryBase = &RD;
10652 if (PrimaryBase->hasAnyDependentBases())
10653 return;
10654
10655 while (1) {
10656 assert(PrimaryBase);
10657 const CXXRecordDecl *Base = nullptr;
10658 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10659 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10660 continue;
10661 Base = BasePtr.getType()->getAsCXXRecordDecl();
10662 break;
10663 }
10664 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10665 break;
10666 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10667 diag::err_non_top_level_vtable_pointer_auth)
10668 << &RD << Base;
10669 PrimaryBase = Base;
10670 }
10671
10672 if (!RD.isPolymorphic())
10673 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10674 diag::err_non_polymorphic_vtable_pointer_auth)
10675 << &RD;
10676}
10677
10678void Sema::ActOnFinishCXXMemberSpecification(
10679 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10680 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10681 if (!TagDecl)
10682 return;
10683
10684 AdjustDeclIfTemplate(Decl&: TagDecl);
10685
10686 for (const ParsedAttr &AL : AttrList) {
10687 if (AL.getKind() != ParsedAttr::AT_Visibility)
10688 continue;
10689 AL.setInvalid();
10690 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10691 }
10692
10693 ActOnFields(S, RecLoc: RLoc, TagDecl,
10694 Fields: llvm::ArrayRef(
10695 // strict aliasing violation!
10696 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10697 FieldCollector->getCurNumFields()),
10698 LBrac, RBrac, AttrList);
10699
10700 CheckCompletedCXXClass(S, Record: cast<CXXRecordDecl>(Val: TagDecl));
10701}
10702
10703/// Find the equality comparison functions that should be implicitly declared
10704/// in a given class definition, per C++2a [class.compare.default]p3.
10705static void findImplicitlyDeclaredEqualityComparisons(
10706 ASTContext &Ctx, CXXRecordDecl *RD,
10707 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10708 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual);
10709 if (!RD->lookup(EqEq).empty())
10710 // Member operator== explicitly declared: no implicit operator==s.
10711 return;
10712
10713 // Traverse friends looking for an '==' or a '<=>'.
10714 for (FriendDecl *Friend : RD->friends()) {
10715 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Friend->getFriendDecl());
10716 if (!FD) continue;
10717
10718 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10719 // Friend operator== explicitly declared: no implicit operator==s.
10720 Spaceships.clear();
10721 return;
10722 }
10723
10724 if (FD->getOverloadedOperator() == OO_Spaceship &&
10725 FD->isExplicitlyDefaulted())
10726 Spaceships.push_back(Elt: FD);
10727 }
10728
10729 // Look for members named 'operator<=>'.
10730 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_Spaceship);
10731 for (NamedDecl *ND : RD->lookup(Cmp)) {
10732 // Note that we could find a non-function here (either a function template
10733 // or a using-declaration). Neither case results in an implicit
10734 // 'operator=='.
10735 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10736 if (FD->isExplicitlyDefaulted())
10737 Spaceships.push_back(FD);
10738 }
10739}
10740
10741void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10742 // Don't add implicit special members to templated classes.
10743 // FIXME: This means unqualified lookups for 'operator=' within a class
10744 // template don't work properly.
10745 if (!ClassDecl->isDependentType()) {
10746 if (ClassDecl->needsImplicitDefaultConstructor()) {
10747 ++getASTContext().NumImplicitDefaultConstructors;
10748
10749 if (ClassDecl->hasInheritedConstructor())
10750 DeclareImplicitDefaultConstructor(ClassDecl);
10751 }
10752
10753 if (ClassDecl->needsImplicitCopyConstructor()) {
10754 ++getASTContext().NumImplicitCopyConstructors;
10755
10756 // If the properties or semantics of the copy constructor couldn't be
10757 // determined while the class was being declared, force a declaration
10758 // of it now.
10759 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10760 ClassDecl->hasInheritedConstructor())
10761 DeclareImplicitCopyConstructor(ClassDecl);
10762 // For the MS ABI we need to know whether the copy ctor is deleted. A
10763 // prerequisite for deleting the implicit copy ctor is that the class has
10764 // a move ctor or move assignment that is either user-declared or whose
10765 // semantics are inherited from a subobject. FIXME: We should provide a
10766 // more direct way for CodeGen to ask whether the constructor was deleted.
10767 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10768 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10769 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10770 ClassDecl->hasUserDeclaredMoveAssignment() ||
10771 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10772 DeclareImplicitCopyConstructor(ClassDecl);
10773 }
10774
10775 if (getLangOpts().CPlusPlus11 &&
10776 ClassDecl->needsImplicitMoveConstructor()) {
10777 ++getASTContext().NumImplicitMoveConstructors;
10778
10779 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10780 ClassDecl->hasInheritedConstructor())
10781 DeclareImplicitMoveConstructor(ClassDecl);
10782 }
10783
10784 if (ClassDecl->needsImplicitCopyAssignment()) {
10785 ++getASTContext().NumImplicitCopyAssignmentOperators;
10786
10787 // If we have a dynamic class, then the copy assignment operator may be
10788 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10789 // it shows up in the right place in the vtable and that we diagnose
10790 // problems with the implicit exception specification.
10791 if (ClassDecl->isDynamicClass() ||
10792 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10793 ClassDecl->hasInheritedAssignment())
10794 DeclareImplicitCopyAssignment(ClassDecl);
10795 }
10796
10797 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10798 ++getASTContext().NumImplicitMoveAssignmentOperators;
10799
10800 // Likewise for the move assignment operator.
10801 if (ClassDecl->isDynamicClass() ||
10802 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10803 ClassDecl->hasInheritedAssignment())
10804 DeclareImplicitMoveAssignment(ClassDecl);
10805 }
10806
10807 if (ClassDecl->needsImplicitDestructor()) {
10808 ++getASTContext().NumImplicitDestructors;
10809
10810 // If we have a dynamic class, then the destructor may be virtual, so we
10811 // have to declare the destructor immediately. This ensures that, e.g., it
10812 // shows up in the right place in the vtable and that we diagnose problems
10813 // with the implicit exception specification.
10814 if (ClassDecl->isDynamicClass() ||
10815 ClassDecl->needsOverloadResolutionForDestructor())
10816 DeclareImplicitDestructor(ClassDecl);
10817 }
10818 }
10819
10820 // C++2a [class.compare.default]p3:
10821 // If the member-specification does not explicitly declare any member or
10822 // friend named operator==, an == operator function is declared implicitly
10823 // for each defaulted three-way comparison operator function defined in
10824 // the member-specification
10825 // FIXME: Consider doing this lazily.
10826 // We do this during the initial parse for a class template, not during
10827 // instantiation, so that we can handle unqualified lookups for 'operator=='
10828 // when parsing the template.
10829 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10830 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10831 findImplicitlyDeclaredEqualityComparisons(Ctx&: Context, RD: ClassDecl,
10832 Spaceships&: DefaultedSpaceships);
10833 for (auto *FD : DefaultedSpaceships)
10834 DeclareImplicitEqualityComparison(RD: ClassDecl, Spaceship: FD);
10835 }
10836}
10837
10838unsigned
10839Sema::ActOnReenterTemplateScope(Decl *D,
10840 llvm::function_ref<Scope *()> EnterScope) {
10841 if (!D)
10842 return 0;
10843 AdjustDeclIfTemplate(Decl&: D);
10844
10845 // In order to get name lookup right, reenter template scopes in order from
10846 // outermost to innermost.
10847 SmallVector<TemplateParameterList *, 4> ParameterLists;
10848 DeclContext *LookupDC = dyn_cast<DeclContext>(Val: D);
10849
10850 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
10851 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10852 ParameterLists.push_back(Elt: DD->getTemplateParameterList(index: i));
10853
10854 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
10855 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10856 ParameterLists.push_back(Elt: FTD->getTemplateParameters());
10857 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
10858 LookupDC = VD->getDeclContext();
10859
10860 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10861 ParameterLists.push_back(Elt: VTD->getTemplateParameters());
10862 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D))
10863 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
10864 }
10865 } else if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
10866 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10867 ParameterLists.push_back(Elt: TD->getTemplateParameterList(i));
10868
10869 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TD)) {
10870 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10871 ParameterLists.push_back(Elt: CTD->getTemplateParameters());
10872 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D))
10873 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
10874 }
10875 }
10876 // FIXME: Alias declarations and concepts.
10877
10878 unsigned Count = 0;
10879 Scope *InnermostTemplateScope = nullptr;
10880 for (TemplateParameterList *Params : ParameterLists) {
10881 // Ignore explicit specializations; they don't contribute to the template
10882 // depth.
10883 if (Params->size() == 0)
10884 continue;
10885
10886 InnermostTemplateScope = EnterScope();
10887 for (NamedDecl *Param : *Params) {
10888 if (Param->getDeclName()) {
10889 InnermostTemplateScope->AddDecl(Param);
10890 IdResolver.AddDecl(D: Param);
10891 }
10892 }
10893 ++Count;
10894 }
10895
10896 // Associate the new template scopes with the corresponding entities.
10897 if (InnermostTemplateScope) {
10898 assert(LookupDC && "no enclosing DeclContext for template lookup");
10899 EnterTemplatedContext(S: InnermostTemplateScope, DC: LookupDC);
10900 }
10901
10902 return Count;
10903}
10904
10905void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10906 if (!RecordD) return;
10907 AdjustDeclIfTemplate(Decl&: RecordD);
10908 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: RecordD);
10909 PushDeclContext(S, Record);
10910}
10911
10912void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10913 if (!RecordD) return;
10914 PopDeclContext();
10915}
10916
10917void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10918 if (!Param)
10919 return;
10920
10921 S->AddDecl(Param);
10922 if (Param->getDeclName())
10923 IdResolver.AddDecl(Param);
10924}
10925
10926void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10927}
10928
10929/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10930/// C++ method declaration. We're (re-)introducing the given
10931/// function parameter into scope for use in parsing later parts of
10932/// the method declaration. For example, we could see an
10933/// ActOnParamDefaultArgument event for this parameter.
10934void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10935 if (!ParamD)
10936 return;
10937
10938 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamD);
10939
10940 S->AddDecl(Param);
10941 if (Param->getDeclName())
10942 IdResolver.AddDecl(Param);
10943}
10944
10945void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10946 if (!MethodD)
10947 return;
10948
10949 AdjustDeclIfTemplate(Decl&: MethodD);
10950
10951 FunctionDecl *Method = cast<FunctionDecl>(Val: MethodD);
10952
10953 // Now that we have our default arguments, check the constructor
10954 // again. It could produce additional diagnostics or affect whether
10955 // the class has implicitly-declared destructors, among other
10956 // things.
10957 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method))
10958 CheckConstructor(Constructor);
10959
10960 // Check the default arguments, which we may have added.
10961 if (!Method->isInvalidDecl())
10962 CheckCXXDefaultArguments(FD: Method);
10963}
10964
10965// Emit the given diagnostic for each non-address-space qualifier.
10966// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10967static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10968 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10969 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10970 bool DiagOccured = false;
10971 FTI.MethodQualifiers->forEachQualifier(
10972 Handle: [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10973 SourceLocation SL) {
10974 // This diagnostic should be emitted on any qualifier except an addr
10975 // space qualifier. However, forEachQualifier currently doesn't visit
10976 // addr space qualifiers, so there's no way to write this condition
10977 // right now; we just diagnose on everything.
10978 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10979 DiagOccured = true;
10980 });
10981 if (DiagOccured)
10982 D.setInvalidType();
10983 }
10984}
10985
10986static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,
10987 unsigned Kind) {
10988 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
10989 return;
10990
10991 DeclaratorChunk &Chunk = D.getTypeObject(i: D.getNumTypeObjects() - 1);
10992 if (Chunk.Kind == DeclaratorChunk::Paren ||
10993 Chunk.Kind == DeclaratorChunk::Function)
10994 return;
10995
10996 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
10997 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
10998 << Kind << Chunk.getSourceRange();
10999 D.setInvalidType();
11000}
11001
11002QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
11003 StorageClass &SC) {
11004 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11005
11006 // C++ [class.ctor]p3:
11007 // A constructor shall not be virtual (10.3) or static (9.4). A
11008 // constructor can be invoked for a const, volatile or const
11009 // volatile object. A constructor shall not be declared const,
11010 // volatile, or const volatile (9.3.2).
11011 if (isVirtual) {
11012 if (!D.isInvalidType())
11013 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11014 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11015 << SourceRange(D.getIdentifierLoc());
11016 D.setInvalidType();
11017 }
11018 if (SC == SC_Static) {
11019 if (!D.isInvalidType())
11020 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11021 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11022 << SourceRange(D.getIdentifierLoc());
11023 D.setInvalidType();
11024 SC = SC_None;
11025 }
11026
11027 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11028 diagnoseIgnoredQualifiers(
11029 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11030 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
11031 D.getDeclSpec().getRestrictSpecLoc(),
11032 D.getDeclSpec().getAtomicSpecLoc());
11033 D.setInvalidType();
11034 }
11035
11036 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11037 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*constructor*/ Kind: 0);
11038
11039 // C++0x [class.ctor]p4:
11040 // A constructor shall not be declared with a ref-qualifier.
11041 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11042 if (FTI.hasRefQualifier()) {
11043 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11044 << FTI.RefQualifierIsLValueRef
11045 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
11046 D.setInvalidType();
11047 }
11048
11049 // Rebuild the function type "R" without any type qualifiers (in
11050 // case any of the errors above fired) and with "void" as the
11051 // return type, since constructors don't have return types.
11052 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11053 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11054 return R;
11055
11056 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11057 EPI.TypeQuals = Qualifiers();
11058 EPI.RefQualifier = RQ_None;
11059
11060 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: Proto->getParamTypes(), EPI);
11061}
11062
11063void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
11064 CXXRecordDecl *ClassDecl
11065 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11066 if (!ClassDecl)
11067 return Constructor->setInvalidDecl();
11068
11069 // C++ [class.copy]p3:
11070 // A declaration of a constructor for a class X is ill-formed if
11071 // its first parameter is of type (optionally cv-qualified) X and
11072 // either there are no other parameters or else all other
11073 // parameters have default arguments.
11074 if (!Constructor->isInvalidDecl() &&
11075 Constructor->hasOneParamOrDefaultArgs() &&
11076 !Constructor->isFunctionTemplateSpecialization()) {
11077 QualType ParamType = Constructor->getParamDecl(0)->getType();
11078 QualType ClassTy = Context.getTagDeclType(ClassDecl);
11079 if (Context.getCanonicalType(T: ParamType).getUnqualifiedType() == ClassTy) {
11080 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11081 const char *ConstRef
11082 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11083 : " const &";
11084 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11085 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11086
11087 // FIXME: Rather that making the constructor invalid, we should endeavor
11088 // to fix the type.
11089 Constructor->setInvalidDecl();
11090 }
11091 }
11092}
11093
11094bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
11095 CXXRecordDecl *RD = Destructor->getParent();
11096
11097 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11098 SourceLocation Loc;
11099
11100 if (!Destructor->isImplicit())
11101 Loc = Destructor->getLocation();
11102 else
11103 Loc = RD->getLocation();
11104
11105 // If we have a virtual destructor, look up the deallocation function
11106 if (FunctionDecl *OperatorDelete =
11107 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD)) {
11108 Expr *ThisArg = nullptr;
11109
11110 // If the notional 'delete this' expression requires a non-trivial
11111 // conversion from 'this' to the type of a destroying operator delete's
11112 // first parameter, perform that conversion now.
11113 if (OperatorDelete->isDestroyingOperatorDelete()) {
11114 unsigned AddressParamIndex = 0;
11115 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11116 ++AddressParamIndex;
11117 QualType ParamType =
11118 OperatorDelete->getParamDecl(i: AddressParamIndex)->getType();
11119 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11120 // C++ [class.dtor]p13:
11121 // ... as if for the expression 'delete this' appearing in a
11122 // non-virtual destructor of the destructor's class.
11123 ContextRAII SwitchContext(*this, Destructor);
11124 ExprResult This = ActOnCXXThis(
11125 Loc: OperatorDelete->getParamDecl(i: AddressParamIndex)->getLocation());
11126 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11127 This = PerformImplicitConversion(From: This.get(), ToType: ParamType,
11128 Action: AssignmentAction::Passing);
11129 if (This.isInvalid()) {
11130 // FIXME: Register this as a context note so that it comes out
11131 // in the right order.
11132 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11133 return true;
11134 }
11135 ThisArg = This.get();
11136 }
11137 }
11138
11139 DiagnoseUseOfDecl(OperatorDelete, Loc);
11140 MarkFunctionReferenced(Loc, Func: OperatorDelete);
11141 Destructor->setOperatorDelete(OD: OperatorDelete, ThisArg);
11142 }
11143 }
11144
11145 return false;
11146}
11147
11148QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11149 StorageClass& SC) {
11150 // C++ [class.dtor]p1:
11151 // [...] A typedef-name that names a class is a class-name
11152 // (7.1.3); however, a typedef-name that names a class shall not
11153 // be used as the identifier in the declarator for a destructor
11154 // declaration.
11155 QualType DeclaratorType = GetTypeFromParser(Ty: D.getName().DestructorName);
11156 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11157 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11158 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11159 else if (const TemplateSpecializationType *TST =
11160 DeclaratorType->getAs<TemplateSpecializationType>())
11161 if (TST->isTypeAlias())
11162 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11163 << DeclaratorType << 1;
11164
11165 // C++ [class.dtor]p2:
11166 // A destructor is used to destroy objects of its class type. A
11167 // destructor takes no parameters, and no return type can be
11168 // specified for it (not even void). The address of a destructor
11169 // shall not be taken. A destructor shall not be static. A
11170 // destructor can be invoked for a const, volatile or const
11171 // volatile object. A destructor shall not be declared const,
11172 // volatile or const volatile (9.3.2).
11173 if (SC == SC_Static) {
11174 if (!D.isInvalidType())
11175 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11176 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11177 << SourceRange(D.getIdentifierLoc())
11178 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
11179
11180 SC = SC_None;
11181 }
11182 if (!D.isInvalidType()) {
11183 // Destructors don't have return types, but the parser will
11184 // happily parse something like:
11185 //
11186 // class X {
11187 // float ~X();
11188 // };
11189 //
11190 // The return type will be eliminated later.
11191 if (D.getDeclSpec().hasTypeSpecifier())
11192 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11193 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11194 << SourceRange(D.getIdentifierLoc());
11195 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11196 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11197 SourceLocation(),
11198 D.getDeclSpec().getConstSpecLoc(),
11199 D.getDeclSpec().getVolatileSpecLoc(),
11200 D.getDeclSpec().getRestrictSpecLoc(),
11201 D.getDeclSpec().getAtomicSpecLoc());
11202 D.setInvalidType();
11203 }
11204 }
11205
11206 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11207 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*destructor*/ Kind: 1);
11208
11209 // C++0x [class.dtor]p2:
11210 // A destructor shall not be declared with a ref-qualifier.
11211 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11212 if (FTI.hasRefQualifier()) {
11213 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11214 << FTI.RefQualifierIsLValueRef
11215 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
11216 D.setInvalidType();
11217 }
11218
11219 // Make sure we don't have any parameters.
11220 if (FTIHasNonVoidParameters(FTI)) {
11221 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11222
11223 // Delete the parameters.
11224 FTI.freeParams();
11225 D.setInvalidType();
11226 }
11227
11228 // Make sure the destructor isn't variadic.
11229 if (FTI.isVariadic) {
11230 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11231 D.setInvalidType();
11232 }
11233
11234 // Rebuild the function type "R" without any type qualifiers or
11235 // parameters (in case any of the errors above fired) and with
11236 // "void" as the return type, since destructors don't have return
11237 // types.
11238 if (!D.isInvalidType())
11239 return R;
11240
11241 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11242 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11243 EPI.Variadic = false;
11244 EPI.TypeQuals = Qualifiers();
11245 EPI.RefQualifier = RQ_None;
11246 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI);
11247}
11248
11249static void extendLeft(SourceRange &R, SourceRange Before) {
11250 if (Before.isInvalid())
11251 return;
11252 R.setBegin(Before.getBegin());
11253 if (R.getEnd().isInvalid())
11254 R.setEnd(Before.getEnd());
11255}
11256
11257static void extendRight(SourceRange &R, SourceRange After) {
11258 if (After.isInvalid())
11259 return;
11260 if (R.getBegin().isInvalid())
11261 R.setBegin(After.getBegin());
11262 R.setEnd(After.getEnd());
11263}
11264
11265void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11266 StorageClass& SC) {
11267 // C++ [class.conv.fct]p1:
11268 // Neither parameter types nor return type can be specified. The
11269 // type of a conversion function (8.3.5) is "function taking no
11270 // parameter returning conversion-type-id."
11271 if (SC == SC_Static) {
11272 if (!D.isInvalidType())
11273 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11274 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11275 << D.getName().getSourceRange();
11276 D.setInvalidType();
11277 SC = SC_None;
11278 }
11279
11280 TypeSourceInfo *ConvTSI = nullptr;
11281 QualType ConvType =
11282 GetTypeFromParser(Ty: D.getName().ConversionFunctionId, TInfo: &ConvTSI);
11283
11284 const DeclSpec &DS = D.getDeclSpec();
11285 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11286 // Conversion functions don't have return types, but the parser will
11287 // happily parse something like:
11288 //
11289 // class X {
11290 // float operator bool();
11291 // };
11292 //
11293 // The return type will be changed later anyway.
11294 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11295 << SourceRange(DS.getTypeSpecTypeLoc())
11296 << SourceRange(D.getIdentifierLoc());
11297 D.setInvalidType();
11298 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11299 // It's also plausible that the user writes type qualifiers in the wrong
11300 // place, such as:
11301 // struct S { const operator int(); };
11302 // FIXME: we could provide a fixit to move the qualifiers onto the
11303 // conversion type.
11304 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11305 << SourceRange(D.getIdentifierLoc()) << 0;
11306 D.setInvalidType();
11307 }
11308 const auto *Proto = R->castAs<FunctionProtoType>();
11309 // Make sure we don't have any parameters.
11310 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11311 unsigned NumParam = Proto->getNumParams();
11312
11313 // [C++2b]
11314 // A conversion function shall have no non-object parameters.
11315 if (NumParam == 1) {
11316 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11317 if (const auto *First =
11318 dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param);
11319 First && First->isExplicitObjectParameter())
11320 NumParam--;
11321 }
11322
11323 if (NumParam != 0) {
11324 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11325 // Delete the parameters.
11326 FTI.freeParams();
11327 D.setInvalidType();
11328 } else if (Proto->isVariadic()) {
11329 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11330 D.setInvalidType();
11331 }
11332
11333 // Diagnose "&operator bool()" and other such nonsense. This
11334 // is actually a gcc extension which we don't support.
11335 if (Proto->getReturnType() != ConvType) {
11336 bool NeedsTypedef = false;
11337 SourceRange Before, After;
11338
11339 // Walk the chunks and extract information on them for our diagnostic.
11340 bool PastFunctionChunk = false;
11341 for (auto &Chunk : D.type_objects()) {
11342 switch (Chunk.Kind) {
11343 case DeclaratorChunk::Function:
11344 if (!PastFunctionChunk) {
11345 if (Chunk.Fun.HasTrailingReturnType) {
11346 TypeSourceInfo *TRT = nullptr;
11347 GetTypeFromParser(Ty: Chunk.Fun.getTrailingReturnType(), TInfo: &TRT);
11348 if (TRT) extendRight(R&: After, After: TRT->getTypeLoc().getSourceRange());
11349 }
11350 PastFunctionChunk = true;
11351 break;
11352 }
11353 [[fallthrough]];
11354 case DeclaratorChunk::Array:
11355 NeedsTypedef = true;
11356 extendRight(R&: After, After: Chunk.getSourceRange());
11357 break;
11358
11359 case DeclaratorChunk::Pointer:
11360 case DeclaratorChunk::BlockPointer:
11361 case DeclaratorChunk::Reference:
11362 case DeclaratorChunk::MemberPointer:
11363 case DeclaratorChunk::Pipe:
11364 extendLeft(R&: Before, Before: Chunk.getSourceRange());
11365 break;
11366
11367 case DeclaratorChunk::Paren:
11368 extendLeft(R&: Before, Before: Chunk.Loc);
11369 extendRight(R&: After, After: Chunk.EndLoc);
11370 break;
11371 }
11372 }
11373
11374 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11375 After.isValid() ? After.getBegin() :
11376 D.getIdentifierLoc();
11377 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11378 DB << Before << After;
11379
11380 if (!NeedsTypedef) {
11381 DB << /*don't need a typedef*/0;
11382
11383 // If we can provide a correct fix-it hint, do so.
11384 if (After.isInvalid() && ConvTSI) {
11385 SourceLocation InsertLoc =
11386 getLocForEndOfToken(Loc: ConvTSI->getTypeLoc().getEndLoc());
11387 DB << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " ")
11388 << FixItHint::CreateInsertionFromRange(
11389 InsertionLoc: InsertLoc, FromRange: CharSourceRange::getTokenRange(R: Before))
11390 << FixItHint::CreateRemoval(RemoveRange: Before);
11391 }
11392 } else if (!Proto->getReturnType()->isDependentType()) {
11393 DB << /*typedef*/1 << Proto->getReturnType();
11394 } else if (getLangOpts().CPlusPlus11) {
11395 DB << /*alias template*/2 << Proto->getReturnType();
11396 } else {
11397 DB << /*might not be fixable*/3;
11398 }
11399
11400 // Recover by incorporating the other type chunks into the result type.
11401 // Note, this does *not* change the name of the function. This is compatible
11402 // with the GCC extension:
11403 // struct S { &operator int(); } s;
11404 // int &r = s.operator int(); // ok in GCC
11405 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11406 ConvType = Proto->getReturnType();
11407 }
11408
11409 // C++ [class.conv.fct]p4:
11410 // The conversion-type-id shall not represent a function type nor
11411 // an array type.
11412 if (ConvType->isArrayType()) {
11413 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11414 ConvType = Context.getPointerType(T: ConvType);
11415 D.setInvalidType();
11416 } else if (ConvType->isFunctionType()) {
11417 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11418 ConvType = Context.getPointerType(T: ConvType);
11419 D.setInvalidType();
11420 }
11421
11422 // Rebuild the function type "R" without any parameters (in case any
11423 // of the errors above fired) and with the conversion type as the
11424 // return type.
11425 if (D.isInvalidType())
11426 R = Context.getFunctionType(ResultTy: ConvType, Args: {}, EPI: Proto->getExtProtoInfo());
11427
11428 // C++0x explicit conversion operators.
11429 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11430 Diag(DS.getExplicitSpecLoc(),
11431 getLangOpts().CPlusPlus11
11432 ? diag::warn_cxx98_compat_explicit_conversion_functions
11433 : diag::ext_explicit_conversion_functions)
11434 << SourceRange(DS.getExplicitSpecRange());
11435}
11436
11437Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11438 assert(Conversion && "Expected to receive a conversion function declaration");
11439
11440 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11441
11442 // Make sure we aren't redeclaring the conversion function.
11443 QualType ConvType = Context.getCanonicalType(T: Conversion->getConversionType());
11444 // C++ [class.conv.fct]p1:
11445 // [...] A conversion function is never used to convert a
11446 // (possibly cv-qualified) object to the (possibly cv-qualified)
11447 // same object type (or a reference to it), to a (possibly
11448 // cv-qualified) base class of that type (or a reference to it),
11449 // or to (possibly cv-qualified) void.
11450 QualType ClassType
11451 = Context.getCanonicalType(T: Context.getTypeDeclType(ClassDecl));
11452 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11453 ConvType = ConvTypeRef->getPointeeType();
11454 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11455 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11456 /* Suppress diagnostics for instantiations. */;
11457 else if (Conversion->size_overridden_methods() != 0)
11458 /* Suppress diagnostics for overriding virtual function in a base class. */;
11459 else if (ConvType->isRecordType()) {
11460 ConvType = Context.getCanonicalType(T: ConvType).getUnqualifiedType();
11461 if (ConvType == ClassType)
11462 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11463 << ClassType;
11464 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11465 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11466 << ClassType << ConvType;
11467 } else if (ConvType->isVoidType()) {
11468 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11469 << ClassType << ConvType;
11470 }
11471
11472 if (FunctionTemplateDecl *ConversionTemplate =
11473 Conversion->getDescribedFunctionTemplate()) {
11474 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11475 ConvType = ConvTypePtr->getPointeeType();
11476 }
11477 if (ConvType->isUndeducedAutoType()) {
11478 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11479 << getReturnTypeLoc(Conversion).getSourceRange()
11480 << ConvType->castAs<AutoType>()->getKeyword()
11481 << /* in declaration of conversion function template= */ 24;
11482 }
11483
11484 return ConversionTemplate;
11485 }
11486
11487 return Conversion;
11488}
11489
11490void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11491 DeclarationName Name, QualType R) {
11492 CheckExplicitObjectMemberFunction(D, Name, R, IsLambda: false, DC);
11493}
11494
11495void Sema::CheckExplicitObjectLambda(Declarator &D) {
11496 CheckExplicitObjectMemberFunction(D, Name: {}, R: {}, IsLambda: true);
11497}
11498
11499void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11500 DeclarationName Name, QualType R,
11501 bool IsLambda, DeclContext *DC) {
11502 if (!D.isFunctionDeclarator())
11503 return;
11504
11505 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11506 if (FTI.NumParams == 0)
11507 return;
11508 ParmVarDecl *ExplicitObjectParam = nullptr;
11509 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11510 const auto &ParamInfo = FTI.Params[Idx];
11511 if (!ParamInfo.Param)
11512 continue;
11513 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamInfo.Param);
11514 if (!Param->isExplicitObjectParameter())
11515 continue;
11516 if (Idx == 0) {
11517 ExplicitObjectParam = Param;
11518 continue;
11519 } else {
11520 Diag(Param->getLocation(),
11521 diag::err_explicit_object_parameter_must_be_first)
11522 << IsLambda << Param->getSourceRange();
11523 }
11524 }
11525 if (!ExplicitObjectParam)
11526 return;
11527
11528 if (ExplicitObjectParam->hasDefaultArg()) {
11529 Diag(ExplicitObjectParam->getLocation(),
11530 diag::err_explicit_object_default_arg)
11531 << ExplicitObjectParam->getSourceRange();
11532 }
11533
11534 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11535 (D.getContext() == clang::DeclaratorContext::Member &&
11536 D.isStaticMember())) {
11537 Diag(ExplicitObjectParam->getBeginLoc(),
11538 diag::err_explicit_object_parameter_nonmember)
11539 << D.getSourceRange() << /*static=*/0 << IsLambda;
11540 D.setInvalidType();
11541 }
11542
11543 if (D.getDeclSpec().isVirtualSpecified()) {
11544 Diag(ExplicitObjectParam->getBeginLoc(),
11545 diag::err_explicit_object_parameter_nonmember)
11546 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11547 D.setInvalidType();
11548 }
11549
11550 // Friend declarations require some care. Consider:
11551 //
11552 // namespace N {
11553 // struct A{};
11554 // int f(A);
11555 // }
11556 //
11557 // struct S {
11558 // struct T {
11559 // int f(this T);
11560 // };
11561 //
11562 // friend int T::f(this T); // Allow this.
11563 // friend int f(this S); // But disallow this.
11564 // friend int N::f(this A); // And disallow this.
11565 // };
11566 //
11567 // Here, it seems to suffice to check whether the scope
11568 // specifier designates a class type.
11569 if (D.getDeclSpec().isFriendSpecified() &&
11570 !isa_and_present<CXXRecordDecl>(
11571 Val: computeDeclContext(SS: D.getCXXScopeSpec()))) {
11572 Diag(ExplicitObjectParam->getBeginLoc(),
11573 diag::err_explicit_object_parameter_nonmember)
11574 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11575 D.setInvalidType();
11576 }
11577
11578 if (IsLambda && FTI.hasMutableQualifier()) {
11579 Diag(ExplicitObjectParam->getBeginLoc(),
11580 diag::err_explicit_object_parameter_mutable)
11581 << D.getSourceRange();
11582 }
11583
11584 if (IsLambda)
11585 return;
11586
11587 if (!DC || !DC->isRecord()) {
11588 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11589 "should have been diagnosed already");
11590 return;
11591 }
11592
11593 // CWG2674: constructors and destructors cannot have explicit parameters.
11594 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11595 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11596 Diag(ExplicitObjectParam->getBeginLoc(),
11597 diag::err_explicit_object_parameter_constructor)
11598 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11599 << D.getSourceRange();
11600 D.setInvalidType();
11601 }
11602}
11603
11604namespace {
11605/// Utility class to accumulate and print a diagnostic listing the invalid
11606/// specifier(s) on a declaration.
11607struct BadSpecifierDiagnoser {
11608 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11609 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11610 ~BadSpecifierDiagnoser() {
11611 Diagnostic << Specifiers;
11612 }
11613
11614 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11615 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11616 }
11617 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11618 return check(SpecLoc,
11619 Spec: DeclSpec::getSpecifierName(T: Spec, Policy: S.getPrintingPolicy()));
11620 }
11621 void check(SourceLocation SpecLoc, const char *Spec) {
11622 if (SpecLoc.isInvalid()) return;
11623 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11624 if (!Specifiers.empty()) Specifiers += " ";
11625 Specifiers += Spec;
11626 }
11627
11628 Sema &S;
11629 Sema::SemaDiagnosticBuilder Diagnostic;
11630 std::string Specifiers;
11631};
11632}
11633
11634bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11635 StorageClass &SC) {
11636 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11637 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11638 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11639
11640 // C++ [temp.deduct.guide]p3:
11641 // A deduction-gide shall be declared in the same scope as the
11642 // corresponding class template.
11643 if (!CurContext->getRedeclContext()->Equals(
11644 DC: GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11645 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11646 << GuidedTemplateDecl;
11647 NoteTemplateLocation(*GuidedTemplateDecl);
11648 }
11649
11650 auto &DS = D.getMutableDeclSpec();
11651 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11652 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11653 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11654 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11655 BadSpecifierDiagnoser Diagnoser(
11656 *this, D.getIdentifierLoc(),
11657 diag::err_deduction_guide_invalid_specifier);
11658
11659 Diagnoser.check(SpecLoc: DS.getStorageClassSpecLoc(), Spec: DS.getStorageClassSpec());
11660 DS.ClearStorageClassSpecs();
11661 SC = SC_None;
11662
11663 // 'explicit' is permitted.
11664 Diagnoser.check(SpecLoc: DS.getInlineSpecLoc(), Spec: "inline");
11665 Diagnoser.check(SpecLoc: DS.getNoreturnSpecLoc(), Spec: "_Noreturn");
11666 Diagnoser.check(SpecLoc: DS.getConstexprSpecLoc(), Spec: "constexpr");
11667 DS.ClearConstexprSpec();
11668
11669 Diagnoser.check(SpecLoc: DS.getConstSpecLoc(), Spec: "const");
11670 Diagnoser.check(SpecLoc: DS.getRestrictSpecLoc(), Spec: "__restrict");
11671 Diagnoser.check(SpecLoc: DS.getVolatileSpecLoc(), Spec: "volatile");
11672 Diagnoser.check(SpecLoc: DS.getAtomicSpecLoc(), Spec: "_Atomic");
11673 Diagnoser.check(SpecLoc: DS.getUnalignedSpecLoc(), Spec: "__unaligned");
11674 DS.ClearTypeQualifiers();
11675
11676 Diagnoser.check(SpecLoc: DS.getTypeSpecComplexLoc(), Spec: DS.getTypeSpecComplex());
11677 Diagnoser.check(SpecLoc: DS.getTypeSpecSignLoc(), Spec: DS.getTypeSpecSign());
11678 Diagnoser.check(SpecLoc: DS.getTypeSpecWidthLoc(), Spec: DS.getTypeSpecWidth());
11679 Diagnoser.check(SpecLoc: DS.getTypeSpecTypeLoc(), Spec: DS.getTypeSpecType());
11680 DS.ClearTypeSpecType();
11681 }
11682
11683 if (D.isInvalidType())
11684 return true;
11685
11686 // Check the declarator is simple enough.
11687 bool FoundFunction = false;
11688 for (const DeclaratorChunk &Chunk : llvm::reverse(C: D.type_objects())) {
11689 if (Chunk.Kind == DeclaratorChunk::Paren)
11690 continue;
11691 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11692 Diag(D.getDeclSpec().getBeginLoc(),
11693 diag::err_deduction_guide_with_complex_decl)
11694 << D.getSourceRange();
11695 break;
11696 }
11697 if (!Chunk.Fun.hasTrailingReturnType())
11698 return Diag(D.getName().getBeginLoc(),
11699 diag::err_deduction_guide_no_trailing_return_type);
11700
11701 // Check that the return type is written as a specialization of
11702 // the template specified as the deduction-guide's name.
11703 // The template name may not be qualified. [temp.deduct.guide]
11704 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11705 TypeSourceInfo *TSI = nullptr;
11706 QualType RetTy = GetTypeFromParser(Ty: TrailingReturnType, TInfo: &TSI);
11707 assert(TSI && "deduction guide has valid type but invalid return type?");
11708 bool AcceptableReturnType = false;
11709 bool MightInstantiateToSpecialization = false;
11710 if (auto RetTST =
11711 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11712 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11713 bool TemplateMatches = Context.hasSameTemplateName(
11714 X: SpecifiedName, Y: GuidedTemplate, /*IgnoreDeduced=*/true);
11715
11716 const QualifiedTemplateName *Qualifiers =
11717 SpecifiedName.getAsQualifiedTemplateName();
11718 assert(Qualifiers && "expected QualifiedTemplate");
11719 bool SimplyWritten = !Qualifiers->hasTemplateKeyword() &&
11720 Qualifiers->getQualifier() == nullptr;
11721 if (SimplyWritten && TemplateMatches)
11722 AcceptableReturnType = true;
11723 else {
11724 // This could still instantiate to the right type, unless we know it
11725 // names the wrong class template.
11726 auto *TD = SpecifiedName.getAsTemplateDecl();
11727 MightInstantiateToSpecialization =
11728 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11729 }
11730 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11731 MightInstantiateToSpecialization = true;
11732 }
11733
11734 if (!AcceptableReturnType)
11735 return Diag(TSI->getTypeLoc().getBeginLoc(),
11736 diag::err_deduction_guide_bad_trailing_return_type)
11737 << GuidedTemplate << TSI->getType()
11738 << MightInstantiateToSpecialization
11739 << TSI->getTypeLoc().getSourceRange();
11740
11741 // Keep going to check that we don't have any inner declarator pieces (we
11742 // could still have a function returning a pointer to a function).
11743 FoundFunction = true;
11744 }
11745
11746 if (D.isFunctionDefinition())
11747 // we can still create a valid deduction guide here.
11748 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11749 return false;
11750}
11751
11752//===----------------------------------------------------------------------===//
11753// Namespace Handling
11754//===----------------------------------------------------------------------===//
11755
11756/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11757/// reopened.
11758static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11759 SourceLocation Loc,
11760 IdentifierInfo *II, bool *IsInline,
11761 NamespaceDecl *PrevNS) {
11762 assert(*IsInline != PrevNS->isInline());
11763
11764 // 'inline' must appear on the original definition, but not necessarily
11765 // on all extension definitions, so the note should point to the first
11766 // definition to avoid confusion.
11767 PrevNS = PrevNS->getFirstDecl();
11768
11769 if (PrevNS->isInline())
11770 // The user probably just forgot the 'inline', so suggest that it
11771 // be added back.
11772 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11773 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11774 else
11775 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11776
11777 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11778 *IsInline = PrevNS->isInline();
11779}
11780
11781/// ActOnStartNamespaceDef - This is called at the start of a namespace
11782/// definition.
11783Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11784 SourceLocation InlineLoc,
11785 SourceLocation NamespaceLoc,
11786 SourceLocation IdentLoc, IdentifierInfo *II,
11787 SourceLocation LBrace,
11788 const ParsedAttributesView &AttrList,
11789 UsingDirectiveDecl *&UD, bool IsNested) {
11790 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11791 // For anonymous namespace, take the location of the left brace.
11792 SourceLocation Loc = II ? IdentLoc : LBrace;
11793 bool IsInline = InlineLoc.isValid();
11794 bool IsInvalid = false;
11795 bool IsStd = false;
11796 bool AddToKnown = false;
11797 Scope *DeclRegionScope = NamespcScope->getParent();
11798
11799 NamespaceDecl *PrevNS = nullptr;
11800 if (II) {
11801 // C++ [namespace.std]p7:
11802 // A translation unit shall not declare namespace std to be an inline
11803 // namespace (9.8.2).
11804 //
11805 // Precondition: the std namespace is in the file scope and is declared to
11806 // be inline
11807 auto DiagnoseInlineStdNS = [&]() {
11808 assert(IsInline && II->isStr("std") &&
11809 CurContext->getRedeclContext()->isTranslationUnit() &&
11810 "Precondition of DiagnoseInlineStdNS not met");
11811 Diag(InlineLoc, diag::err_inline_namespace_std)
11812 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11813 IsInline = false;
11814 };
11815 // C++ [namespace.def]p2:
11816 // The identifier in an original-namespace-definition shall not
11817 // have been previously defined in the declarative region in
11818 // which the original-namespace-definition appears. The
11819 // identifier in an original-namespace-definition is the name of
11820 // the namespace. Subsequently in that declarative region, it is
11821 // treated as an original-namespace-name.
11822 //
11823 // Since namespace names are unique in their scope, and we don't
11824 // look through using directives, just look for any ordinary names
11825 // as if by qualified name lookup.
11826 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11827 RedeclarationKind::ForExternalRedeclaration);
11828 LookupQualifiedName(R, LookupCtx: CurContext->getRedeclContext());
11829 NamedDecl *PrevDecl =
11830 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11831 PrevNS = dyn_cast_or_null<NamespaceDecl>(Val: PrevDecl);
11832
11833 if (PrevNS) {
11834 // This is an extended namespace definition.
11835 if (IsInline && II->isStr(Str: "std") &&
11836 CurContext->getRedeclContext()->isTranslationUnit())
11837 DiagnoseInlineStdNS();
11838 else if (IsInline != PrevNS->isInline())
11839 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc, II,
11840 IsInline: &IsInline, PrevNS);
11841 } else if (PrevDecl) {
11842 // This is an invalid name redefinition.
11843 Diag(Loc, diag::err_redefinition_different_kind)
11844 << II;
11845 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11846 IsInvalid = true;
11847 // Continue on to push Namespc as current DeclContext and return it.
11848 } else if (II->isStr(Str: "std") &&
11849 CurContext->getRedeclContext()->isTranslationUnit()) {
11850 if (IsInline)
11851 DiagnoseInlineStdNS();
11852 // This is the first "real" definition of the namespace "std", so update
11853 // our cache of the "std" namespace to point at this definition.
11854 PrevNS = getStdNamespace();
11855 IsStd = true;
11856 AddToKnown = !IsInline;
11857 } else {
11858 // We've seen this namespace for the first time.
11859 AddToKnown = !IsInline;
11860 }
11861 } else {
11862 // Anonymous namespaces.
11863
11864 // Determine whether the parent already has an anonymous namespace.
11865 DeclContext *Parent = CurContext->getRedeclContext();
11866 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
11867 PrevNS = TU->getAnonymousNamespace();
11868 } else {
11869 NamespaceDecl *ND = cast<NamespaceDecl>(Val: Parent);
11870 PrevNS = ND->getAnonymousNamespace();
11871 }
11872
11873 if (PrevNS && IsInline != PrevNS->isInline())
11874 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc: NamespaceLoc, II,
11875 IsInline: &IsInline, PrevNS);
11876 }
11877
11878 NamespaceDecl *Namespc = NamespaceDecl::Create(
11879 C&: Context, DC: CurContext, Inline: IsInline, StartLoc, IdLoc: Loc, Id: II, PrevDecl: PrevNS, Nested: IsNested);
11880 if (IsInvalid)
11881 Namespc->setInvalidDecl();
11882
11883 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11884 AddPragmaAttributes(DeclRegionScope, Namespc);
11885 ProcessAPINotes(Namespc);
11886
11887 // FIXME: Should we be merging attributes?
11888 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11889 PushNamespaceVisibilityAttr(Attr, Loc);
11890
11891 if (IsStd)
11892 StdNamespace = Namespc;
11893 if (AddToKnown)
11894 KnownNamespaces[Namespc] = false;
11895
11896 if (II) {
11897 PushOnScopeChains(Namespc, DeclRegionScope);
11898 } else {
11899 // Link the anonymous namespace into its parent.
11900 DeclContext *Parent = CurContext->getRedeclContext();
11901 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
11902 TU->setAnonymousNamespace(Namespc);
11903 } else {
11904 cast<NamespaceDecl>(Val: Parent)->setAnonymousNamespace(Namespc);
11905 }
11906
11907 CurContext->addDecl(Namespc);
11908
11909 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11910 // behaves as if it were replaced by
11911 // namespace unique { /* empty body */ }
11912 // using namespace unique;
11913 // namespace unique { namespace-body }
11914 // where all occurrences of 'unique' in a translation unit are
11915 // replaced by the same identifier and this identifier differs
11916 // from all other identifiers in the entire program.
11917
11918 // We just create the namespace with an empty name and then add an
11919 // implicit using declaration, just like the standard suggests.
11920 //
11921 // CodeGen enforces the "universally unique" aspect by giving all
11922 // declarations semantically contained within an anonymous
11923 // namespace internal linkage.
11924
11925 if (!PrevNS) {
11926 UD = UsingDirectiveDecl::Create(Context, Parent,
11927 /* 'using' */ LBrace,
11928 /* 'namespace' */ SourceLocation(),
11929 /* qualifier */ NestedNameSpecifierLoc(),
11930 /* identifier */ SourceLocation(),
11931 Namespc,
11932 /* Ancestor */ Parent);
11933 UD->setImplicit();
11934 Parent->addDecl(UD);
11935 }
11936 }
11937
11938 ActOnDocumentableDecl(Namespc);
11939
11940 // Although we could have an invalid decl (i.e. the namespace name is a
11941 // redefinition), push it as current DeclContext and try to continue parsing.
11942 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11943 // for the namespace has the declarations that showed up in that particular
11944 // namespace definition.
11945 PushDeclContext(NamespcScope, Namespc);
11946 return Namespc;
11947}
11948
11949/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11950/// is a namespace alias, returns the namespace it points to.
11951static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11952 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(Val: D))
11953 return AD->getNamespace();
11954 return dyn_cast_or_null<NamespaceDecl>(Val: D);
11955}
11956
11957void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11958 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Val: Dcl);
11959 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11960 Namespc->setRBraceLoc(RBrace);
11961 PopDeclContext();
11962 if (Namespc->hasAttr<VisibilityAttr>())
11963 PopPragmaVisibility(IsNamespaceEnd: true, EndLoc: RBrace);
11964 // If this namespace contains an export-declaration, export it now.
11965 if (DeferredExportedNamespaces.erase(Ptr: Namespc))
11966 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11967}
11968
11969CXXRecordDecl *Sema::getStdBadAlloc() const {
11970 return cast_or_null<CXXRecordDecl>(
11971 Val: StdBadAlloc.get(Source: Context.getExternalSource()));
11972}
11973
11974EnumDecl *Sema::getStdAlignValT() const {
11975 return cast_or_null<EnumDecl>(Val: StdAlignValT.get(Source: Context.getExternalSource()));
11976}
11977
11978NamespaceDecl *Sema::getStdNamespace() const {
11979 return cast_or_null<NamespaceDecl>(
11980 Val: StdNamespace.get(Source: Context.getExternalSource()));
11981}
11982
11983namespace {
11984
11985enum UnsupportedSTLSelect {
11986 USS_InvalidMember,
11987 USS_MissingMember,
11988 USS_NonTrivial,
11989 USS_Other
11990};
11991
11992struct InvalidSTLDiagnoser {
11993 Sema &S;
11994 SourceLocation Loc;
11995 QualType TyForDiags;
11996
11997 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11998 const VarDecl *VD = nullptr) {
11999 {
12000 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
12001 << TyForDiags << ((int)Sel);
12002 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12003 assert(!Name.empty());
12004 D << Name;
12005 }
12006 }
12007 if (Sel == USS_InvalidMember) {
12008 S.Diag(VD->getLocation(), diag::note_var_declared_here)
12009 << VD << VD->getSourceRange();
12010 }
12011 return QualType();
12012 }
12013};
12014} // namespace
12015
12016QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
12017 SourceLocation Loc,
12018 ComparisonCategoryUsage Usage) {
12019 assert(getLangOpts().CPlusPlus &&
12020 "Looking for comparison category type outside of C++.");
12021
12022 // Use an elaborated type for diagnostics which has a name containing the
12023 // prepended 'std' namespace but not any inline namespace names.
12024 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12025 auto *NNS =
12026 NestedNameSpecifier::Create(Context, Prefix: nullptr, NS: getStdNamespace());
12027 return Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS,
12028 NamedType: Info->getType());
12029 };
12030
12031 // Check if we've already successfully checked the comparison category type
12032 // before. If so, skip checking it again.
12033 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12034 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12035 // The only thing we need to check is that the type has a reachable
12036 // definition in the current context.
12037 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12038 return QualType();
12039
12040 return Info->getType();
12041 }
12042
12043 // If lookup failed
12044 if (!Info) {
12045 std::string NameForDiags = "std::";
12046 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12047 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12048 << NameForDiags << (int)Usage;
12049 return QualType();
12050 }
12051
12052 assert(Info->Kind == Kind);
12053 assert(Info->Record);
12054
12055 // Update the Record decl in case we encountered a forward declaration on our
12056 // first pass. FIXME: This is a bit of a hack.
12057 if (Info->Record->hasDefinition())
12058 Info->Record = Info->Record->getDefinition();
12059
12060 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12061 return QualType();
12062
12063 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12064
12065 if (!Info->Record->isTriviallyCopyable())
12066 return UnsupportedSTLError(USS_NonTrivial);
12067
12068 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12069 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12070 // Tolerate empty base classes.
12071 if (Base->isEmpty())
12072 continue;
12073 // Reject STL implementations which have at least one non-empty base.
12074 return UnsupportedSTLError();
12075 }
12076
12077 // Check that the STL has implemented the types using a single integer field.
12078 // This expectation allows better codegen for builtin operators. We require:
12079 // (1) The class has exactly one field.
12080 // (2) The field is an integral or enumeration type.
12081 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12082 if (std::distance(FIt, FEnd) != 1 ||
12083 !FIt->getType()->isIntegralOrEnumerationType()) {
12084 return UnsupportedSTLError();
12085 }
12086
12087 // Build each of the require values and store them in Info.
12088 for (ComparisonCategoryResult CCR :
12089 ComparisonCategories::getPossibleResultsForType(Type: Kind)) {
12090 StringRef MemName = ComparisonCategories::getResultString(Kind: CCR);
12091 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(ValueKind: CCR);
12092
12093 if (!ValInfo)
12094 return UnsupportedSTLError(USS_MissingMember, MemName);
12095
12096 VarDecl *VD = ValInfo->VD;
12097 assert(VD && "should not be null!");
12098
12099 // Attempt to diagnose reasons why the STL definition of this type
12100 // might be foobar, including it failing to be a constant expression.
12101 // TODO Handle more ways the lookup or result can be invalid.
12102 if (!VD->isStaticDataMember() ||
12103 !VD->isUsableInConstantExpressions(C: Context))
12104 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12105
12106 // Attempt to evaluate the var decl as a constant expression and extract
12107 // the value of its first field as a ICE. If this fails, the STL
12108 // implementation is not supported.
12109 if (!ValInfo->hasValidIntValue())
12110 return UnsupportedSTLError();
12111
12112 MarkVariableReferenced(Loc, Var: VD);
12113 }
12114
12115 // We've successfully built the required types and expressions. Update
12116 // the cache and return the newly cached value.
12117 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12118 return Info->getType();
12119}
12120
12121NamespaceDecl *Sema::getOrCreateStdNamespace() {
12122 if (!StdNamespace) {
12123 // The "std" namespace has not yet been defined, so build one implicitly.
12124 StdNamespace = NamespaceDecl::Create(
12125 Context, Context.getTranslationUnitDecl(),
12126 /*Inline=*/false, SourceLocation(), SourceLocation(),
12127 &PP.getIdentifierTable().get(Name: "std"),
12128 /*PrevDecl=*/nullptr, /*Nested=*/false);
12129 getStdNamespace()->setImplicit(true);
12130 // We want the created NamespaceDecl to be available for redeclaration
12131 // lookups, but not for regular name lookups.
12132 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12133 getStdNamespace()->clearIdentifierNamespace();
12134 }
12135
12136 return getStdNamespace();
12137}
12138
12139static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12140 const char *ClassName,
12141 ClassTemplateDecl **CachedDecl,
12142 const Decl **MalformedDecl) {
12143 // We're looking for implicit instantiations of
12144 // template <typename U> class std::{ClassName}.
12145
12146 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12147 // it.
12148 return false;
12149
12150 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12151 if (!MalformedDecl)
12152 return;
12153 if (!D)
12154 D = SugaredType->getAsTagDecl();
12155 if (!D || !D->isInStdNamespace())
12156 return;
12157 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12158 if (II && II == &S.PP.getIdentifierTable().get(Name: ClassName))
12159 *MalformedDecl = D;
12160 };
12161
12162 ClassTemplateDecl *Template = nullptr;
12163 ArrayRef<TemplateArgument> Arguments;
12164 {
12165 const TemplateSpecializationType *TST =
12166 SugaredType->getAsNonAliasTemplateSpecializationType();
12167 if (!TST)
12168 if (const auto *ICN = SugaredType->getAs<InjectedClassNameType>())
12169 TST = ICN->getInjectedTST();
12170 if (TST) {
12171 Template = dyn_cast_or_null<ClassTemplateDecl>(
12172 Val: TST->getTemplateName().getAsTemplateDecl());
12173 Arguments = TST->template_arguments();
12174 } else if (const RecordType *RT = SugaredType->getAs<RecordType>()) {
12175 ClassTemplateSpecializationDecl *Specialization =
12176 dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
12177 if (!Specialization) {
12178 ReportMatchingNameAsMalformed(RT->getDecl());
12179 return false;
12180 }
12181 Template = Specialization->getSpecializedTemplate();
12182 Arguments = Specialization->getTemplateArgs().asArray();
12183 }
12184 }
12185
12186 if (!Template) {
12187 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12188 return false;
12189 }
12190
12191 if (!*CachedDecl) {
12192 // Haven't recognized std::{ClassName} yet, maybe this is it.
12193 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12194 // semantics of this are slightly different, most notably the existing
12195 // "lookup" semantics explicitly diagnose an invalid definition as an
12196 // error.
12197 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12198 if (TemplateClass->getIdentifier() !=
12199 &S.PP.getIdentifierTable().get(Name: ClassName) ||
12200 !S.getStdNamespace()->InEnclosingNamespaceSetOf(
12201 NS: TemplateClass->getNonTransparentDeclContext()))
12202 return false;
12203 // This is a template called std::{ClassName}, but is it the right
12204 // template?
12205 TemplateParameterList *Params = Template->getTemplateParameters();
12206 if (Params->getMinRequiredArguments() != 1 ||
12207 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0)) ||
12208 Params->getParam(Idx: 0)->isTemplateParameterPack()) {
12209 if (MalformedDecl)
12210 *MalformedDecl = TemplateClass;
12211 return false;
12212 }
12213
12214 // It's the right template.
12215 *CachedDecl = Template;
12216 }
12217
12218 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12219 return false;
12220
12221 // This is an instance of std::{ClassName}. Find the argument type.
12222 if (TypeArg) {
12223 QualType ArgType = Arguments[0].getAsType();
12224 // FIXME: Since TST only has as-written arguments, we have to perform the
12225 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12226 // - If an explicitly-specified template argument type is a lifetime type
12227 // with no lifetime qualifier, the __strong lifetime qualifier is
12228 // inferred.
12229 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12230 !ArgType.getObjCLifetime()) {
12231 Qualifiers Qs;
12232 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
12233 ArgType = S.Context.getQualifiedType(T: ArgType, Qs);
12234 }
12235 *TypeArg = ArgType;
12236 }
12237
12238 return true;
12239}
12240
12241bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
12242 assert(getLangOpts().CPlusPlus &&
12243 "Looking for std::initializer_list outside of C++.");
12244
12245 // We're looking for implicit instantiations of
12246 // template <typename E> class std::initializer_list.
12247
12248 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "initializer_list",
12249 CachedDecl: &StdInitializerList, /*MalformedDecl=*/nullptr);
12250}
12251
12252bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,
12253 const Decl **MalformedDecl) {
12254 assert(getLangOpts().CPlusPlus &&
12255 "Looking for std::type_identity outside of C++.");
12256
12257 // We're looking for implicit instantiations of
12258 // template <typename T> struct std::type_identity.
12259
12260 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "type_identity",
12261 CachedDecl: &StdTypeIdentity, MalformedDecl);
12262}
12263
12264static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,
12265 const char *ClassName,
12266 bool *WasMalformed) {
12267 if (!S.StdNamespace)
12268 return nullptr;
12269
12270 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: ClassName), Loc,
12271 Sema::LookupOrdinaryName);
12272 if (!S.LookupQualifiedName(Result, S.getStdNamespace()))
12273 return nullptr;
12274
12275 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12276 if (!Template) {
12277 Result.suppressDiagnostics();
12278 // We found something weird. Complain about the first thing we found.
12279 NamedDecl *Found = *Result.begin();
12280 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
12281 << ClassName;
12282 if (WasMalformed)
12283 *WasMalformed = true;
12284 return nullptr;
12285 }
12286
12287 // We found some template with the correct name. Now verify that it's
12288 // correct.
12289 TemplateParameterList *Params = Template->getTemplateParameters();
12290 if (Params->getMinRequiredArguments() != 1 ||
12291 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
12292 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
12293 << ClassName;
12294 if (WasMalformed)
12295 *WasMalformed = true;
12296 return nullptr;
12297 }
12298
12299 return Template;
12300}
12301
12302static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,
12303 QualType TypeParam, SourceLocation Loc) {
12304 assert(S.getStdNamespace());
12305 TemplateArgumentListInfo Args(Loc, Loc);
12306 auto TSI = S.Context.getTrivialTypeSourceInfo(T: TypeParam, Loc);
12307 Args.addArgument(Loc: TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12308
12309 QualType T = S.CheckTemplateIdType(Template: TemplateName(CTD), TemplateLoc: Loc, TemplateArgs&: Args);
12310 if (T.isNull())
12311 return QualType();
12312
12313 return S.Context.getElaboratedType(
12314 Keyword: ElaboratedTypeKeyword::None,
12315 NNS: NestedNameSpecifier::Create(Context: S.Context, Prefix: nullptr, NS: S.getStdNamespace()), NamedType: T);
12316}
12317
12318QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12319 if (!StdInitializerList) {
12320 bool WasMalformed = false;
12321 StdInitializerList =
12322 LookupStdClassTemplate(S&: *this, Loc, ClassName: "initializer_list", WasMalformed: &WasMalformed);
12323 if (!StdInitializerList) {
12324 if (!WasMalformed)
12325 Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12326 return QualType();
12327 }
12328 }
12329 return BuildStdClassTemplate(S&: *this, CTD: StdInitializerList, TypeParam: Element, Loc);
12330}
12331
12332QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {
12333 if (!StdTypeIdentity) {
12334 StdTypeIdentity = LookupStdClassTemplate(S&: *this, Loc, ClassName: "type_identity",
12335 /*WasMalformed=*/nullptr);
12336 if (!StdTypeIdentity)
12337 return QualType();
12338 }
12339 return BuildStdClassTemplate(S&: *this, CTD: StdTypeIdentity, TypeParam: Type, Loc);
12340}
12341
12342bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12343 // C++ [dcl.init.list]p2:
12344 // A constructor is an initializer-list constructor if its first parameter
12345 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12346 // std::initializer_list<E> for some type E, and either there are no other
12347 // parameters or else all other parameters have default arguments.
12348 if (!Ctor->hasOneParamOrDefaultArgs())
12349 return false;
12350
12351 QualType ArgType = Ctor->getParamDecl(i: 0)->getType();
12352 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12353 ArgType = RT->getPointeeType().getUnqualifiedType();
12354
12355 return isStdInitializerList(Ty: ArgType, Element: nullptr);
12356}
12357
12358/// Determine whether a using statement is in a context where it will be
12359/// apply in all contexts.
12360static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12361 switch (CurContext->getDeclKind()) {
12362 case Decl::TranslationUnit:
12363 return true;
12364 case Decl::LinkageSpec:
12365 return IsUsingDirectiveInToplevelContext(CurContext: CurContext->getParent());
12366 default:
12367 return false;
12368 }
12369}
12370
12371namespace {
12372
12373// Callback to only accept typo corrections that are namespaces.
12374class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12375public:
12376 bool ValidateCandidate(const TypoCorrection &candidate) override {
12377 if (NamedDecl *ND = candidate.getCorrectionDecl())
12378 return isa<NamespaceDecl>(Val: ND) || isa<NamespaceAliasDecl>(Val: ND);
12379 return false;
12380 }
12381
12382 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12383 return std::make_unique<NamespaceValidatorCCC>(args&: *this);
12384 }
12385};
12386
12387}
12388
12389static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12390 Sema &S) {
12391 auto *ND = cast<NamespaceDecl>(Val: Corrected.getFoundDecl());
12392 Module *M = ND->getOwningModule();
12393 assert(M && "hidden namespace definition not in a module?");
12394
12395 if (M->isExplicitGlobalModule())
12396 S.Diag(Corrected.getCorrectionRange().getBegin(),
12397 diag::err_module_unimported_use_header)
12398 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12399 << /*Header Name*/ false;
12400 else
12401 S.Diag(Corrected.getCorrectionRange().getBegin(),
12402 diag::err_module_unimported_use)
12403 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12404 << M->getTopLevelModuleName();
12405}
12406
12407static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12408 CXXScopeSpec &SS,
12409 SourceLocation IdentLoc,
12410 IdentifierInfo *Ident) {
12411 R.clear();
12412 NamespaceValidatorCCC CCC{};
12413 if (TypoCorrection Corrected =
12414 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Sc, SS: &SS, CCC,
12415 Mode: CorrectTypoKind::ErrorRecovery)) {
12416 // Generally we find it is confusing more than helpful to diagnose the
12417 // invisible namespace.
12418 // See https://github.com/llvm/llvm-project/issues/73893.
12419 //
12420 // However, we should diagnose when the users are trying to using an
12421 // invisible namespace. So we handle the case specially here.
12422 if (isa_and_nonnull<NamespaceDecl>(Val: Corrected.getFoundDecl()) &&
12423 Corrected.requiresImport()) {
12424 DiagnoseInvisibleNamespace(Corrected, S);
12425 } else if (DeclContext *DC = S.computeDeclContext(SS, EnteringContext: false)) {
12426 std::string CorrectedStr(Corrected.getAsString(LO: S.getLangOpts()));
12427 bool DroppedSpecifier =
12428 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12429 S.diagnoseTypo(Corrected,
12430 S.PDiag(diag::err_using_directive_member_suggest)
12431 << Ident << DC << DroppedSpecifier << SS.getRange(),
12432 S.PDiag(diag::note_namespace_defined_here));
12433 } else {
12434 S.diagnoseTypo(Corrected,
12435 S.PDiag(diag::err_using_directive_suggest) << Ident,
12436 S.PDiag(diag::note_namespace_defined_here));
12437 }
12438 R.addDecl(D: Corrected.getFoundDecl());
12439 return true;
12440 }
12441 return false;
12442}
12443
12444Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12445 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12446 SourceLocation IdentLoc,
12447 IdentifierInfo *NamespcName,
12448 const ParsedAttributesView &AttrList) {
12449 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12450 assert(NamespcName && "Invalid NamespcName.");
12451 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12452
12453 // Get the innermost enclosing declaration scope.
12454 S = S->getDeclParent();
12455
12456 UsingDirectiveDecl *UDir = nullptr;
12457 NestedNameSpecifier *Qualifier = nullptr;
12458 if (SS.isSet())
12459 Qualifier = SS.getScopeRep();
12460
12461 // Lookup namespace name.
12462 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12463 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
12464 if (R.isAmbiguous())
12465 return nullptr;
12466
12467 if (R.empty()) {
12468 R.clear();
12469 // Allow "using namespace std;" or "using namespace ::std;" even if
12470 // "std" hasn't been defined yet, for GCC compatibility.
12471 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12472 NamespcName->isStr(Str: "std")) {
12473 Diag(IdentLoc, diag::ext_using_undefined_std);
12474 R.addDecl(getOrCreateStdNamespace());
12475 R.resolveKind();
12476 }
12477 // Otherwise, attempt typo correction.
12478 else TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident: NamespcName);
12479 }
12480
12481 if (!R.empty()) {
12482 NamedDecl *Named = R.getRepresentativeDecl();
12483 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12484 assert(NS && "expected namespace decl");
12485
12486 // The use of a nested name specifier may trigger deprecation warnings.
12487 DiagnoseUseOfDecl(D: Named, Locs: IdentLoc);
12488
12489 // C++ [namespace.udir]p1:
12490 // A using-directive specifies that the names in the nominated
12491 // namespace can be used in the scope in which the
12492 // using-directive appears after the using-directive. During
12493 // unqualified name lookup (3.4.1), the names appear as if they
12494 // were declared in the nearest enclosing namespace which
12495 // contains both the using-directive and the nominated
12496 // namespace. [Note: in this context, "contains" means "contains
12497 // directly or indirectly". ]
12498
12499 // Find enclosing context containing both using-directive and
12500 // nominated namespace.
12501 DeclContext *CommonAncestor = NS;
12502 while (CommonAncestor && !CommonAncestor->Encloses(DC: CurContext))
12503 CommonAncestor = CommonAncestor->getParent();
12504
12505 UDir = UsingDirectiveDecl::Create(C&: Context, DC: CurContext, UsingLoc, NamespaceLoc: NamespcLoc,
12506 QualifierLoc: SS.getWithLocInContext(Context),
12507 IdentLoc, Nominated: Named, CommonAncestor);
12508
12509 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12510 !SourceMgr.isInMainFile(Loc: SourceMgr.getExpansionLoc(Loc: IdentLoc))) {
12511 Diag(IdentLoc, diag::warn_using_directive_in_header);
12512 }
12513
12514 PushUsingDirective(S, UDir);
12515 } else {
12516 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12517 }
12518
12519 if (UDir) {
12520 ProcessDeclAttributeList(S, UDir, AttrList);
12521 ProcessAPINotes(UDir);
12522 }
12523
12524 return UDir;
12525}
12526
12527void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12528 // If the scope has an associated entity and the using directive is at
12529 // namespace or translation unit scope, add the UsingDirectiveDecl into
12530 // its lookup structure so qualified name lookup can find it.
12531 DeclContext *Ctx = S->getEntity();
12532 if (Ctx && !Ctx->isFunctionOrMethod())
12533 Ctx->addDecl(UDir);
12534 else
12535 // Otherwise, it is at block scope. The using-directives will affect lookup
12536 // only to the end of the scope.
12537 S->PushUsingDirective(UDir);
12538}
12539
12540Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12541 SourceLocation UsingLoc,
12542 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12543 UnqualifiedId &Name,
12544 SourceLocation EllipsisLoc,
12545 const ParsedAttributesView &AttrList) {
12546 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12547
12548 if (SS.isEmpty()) {
12549 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12550 return nullptr;
12551 }
12552
12553 switch (Name.getKind()) {
12554 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12555 case UnqualifiedIdKind::IK_Identifier:
12556 case UnqualifiedIdKind::IK_OperatorFunctionId:
12557 case UnqualifiedIdKind::IK_LiteralOperatorId:
12558 case UnqualifiedIdKind::IK_ConversionFunctionId:
12559 break;
12560
12561 case UnqualifiedIdKind::IK_ConstructorName:
12562 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12563 // C++11 inheriting constructors.
12564 Diag(Name.getBeginLoc(),
12565 getLangOpts().CPlusPlus11
12566 ? diag::warn_cxx98_compat_using_decl_constructor
12567 : diag::err_using_decl_constructor)
12568 << SS.getRange();
12569
12570 if (getLangOpts().CPlusPlus11) break;
12571
12572 return nullptr;
12573
12574 case UnqualifiedIdKind::IK_DestructorName:
12575 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12576 return nullptr;
12577
12578 case UnqualifiedIdKind::IK_TemplateId:
12579 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12580 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12581 return nullptr;
12582
12583 case UnqualifiedIdKind::IK_DeductionGuideName:
12584 llvm_unreachable("cannot parse qualified deduction guide name");
12585 }
12586
12587 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12588 DeclarationName TargetName = TargetNameInfo.getName();
12589 if (!TargetName)
12590 return nullptr;
12591
12592 // Warn about access declarations.
12593 if (UsingLoc.isInvalid()) {
12594 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12595 ? diag::err_access_decl
12596 : diag::warn_access_decl_deprecated)
12597 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12598 }
12599
12600 if (EllipsisLoc.isInvalid()) {
12601 if (DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_UsingDeclaration) ||
12602 DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC: UPPC_UsingDeclaration))
12603 return nullptr;
12604 } else {
12605 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
12606 !TargetNameInfo.containsUnexpandedParameterPack()) {
12607 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12608 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12609 EllipsisLoc = SourceLocation();
12610 }
12611 }
12612
12613 NamedDecl *UD =
12614 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12615 SS, TargetNameInfo, EllipsisLoc, AttrList,
12616 /*IsInstantiation*/ false,
12617 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12618 if (UD)
12619 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12620
12621 return UD;
12622}
12623
12624Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12625 SourceLocation UsingLoc,
12626 SourceLocation EnumLoc, SourceRange TyLoc,
12627 const IdentifierInfo &II, ParsedType Ty,
12628 CXXScopeSpec *SS) {
12629 assert(SS && !SS->isInvalid() && "ScopeSpec is invalid");
12630 TypeSourceInfo *TSI = nullptr;
12631 SourceLocation IdentLoc = TyLoc.getBegin();
12632 QualType EnumTy = GetTypeFromParser(Ty, TInfo: &TSI);
12633 if (EnumTy.isNull()) {
12634 Diag(IdentLoc, isDependentScopeSpecifier(*SS)
12635 ? diag::err_using_enum_is_dependent
12636 : diag::err_unknown_typename)
12637 << II.getName() << SourceRange(SS->getBeginLoc(), TyLoc.getEnd());
12638 return nullptr;
12639 }
12640
12641 if (EnumTy->isDependentType()) {
12642 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12643 return nullptr;
12644 }
12645
12646 auto *Enum = dyn_cast_if_present<EnumDecl>(Val: EnumTy->getAsTagDecl());
12647 if (!Enum) {
12648 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12649 return nullptr;
12650 }
12651
12652 if (auto *Def = Enum->getDefinition())
12653 Enum = Def;
12654
12655 if (TSI == nullptr)
12656 TSI = Context.getTrivialTypeSourceInfo(T: EnumTy, Loc: IdentLoc);
12657
12658 auto *UD =
12659 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, NameLoc: IdentLoc, EnumType: TSI, ED: Enum);
12660
12661 if (UD)
12662 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12663
12664 return UD;
12665}
12666
12667/// Determine whether a using declaration considers the given
12668/// declarations as "equivalent", e.g., if they are redeclarations of
12669/// the same entity or are both typedefs of the same type.
12670static bool
12671IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12672 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12673 return true;
12674
12675 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(Val: D1))
12676 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(Val: D2))
12677 return Context.hasSameType(T1: TD1->getUnderlyingType(),
12678 T2: TD2->getUnderlyingType());
12679
12680 // Two using_if_exists using-declarations are equivalent if both are
12681 // unresolved.
12682 if (isa<UnresolvedUsingIfExistsDecl>(Val: D1) &&
12683 isa<UnresolvedUsingIfExistsDecl>(Val: D2))
12684 return true;
12685
12686 return false;
12687}
12688
12689bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12690 const LookupResult &Previous,
12691 UsingShadowDecl *&PrevShadow) {
12692 // Diagnose finding a decl which is not from a base class of the
12693 // current class. We do this now because there are cases where this
12694 // function will silently decide not to build a shadow decl, which
12695 // will pre-empt further diagnostics.
12696 //
12697 // We don't need to do this in C++11 because we do the check once on
12698 // the qualifier.
12699 //
12700 // FIXME: diagnose the following if we care enough:
12701 // struct A { int foo; };
12702 // struct B : A { using A::foo; };
12703 // template <class T> struct C : A {};
12704 // template <class T> struct D : C<T> { using B::foo; } // <---
12705 // This is invalid (during instantiation) in C++03 because B::foo
12706 // resolves to the using decl in B, which is not a base class of D<T>.
12707 // We can't diagnose it immediately because C<T> is an unknown
12708 // specialization. The UsingShadowDecl in D<T> then points directly
12709 // to A::foo, which will look well-formed when we instantiate.
12710 // The right solution is to not collapse the shadow-decl chain.
12711 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12712 if (auto *Using = dyn_cast<UsingDecl>(Val: BUD)) {
12713 DeclContext *OrigDC = Orig->getDeclContext();
12714
12715 // Handle enums and anonymous structs.
12716 if (isa<EnumDecl>(Val: OrigDC))
12717 OrigDC = OrigDC->getParent();
12718 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(Val: OrigDC);
12719 while (OrigRec->isAnonymousStructOrUnion())
12720 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12721
12722 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(Base: OrigRec)) {
12723 if (OrigDC == CurContext) {
12724 Diag(Using->getLocation(),
12725 diag::err_using_decl_nested_name_specifier_is_current_class)
12726 << Using->getQualifierLoc().getSourceRange();
12727 Diag(Orig->getLocation(), diag::note_using_decl_target);
12728 Using->setInvalidDecl();
12729 return true;
12730 }
12731
12732 Diag(Using->getQualifierLoc().getBeginLoc(),
12733 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12734 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12735 << Using->getQualifierLoc().getSourceRange();
12736 Diag(Orig->getLocation(), diag::note_using_decl_target);
12737 Using->setInvalidDecl();
12738 return true;
12739 }
12740 }
12741
12742 if (Previous.empty()) return false;
12743
12744 NamedDecl *Target = Orig;
12745 if (isa<UsingShadowDecl>(Val: Target))
12746 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12747
12748 // If the target happens to be one of the previous declarations, we
12749 // don't have a conflict.
12750 //
12751 // FIXME: but we might be increasing its access, in which case we
12752 // should redeclare it.
12753 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12754 bool FoundEquivalentDecl = false;
12755 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12756 I != E; ++I) {
12757 NamedDecl *D = (*I)->getUnderlyingDecl();
12758 // We can have UsingDecls in our Previous results because we use the same
12759 // LookupResult for checking whether the UsingDecl itself is a valid
12760 // redeclaration.
12761 if (isa<UsingDecl>(Val: D) || isa<UsingPackDecl>(Val: D) || isa<UsingEnumDecl>(Val: D))
12762 continue;
12763
12764 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
12765 // C++ [class.mem]p19:
12766 // If T is the name of a class, then [every named member other than
12767 // a non-static data member] shall have a name different from T
12768 if (RD->isInjectedClassName() && !isa<FieldDecl>(Val: Target) &&
12769 !isa<IndirectFieldDecl>(Val: Target) &&
12770 !isa<UnresolvedUsingValueDecl>(Val: Target) &&
12771 DiagnoseClassNameShadow(
12772 DC: CurContext,
12773 Info: DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12774 return true;
12775 }
12776
12777 if (IsEquivalentForUsingDecl(Context, D1: D, D2: Target)) {
12778 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: *I))
12779 PrevShadow = Shadow;
12780 FoundEquivalentDecl = true;
12781 } else if (isEquivalentInternalLinkageDeclaration(A: D, B: Target)) {
12782 // We don't conflict with an existing using shadow decl of an equivalent
12783 // declaration, but we're not a redeclaration of it.
12784 FoundEquivalentDecl = true;
12785 }
12786
12787 if (isVisible(D))
12788 (isa<TagDecl>(Val: D) ? Tag : NonTag) = D;
12789 }
12790
12791 if (FoundEquivalentDecl)
12792 return false;
12793
12794 // Always emit a diagnostic for a mismatch between an unresolved
12795 // using_if_exists and a resolved using declaration in either direction.
12796 if (isa<UnresolvedUsingIfExistsDecl>(Val: Target) !=
12797 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(Val: NonTag))) {
12798 if (!NonTag && !Tag)
12799 return false;
12800 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12801 Diag(Target->getLocation(), diag::note_using_decl_target);
12802 Diag((NonTag ? NonTag : Tag)->getLocation(),
12803 diag::note_using_decl_conflict);
12804 BUD->setInvalidDecl();
12805 return true;
12806 }
12807
12808 if (FunctionDecl *FD = Target->getAsFunction()) {
12809 NamedDecl *OldDecl = nullptr;
12810 switch (CheckOverload(S: nullptr, New: FD, OldDecls: Previous, OldDecl,
12811 /*IsForUsingDecl*/ UseMemberUsingDeclRules: true)) {
12812 case OverloadKind::Overload:
12813 return false;
12814
12815 case OverloadKind::NonFunction:
12816 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12817 break;
12818
12819 // We found a decl with the exact signature.
12820 case OverloadKind::Match:
12821 // If we're in a record, we want to hide the target, so we
12822 // return true (without a diagnostic) to tell the caller not to
12823 // build a shadow decl.
12824 if (CurContext->isRecord())
12825 return true;
12826
12827 // If we're not in a record, this is an error.
12828 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12829 break;
12830 }
12831
12832 Diag(Target->getLocation(), diag::note_using_decl_target);
12833 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12834 BUD->setInvalidDecl();
12835 return true;
12836 }
12837
12838 // Target is not a function.
12839
12840 if (isa<TagDecl>(Val: Target)) {
12841 // No conflict between a tag and a non-tag.
12842 if (!Tag) return false;
12843
12844 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12845 Diag(Target->getLocation(), diag::note_using_decl_target);
12846 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12847 BUD->setInvalidDecl();
12848 return true;
12849 }
12850
12851 // No conflict between a tag and a non-tag.
12852 if (!NonTag) return false;
12853
12854 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12855 Diag(Target->getLocation(), diag::note_using_decl_target);
12856 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12857 BUD->setInvalidDecl();
12858 return true;
12859}
12860
12861/// Determine whether a direct base class is a virtual base class.
12862static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12863 if (!Derived->getNumVBases())
12864 return false;
12865 for (auto &B : Derived->bases())
12866 if (B.getType()->getAsCXXRecordDecl() == Base)
12867 return B.isVirtual();
12868 llvm_unreachable("not a direct base class");
12869}
12870
12871UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12872 NamedDecl *Orig,
12873 UsingShadowDecl *PrevDecl) {
12874 // If we resolved to another shadow declaration, just coalesce them.
12875 NamedDecl *Target = Orig;
12876 if (isa<UsingShadowDecl>(Val: Target)) {
12877 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12878 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12879 }
12880
12881 NamedDecl *NonTemplateTarget = Target;
12882 if (auto *TargetTD = dyn_cast<TemplateDecl>(Val: Target))
12883 NonTemplateTarget = TargetTD->getTemplatedDecl();
12884
12885 UsingShadowDecl *Shadow;
12886 if (NonTemplateTarget && isa<CXXConstructorDecl>(Val: NonTemplateTarget)) {
12887 UsingDecl *Using = cast<UsingDecl>(Val: BUD);
12888 bool IsVirtualBase =
12889 isVirtualDirectBase(Derived: cast<CXXRecordDecl>(Val: CurContext),
12890 Base: Using->getQualifier()->getAsRecordDecl());
12891 Shadow = ConstructorUsingShadowDecl::Create(
12892 C&: Context, DC: CurContext, Loc: Using->getLocation(), Using, Target: Orig, IsVirtual: IsVirtualBase);
12893 } else {
12894 Shadow = UsingShadowDecl::Create(C&: Context, DC: CurContext, Loc: BUD->getLocation(),
12895 Name: Target->getDeclName(), Introducer: BUD, Target);
12896 }
12897 BUD->addShadowDecl(S: Shadow);
12898
12899 Shadow->setAccess(BUD->getAccess());
12900 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12901 Shadow->setInvalidDecl();
12902
12903 Shadow->setPreviousDecl(PrevDecl);
12904
12905 if (S)
12906 PushOnScopeChains(Shadow, S);
12907 else
12908 CurContext->addDecl(Shadow);
12909
12910
12911 return Shadow;
12912}
12913
12914void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12915 if (Shadow->getDeclName().getNameKind() ==
12916 DeclarationName::CXXConversionFunctionName)
12917 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12918
12919 // Remove it from the DeclContext...
12920 Shadow->getDeclContext()->removeDecl(Shadow);
12921
12922 // ...and the scope, if applicable...
12923 if (S) {
12924 S->RemoveDecl(Shadow);
12925 IdResolver.RemoveDecl(Shadow);
12926 }
12927
12928 // ...and the using decl.
12929 Shadow->getIntroducer()->removeShadowDecl(S: Shadow);
12930
12931 // TODO: complain somehow if Shadow was used. It shouldn't
12932 // be possible for this to happen, because...?
12933}
12934
12935/// Find the base specifier for a base class with the given type.
12936static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12937 QualType DesiredBase,
12938 bool &AnyDependentBases) {
12939 // Check whether the named type is a direct base class.
12940 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12941 .getUnqualifiedType();
12942 for (auto &Base : Derived->bases()) {
12943 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12944 if (CanonicalDesiredBase == BaseType)
12945 return &Base;
12946 if (BaseType->isDependentType())
12947 AnyDependentBases = true;
12948 }
12949 return nullptr;
12950}
12951
12952namespace {
12953class UsingValidatorCCC final : public CorrectionCandidateCallback {
12954public:
12955 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12956 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12957 : HasTypenameKeyword(HasTypenameKeyword),
12958 IsInstantiation(IsInstantiation), OldNNS(NNS),
12959 RequireMemberOf(RequireMemberOf) {}
12960
12961 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12962 NamedDecl *ND = Candidate.getCorrectionDecl();
12963
12964 // Keywords are not valid here.
12965 if (!ND || isa<NamespaceDecl>(Val: ND))
12966 return false;
12967
12968 // Completely unqualified names are invalid for a 'using' declaration.
12969 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12970 return false;
12971
12972 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12973 // reject.
12974
12975 if (RequireMemberOf) {
12976 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
12977 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12978 // No-one ever wants a using-declaration to name an injected-class-name
12979 // of a base class, unless they're declaring an inheriting constructor.
12980 ASTContext &Ctx = ND->getASTContext();
12981 if (!Ctx.getLangOpts().CPlusPlus11)
12982 return false;
12983 QualType FoundType = Ctx.getRecordType(FoundRecord);
12984
12985 // Check that the injected-class-name is named as a member of its own
12986 // type; we don't want to suggest 'using Derived::Base;', since that
12987 // means something else.
12988 NestedNameSpecifier *Specifier =
12989 Candidate.WillReplaceSpecifier()
12990 ? Candidate.getCorrectionSpecifier()
12991 : OldNNS;
12992 if (!Specifier->getAsType() ||
12993 !Ctx.hasSameType(T1: QualType(Specifier->getAsType(), 0), T2: FoundType))
12994 return false;
12995
12996 // Check that this inheriting constructor declaration actually names a
12997 // direct base class of the current class.
12998 bool AnyDependentBases = false;
12999 if (!findDirectBaseWithType(Derived: RequireMemberOf,
13000 DesiredBase: Ctx.getRecordType(FoundRecord),
13001 AnyDependentBases) &&
13002 !AnyDependentBases)
13003 return false;
13004 } else {
13005 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
13006 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(Base: RD))
13007 return false;
13008
13009 // FIXME: Check that the base class member is accessible?
13010 }
13011 } else {
13012 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13013 if (FoundRecord && FoundRecord->isInjectedClassName())
13014 return false;
13015 }
13016
13017 if (isa<TypeDecl>(Val: ND))
13018 return HasTypenameKeyword || !IsInstantiation;
13019
13020 return !HasTypenameKeyword;
13021 }
13022
13023 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13024 return std::make_unique<UsingValidatorCCC>(args&: *this);
13025 }
13026
13027private:
13028 bool HasTypenameKeyword;
13029 bool IsInstantiation;
13030 NestedNameSpecifier *OldNNS;
13031 CXXRecordDecl *RequireMemberOf;
13032};
13033} // end anonymous namespace
13034
13035void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
13036 // It is really dumb that we have to do this.
13037 LookupResult::Filter F = Previous.makeFilter();
13038 while (F.hasNext()) {
13039 NamedDecl *D = F.next();
13040 if (!isDeclInScope(D, Ctx: CurContext, S))
13041 F.erase();
13042 // If we found a local extern declaration that's not ordinarily visible,
13043 // and this declaration is being added to a non-block scope, ignore it.
13044 // We're only checking for scope conflicts here, not also for violations
13045 // of the linkage rules.
13046 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13047 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
13048 F.erase();
13049 }
13050 F.done();
13051}
13052
13053NamedDecl *Sema::BuildUsingDeclaration(
13054 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13055 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13056 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13057 const ParsedAttributesView &AttrList, bool IsInstantiation,
13058 bool IsUsingIfExists) {
13059 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13060 SourceLocation IdentLoc = NameInfo.getLoc();
13061 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13062
13063 // FIXME: We ignore attributes for now.
13064
13065 // For an inheriting constructor declaration, the name of the using
13066 // declaration is the name of a constructor in this class, not in the
13067 // base class.
13068 DeclarationNameInfo UsingName = NameInfo;
13069 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
13070 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext))
13071 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13072 Ty: Context.getCanonicalType(T: Context.getRecordType(RD))));
13073
13074 // Do the redeclaration lookup in the current scope.
13075 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13076 RedeclarationKind::ForVisibleRedeclaration);
13077 Previous.setHideTags(false);
13078 if (S) {
13079 LookupName(R&: Previous, S);
13080
13081 FilterUsingLookup(S, Previous);
13082 } else {
13083 assert(IsInstantiation && "no scope in non-instantiation");
13084 if (CurContext->isRecord())
13085 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13086 else {
13087 // No redeclaration check is needed here; in non-member contexts we
13088 // diagnosed all possible conflicts with other using-declarations when
13089 // building the template:
13090 //
13091 // For a dependent non-type using declaration, the only valid case is
13092 // if we instantiate to a single enumerator. We check for conflicts
13093 // between shadow declarations we introduce, and we check in the template
13094 // definition for conflicts between a non-type using declaration and any
13095 // other declaration, which together covers all cases.
13096 //
13097 // A dependent typename using declaration will never successfully
13098 // instantiate, since it will always name a class member, so we reject
13099 // that in the template definition.
13100 }
13101 }
13102
13103 // Check for invalid redeclarations.
13104 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13105 SS, NameLoc: IdentLoc, Previous))
13106 return nullptr;
13107
13108 // 'using_if_exists' doesn't make sense on an inherited constructor.
13109 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13110 DeclarationName::CXXConstructorName) {
13111 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13112 return nullptr;
13113 }
13114
13115 DeclContext *LookupContext = computeDeclContext(SS);
13116 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13117 if (!LookupContext || EllipsisLoc.isValid()) {
13118 NamedDecl *D;
13119 // Dependent scope, or an unexpanded pack
13120 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword,
13121 SS, NameInfo, NameLoc: IdentLoc))
13122 return nullptr;
13123
13124 if (Previous.isSingleResult() &&
13125 Previous.getFoundDecl()->isTemplateParameter())
13126 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13127
13128 if (HasTypenameKeyword) {
13129 // FIXME: not all declaration name kinds are legal here
13130 D = UnresolvedUsingTypenameDecl::Create(C&: Context, DC: CurContext,
13131 UsingLoc, TypenameLoc,
13132 QualifierLoc,
13133 TargetNameLoc: IdentLoc, TargetName: NameInfo.getName(),
13134 EllipsisLoc);
13135 } else {
13136 D = UnresolvedUsingValueDecl::Create(C&: Context, DC: CurContext, UsingLoc,
13137 QualifierLoc, NameInfo, EllipsisLoc);
13138 }
13139 D->setAccess(AS);
13140 CurContext->addDecl(D);
13141 ProcessDeclAttributeList(S, D, AttrList);
13142 return D;
13143 }
13144
13145 auto Build = [&](bool Invalid) {
13146 UsingDecl *UD =
13147 UsingDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, QualifierLoc,
13148 NameInfo: UsingName, HasTypenameKeyword);
13149 UD->setAccess(AS);
13150 CurContext->addDecl(UD);
13151 ProcessDeclAttributeList(S, UD, AttrList);
13152 UD->setInvalidDecl(Invalid);
13153 return UD;
13154 };
13155 auto BuildInvalid = [&]{ return Build(true); };
13156 auto BuildValid = [&]{ return Build(false); };
13157
13158 if (RequireCompleteDeclContext(SS, DC: LookupContext))
13159 return BuildInvalid();
13160
13161 // Look up the target name.
13162 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13163
13164 // Unlike most lookups, we don't always want to hide tag
13165 // declarations: tag names are visible through the using declaration
13166 // even if hidden by ordinary names, *except* in a dependent context
13167 // where they may be used by two-phase lookup.
13168 if (!IsInstantiation)
13169 R.setHideTags(false);
13170
13171 // For the purposes of this lookup, we have a base object type
13172 // equal to that of the current context.
13173 if (CurContext->isRecord()) {
13174 R.setBaseObjectType(
13175 Context.getTypeDeclType(cast<CXXRecordDecl>(Val: CurContext)));
13176 }
13177
13178 LookupQualifiedName(R, LookupCtx: LookupContext);
13179
13180 // Validate the context, now we have a lookup
13181 if (CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, SS, NameInfo,
13182 NameLoc: IdentLoc, R: &R))
13183 return nullptr;
13184
13185 if (R.empty() && IsUsingIfExists)
13186 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Ctx&: Context, DC: CurContext, Loc: UsingLoc,
13187 Name: UsingName.getName()),
13188 AS_public);
13189
13190 // Try to correct typos if possible. If constructor name lookup finds no
13191 // results, that means the named class has no explicit constructors, and we
13192 // suppressed declaring implicit ones (probably because it's dependent or
13193 // invalid).
13194 if (R.empty() &&
13195 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
13196 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13197 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13198 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13199 auto *II = NameInfo.getName().getAsIdentifierInfo();
13200 if (getLangOpts().CPlusPlus14 && II && II->isStr(Str: "gets") &&
13201 CurContext->isStdNamespace() &&
13202 isa<TranslationUnitDecl>(Val: LookupContext) &&
13203 PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2016'12'21) &&
13204 getSourceManager().isInSystemHeader(Loc: UsingLoc))
13205 return nullptr;
13206 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13207 dyn_cast<CXXRecordDecl>(Val: CurContext));
13208 if (TypoCorrection Corrected =
13209 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
13210 Mode: CorrectTypoKind::ErrorRecovery)) {
13211 // We reject candidates where DroppedSpecifier == true, hence the
13212 // literal '0' below.
13213 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13214 << NameInfo.getName() << LookupContext << 0
13215 << SS.getRange());
13216
13217 // If we picked a correction with no attached Decl we can't do anything
13218 // useful with it, bail out.
13219 NamedDecl *ND = Corrected.getCorrectionDecl();
13220 if (!ND)
13221 return BuildInvalid();
13222
13223 // If we corrected to an inheriting constructor, handle it as one.
13224 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
13225 if (RD && RD->isInjectedClassName()) {
13226 // The parent of the injected class name is the class itself.
13227 RD = cast<CXXRecordDecl>(RD->getParent());
13228
13229 // Fix up the information we'll use to build the using declaration.
13230 if (Corrected.WillReplaceSpecifier()) {
13231 NestedNameSpecifierLocBuilder Builder;
13232 Builder.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
13233 R: QualifierLoc.getSourceRange());
13234 QualifierLoc = Builder.getWithLocInContext(Context);
13235 }
13236
13237 // In this case, the name we introduce is the name of a derived class
13238 // constructor.
13239 auto *CurClass = cast<CXXRecordDecl>(Val: CurContext);
13240 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13241 Ty: Context.getCanonicalType(T: Context.getRecordType(CurClass))));
13242 UsingName.setNamedTypeInfo(nullptr);
13243 for (auto *Ctor : LookupConstructors(Class: RD))
13244 R.addDecl(D: Ctor);
13245 R.resolveKind();
13246 } else {
13247 // FIXME: Pick up all the declarations if we found an overloaded
13248 // function.
13249 UsingName.setName(ND->getDeclName());
13250 R.addDecl(D: ND);
13251 }
13252 } else {
13253 Diag(IdentLoc, diag::err_no_member)
13254 << NameInfo.getName() << LookupContext << SS.getRange();
13255 return BuildInvalid();
13256 }
13257 }
13258
13259 if (R.isAmbiguous())
13260 return BuildInvalid();
13261
13262 if (HasTypenameKeyword) {
13263 // If we asked for a typename and got a non-type decl, error out.
13264 if (!R.getAsSingle<TypeDecl>() &&
13265 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13266 Diag(IdentLoc, diag::err_using_typename_non_type);
13267 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13268 Diag((*I)->getUnderlyingDecl()->getLocation(),
13269 diag::note_using_decl_target);
13270 return BuildInvalid();
13271 }
13272 } else {
13273 // If we asked for a non-typename and we got a type, error out,
13274 // but only if this is an instantiation of an unresolved using
13275 // decl. Otherwise just silently find the type name.
13276 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13277 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13278 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13279 return BuildInvalid();
13280 }
13281 }
13282
13283 // C++14 [namespace.udecl]p6:
13284 // A using-declaration shall not name a namespace.
13285 if (R.getAsSingle<NamespaceDecl>()) {
13286 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13287 << SS.getRange();
13288 // Suggest using 'using namespace ...' instead.
13289 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13290 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13291 return BuildInvalid();
13292 }
13293
13294 UsingDecl *UD = BuildValid();
13295
13296 // Some additional rules apply to inheriting constructors.
13297 if (UsingName.getName().getNameKind() ==
13298 DeclarationName::CXXConstructorName) {
13299 // Suppress access diagnostics; the access check is instead performed at the
13300 // point of use for an inheriting constructor.
13301 R.suppressDiagnostics();
13302 if (CheckInheritingConstructorUsingDecl(UD))
13303 return UD;
13304 }
13305
13306 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
13307 UsingShadowDecl *PrevDecl = nullptr;
13308 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
13309 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
13310 }
13311
13312 return UD;
13313}
13314
13315NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13316 SourceLocation UsingLoc,
13317 SourceLocation EnumLoc,
13318 SourceLocation NameLoc,
13319 TypeSourceInfo *EnumType,
13320 EnumDecl *ED) {
13321 bool Invalid = false;
13322
13323 if (CurContext->getRedeclContext()->isRecord()) {
13324 /// In class scope, check if this is a duplicate, for better a diagnostic.
13325 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13326 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13327 RedeclarationKind::ForVisibleRedeclaration);
13328
13329 LookupName(R&: Previous, S);
13330
13331 for (NamedDecl *D : Previous)
13332 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13333 if (UED->getEnumDecl() == ED) {
13334 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13335 << SourceRange(EnumLoc, NameLoc);
13336 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13337 Invalid = true;
13338 break;
13339 }
13340 }
13341
13342 if (RequireCompleteEnumDecl(D: ED, L: NameLoc))
13343 Invalid = true;
13344
13345 UsingEnumDecl *UD = UsingEnumDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc,
13346 EnumL: EnumLoc, NameL: NameLoc, EnumType);
13347 UD->setAccess(AS);
13348 CurContext->addDecl(UD);
13349
13350 if (Invalid) {
13351 UD->setInvalidDecl();
13352 return UD;
13353 }
13354
13355 // Create the shadow decls for each enumerator
13356 for (EnumConstantDecl *EC : ED->enumerators()) {
13357 UsingShadowDecl *PrevDecl = nullptr;
13358 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13359 LookupResult Previous(*this, DNI, LookupOrdinaryName,
13360 RedeclarationKind::ForVisibleRedeclaration);
13361 LookupName(R&: Previous, S);
13362 FilterUsingLookup(S, Previous);
13363
13364 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13365 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13366 }
13367
13368 return UD;
13369}
13370
13371NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13372 ArrayRef<NamedDecl *> Expansions) {
13373 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13374 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13375 isa<UsingPackDecl>(InstantiatedFrom));
13376
13377 auto *UPD =
13378 UsingPackDecl::Create(C&: Context, DC: CurContext, InstantiatedFrom, UsingDecls: Expansions);
13379 UPD->setAccess(InstantiatedFrom->getAccess());
13380 CurContext->addDecl(UPD);
13381 return UPD;
13382}
13383
13384bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13385 assert(!UD->hasTypename() && "expecting a constructor name");
13386
13387 const Type *SourceType = UD->getQualifier()->getAsType();
13388 assert(SourceType &&
13389 "Using decl naming constructor doesn't have type in scope spec.");
13390 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(Val: CurContext);
13391
13392 // Check whether the named type is a direct base class.
13393 bool AnyDependentBases = false;
13394 auto *Base = findDirectBaseWithType(Derived: TargetClass, DesiredBase: QualType(SourceType, 0),
13395 AnyDependentBases);
13396 if (!Base && !AnyDependentBases) {
13397 Diag(UD->getUsingLoc(),
13398 diag::err_using_decl_constructor_not_in_direct_base)
13399 << UD->getNameInfo().getSourceRange()
13400 << QualType(SourceType, 0) << TargetClass;
13401 UD->setInvalidDecl();
13402 return true;
13403 }
13404
13405 if (Base)
13406 Base->setInheritConstructors();
13407
13408 return false;
13409}
13410
13411bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13412 bool HasTypenameKeyword,
13413 const CXXScopeSpec &SS,
13414 SourceLocation NameLoc,
13415 const LookupResult &Prev) {
13416 NestedNameSpecifier *Qual = SS.getScopeRep();
13417
13418 // C++03 [namespace.udecl]p8:
13419 // C++0x [namespace.udecl]p10:
13420 // A using-declaration is a declaration and can therefore be used
13421 // repeatedly where (and only where) multiple declarations are
13422 // allowed.
13423 //
13424 // That's in non-member contexts.
13425 if (!CurContext->getRedeclContext()->isRecord()) {
13426 // A dependent qualifier outside a class can only ever resolve to an
13427 // enumeration type. Therefore it conflicts with any other non-type
13428 // declaration in the same scope.
13429 // FIXME: How should we check for dependent type-type conflicts at block
13430 // scope?
13431 if (Qual->isDependent() && !HasTypenameKeyword) {
13432 for (auto *D : Prev) {
13433 if (!isa<TypeDecl>(Val: D) && !isa<UsingDecl>(Val: D) && !isa<UsingPackDecl>(Val: D)) {
13434 bool OldCouldBeEnumerator =
13435 isa<UnresolvedUsingValueDecl>(Val: D) || isa<EnumConstantDecl>(Val: D);
13436 Diag(NameLoc,
13437 OldCouldBeEnumerator ? diag::err_redefinition
13438 : diag::err_redefinition_different_kind)
13439 << Prev.getLookupName();
13440 Diag(D->getLocation(), diag::note_previous_definition);
13441 return true;
13442 }
13443 }
13444 }
13445 return false;
13446 }
13447
13448 const NestedNameSpecifier *CNNS =
13449 Context.getCanonicalNestedNameSpecifier(NNS: Qual);
13450 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13451 NamedDecl *D = *I;
13452
13453 bool DTypename;
13454 NestedNameSpecifier *DQual;
13455 if (UsingDecl *UD = dyn_cast<UsingDecl>(Val: D)) {
13456 DTypename = UD->hasTypename();
13457 DQual = UD->getQualifier();
13458 } else if (UnresolvedUsingValueDecl *UD
13459 = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) {
13460 DTypename = false;
13461 DQual = UD->getQualifier();
13462 } else if (UnresolvedUsingTypenameDecl *UD
13463 = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) {
13464 DTypename = true;
13465 DQual = UD->getQualifier();
13466 } else continue;
13467
13468 // using decls differ if one says 'typename' and the other doesn't.
13469 // FIXME: non-dependent using decls?
13470 if (HasTypenameKeyword != DTypename) continue;
13471
13472 // using decls differ if they name different scopes (but note that
13473 // template instantiation can cause this check to trigger when it
13474 // didn't before instantiation).
13475 if (CNNS != Context.getCanonicalNestedNameSpecifier(NNS: DQual))
13476 continue;
13477
13478 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13479 Diag(D->getLocation(), diag::note_using_decl) << 1;
13480 return true;
13481 }
13482
13483 return false;
13484}
13485
13486bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13487 const CXXScopeSpec &SS,
13488 const DeclarationNameInfo &NameInfo,
13489 SourceLocation NameLoc,
13490 const LookupResult *R, const UsingDecl *UD) {
13491 DeclContext *NamedContext = computeDeclContext(SS);
13492 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13493 "resolvable context must have exactly one set of decls");
13494
13495 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13496 // relationship.
13497 bool Cxx20Enumerator = false;
13498 if (NamedContext) {
13499 EnumConstantDecl *EC = nullptr;
13500 if (R)
13501 EC = R->getAsSingle<EnumConstantDecl>();
13502 else if (UD && UD->shadow_size() == 1)
13503 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13504 if (EC)
13505 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13506
13507 if (auto *ED = dyn_cast<EnumDecl>(Val: NamedContext)) {
13508 // C++14 [namespace.udecl]p7:
13509 // A using-declaration shall not name a scoped enumerator.
13510 // C++20 p1099 permits enumerators.
13511 if (EC && R && ED->isScoped())
13512 Diag(SS.getBeginLoc(),
13513 getLangOpts().CPlusPlus20
13514 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13515 : diag::ext_using_decl_scoped_enumerator)
13516 << SS.getRange();
13517
13518 // We want to consider the scope of the enumerator
13519 NamedContext = ED->getDeclContext();
13520 }
13521 }
13522
13523 if (!CurContext->isRecord()) {
13524 // C++03 [namespace.udecl]p3:
13525 // C++0x [namespace.udecl]p8:
13526 // A using-declaration for a class member shall be a member-declaration.
13527 // C++20 [namespace.udecl]p7
13528 // ... other than an enumerator ...
13529
13530 // If we weren't able to compute a valid scope, it might validly be a
13531 // dependent class or enumeration scope. If we have a 'typename' keyword,
13532 // the scope must resolve to a class type.
13533 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13534 : !HasTypename)
13535 return false; // OK
13536
13537 Diag(NameLoc,
13538 Cxx20Enumerator
13539 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13540 : diag::err_using_decl_can_not_refer_to_class_member)
13541 << SS.getRange();
13542
13543 if (Cxx20Enumerator)
13544 return false; // OK
13545
13546 auto *RD = NamedContext
13547 ? cast<CXXRecordDecl>(Val: NamedContext->getRedeclContext())
13548 : nullptr;
13549 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13550 // See if there's a helpful fixit
13551
13552 if (!R) {
13553 // We will have already diagnosed the problem on the template
13554 // definition, Maybe we should do so again?
13555 } else if (R->getAsSingle<TypeDecl>()) {
13556 if (getLangOpts().CPlusPlus11) {
13557 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13558 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13559 << diag::MemClassWorkaround::AliasDecl
13560 << FixItHint::CreateInsertion(SS.getBeginLoc(),
13561 NameInfo.getName().getAsString() +
13562 " = ");
13563 } else {
13564 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13565 SourceLocation InsertLoc = getLocForEndOfToken(Loc: NameInfo.getEndLoc());
13566 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13567 << diag::MemClassWorkaround::TypedefDecl
13568 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13569 << FixItHint::CreateInsertion(
13570 InsertLoc, " " + NameInfo.getName().getAsString());
13571 }
13572 } else if (R->getAsSingle<VarDecl>()) {
13573 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13574 // repeating the type of the static data member here.
13575 FixItHint FixIt;
13576 if (getLangOpts().CPlusPlus11) {
13577 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13578 FixIt = FixItHint::CreateReplacement(
13579 RemoveRange: UsingLoc, Code: "auto &" + NameInfo.getName().getAsString() + " = ");
13580 }
13581
13582 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13583 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13584 } else if (R->getAsSingle<EnumConstantDecl>()) {
13585 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13586 // repeating the type of the enumeration here, and we can't do so if
13587 // the type is anonymous.
13588 FixItHint FixIt;
13589 if (getLangOpts().CPlusPlus11) {
13590 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13591 FixIt = FixItHint::CreateReplacement(
13592 RemoveRange: UsingLoc,
13593 Code: "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13594 }
13595
13596 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13597 << (getLangOpts().CPlusPlus11
13598 ? diag::MemClassWorkaround::ConstexprVar
13599 : diag::MemClassWorkaround::ConstVar)
13600 << FixIt;
13601 }
13602 }
13603
13604 return true; // Fail
13605 }
13606
13607 // If the named context is dependent, we can't decide much.
13608 if (!NamedContext) {
13609 // FIXME: in C++0x, we can diagnose if we can prove that the
13610 // nested-name-specifier does not refer to a base class, which is
13611 // still possible in some cases.
13612
13613 // Otherwise we have to conservatively report that things might be
13614 // okay.
13615 return false;
13616 }
13617
13618 // The current scope is a record.
13619 if (!NamedContext->isRecord()) {
13620 // Ideally this would point at the last name in the specifier,
13621 // but we don't have that level of source info.
13622 Diag(SS.getBeginLoc(),
13623 Cxx20Enumerator
13624 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13625 : diag::err_using_decl_nested_name_specifier_is_not_class)
13626 << SS.getScopeRep() << SS.getRange();
13627
13628 if (Cxx20Enumerator)
13629 return false; // OK
13630
13631 return true;
13632 }
13633
13634 if (!NamedContext->isDependentContext() &&
13635 RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec&>(SS), DC: NamedContext))
13636 return true;
13637
13638 if (getLangOpts().CPlusPlus11) {
13639 // C++11 [namespace.udecl]p3:
13640 // In a using-declaration used as a member-declaration, the
13641 // nested-name-specifier shall name a base class of the class
13642 // being defined.
13643
13644 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(
13645 Base: cast<CXXRecordDecl>(Val: NamedContext))) {
13646
13647 if (Cxx20Enumerator) {
13648 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13649 << SS.getRange();
13650 return false;
13651 }
13652
13653 if (CurContext == NamedContext) {
13654 Diag(SS.getBeginLoc(),
13655 diag::err_using_decl_nested_name_specifier_is_current_class)
13656 << SS.getRange();
13657 return !getLangOpts().CPlusPlus20;
13658 }
13659
13660 if (!cast<CXXRecordDecl>(Val: NamedContext)->isInvalidDecl()) {
13661 Diag(SS.getBeginLoc(),
13662 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13663 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13664 << SS.getRange();
13665 }
13666 return true;
13667 }
13668
13669 return false;
13670 }
13671
13672 // C++03 [namespace.udecl]p4:
13673 // A using-declaration used as a member-declaration shall refer
13674 // to a member of a base class of the class being defined [etc.].
13675
13676 // Salient point: SS doesn't have to name a base class as long as
13677 // lookup only finds members from base classes. Therefore we can
13678 // diagnose here only if we can prove that can't happen,
13679 // i.e. if the class hierarchies provably don't intersect.
13680
13681 // TODO: it would be nice if "definitely valid" results were cached
13682 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13683 // need to be repeated.
13684
13685 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
13686 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13687 Bases.insert(Ptr: Base);
13688 return true;
13689 };
13690
13691 // Collect all bases. Return false if we find a dependent base.
13692 if (!cast<CXXRecordDecl>(Val: CurContext)->forallBases(BaseMatches: Collect))
13693 return false;
13694
13695 // Returns true if the base is dependent or is one of the accumulated base
13696 // classes.
13697 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13698 return !Bases.count(Ptr: Base);
13699 };
13700
13701 // Return false if the class has a dependent base or if it or one
13702 // of its bases is present in the base set of the current context.
13703 if (Bases.count(Ptr: cast<CXXRecordDecl>(Val: NamedContext)) ||
13704 !cast<CXXRecordDecl>(Val: NamedContext)->forallBases(BaseMatches: IsNotBase))
13705 return false;
13706
13707 Diag(SS.getRange().getBegin(),
13708 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13709 << SS.getScopeRep()
13710 << cast<CXXRecordDecl>(CurContext)
13711 << SS.getRange();
13712
13713 return true;
13714}
13715
13716Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13717 MultiTemplateParamsArg TemplateParamLists,
13718 SourceLocation UsingLoc, UnqualifiedId &Name,
13719 const ParsedAttributesView &AttrList,
13720 TypeResult Type, Decl *DeclFromDeclSpec) {
13721
13722 if (Type.isInvalid())
13723 return nullptr;
13724
13725 bool Invalid = false;
13726 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13727 TypeSourceInfo *TInfo = nullptr;
13728 GetTypeFromParser(Ty: Type.get(), TInfo: &TInfo);
13729
13730 if (DiagnoseClassNameShadow(DC: CurContext, Info: NameInfo))
13731 return nullptr;
13732
13733 if (DiagnoseUnexpandedParameterPack(Loc: Name.StartLocation, T: TInfo,
13734 UPPC: UPPC_DeclarationType)) {
13735 Invalid = true;
13736 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
13737 Loc: TInfo->getTypeLoc().getBeginLoc());
13738 }
13739
13740 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13741 TemplateParamLists.size()
13742 ? forRedeclarationInCurContext()
13743 : RedeclarationKind::ForVisibleRedeclaration);
13744 LookupName(R&: Previous, S);
13745
13746 // Warn about shadowing the name of a template parameter.
13747 if (Previous.isSingleResult() &&
13748 Previous.getFoundDecl()->isTemplateParameter()) {
13749 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13750 Previous.clear();
13751 }
13752
13753 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13754 "name in alias declaration must be an identifier");
13755 TypeAliasDecl *NewTD = TypeAliasDecl::Create(C&: Context, DC: CurContext, StartLoc: UsingLoc,
13756 IdLoc: Name.StartLocation,
13757 Id: Name.Identifier, TInfo);
13758
13759 NewTD->setAccess(AS);
13760
13761 if (Invalid)
13762 NewTD->setInvalidDecl();
13763
13764 ProcessDeclAttributeList(S, NewTD, AttrList);
13765 AddPragmaAttributes(S, NewTD);
13766 ProcessAPINotes(NewTD);
13767
13768 CheckTypedefForVariablyModifiedType(S, NewTD);
13769 Invalid |= NewTD->isInvalidDecl();
13770
13771 // Get the innermost enclosing declaration scope.
13772 S = S->getDeclParent();
13773
13774 bool Redeclaration = false;
13775
13776 NamedDecl *NewND;
13777 if (TemplateParamLists.size()) {
13778 TypeAliasTemplateDecl *OldDecl = nullptr;
13779 TemplateParameterList *OldTemplateParams = nullptr;
13780
13781 if (TemplateParamLists.size() != 1) {
13782 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13783 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13784 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13785 Invalid = true;
13786 }
13787 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13788
13789 // Check that we can declare a template here.
13790 if (CheckTemplateDeclScope(S, TemplateParams))
13791 return nullptr;
13792
13793 // Only consider previous declarations in the same scope.
13794 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13795 /*ExplicitInstantiationOrSpecialization*/AllowInlineNamespace: false);
13796 if (!Previous.empty()) {
13797 Redeclaration = true;
13798
13799 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13800 if (!OldDecl && !Invalid) {
13801 Diag(UsingLoc, diag::err_redefinition_different_kind)
13802 << Name.Identifier;
13803
13804 NamedDecl *OldD = Previous.getRepresentativeDecl();
13805 if (OldD->getLocation().isValid())
13806 Diag(OldD->getLocation(), diag::note_previous_definition);
13807
13808 Invalid = true;
13809 }
13810
13811 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13812 if (TemplateParameterListsAreEqual(TemplateParams,
13813 OldDecl->getTemplateParameters(),
13814 /*Complain=*/true,
13815 TPL_TemplateMatch))
13816 OldTemplateParams =
13817 OldDecl->getMostRecentDecl()->getTemplateParameters();
13818 else
13819 Invalid = true;
13820
13821 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13822 if (!Invalid &&
13823 !Context.hasSameType(OldTD->getUnderlyingType(),
13824 NewTD->getUnderlyingType())) {
13825 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13826 // but we can't reasonably accept it.
13827 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13828 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13829 if (OldTD->getLocation().isValid())
13830 Diag(OldTD->getLocation(), diag::note_previous_definition);
13831 Invalid = true;
13832 }
13833 }
13834 }
13835
13836 // Merge any previous default template arguments into our parameters,
13837 // and check the parameter list.
13838 if (CheckTemplateParameterList(NewParams: TemplateParams, OldParams: OldTemplateParams,
13839 TPC: TPC_Other))
13840 return nullptr;
13841
13842 TypeAliasTemplateDecl *NewDecl =
13843 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13844 Name.Identifier, TemplateParams,
13845 NewTD);
13846 NewTD->setDescribedAliasTemplate(NewDecl);
13847
13848 NewDecl->setAccess(AS);
13849
13850 if (Invalid)
13851 NewDecl->setInvalidDecl();
13852 else if (OldDecl) {
13853 NewDecl->setPreviousDecl(OldDecl);
13854 CheckRedeclarationInModule(NewDecl, OldDecl);
13855 }
13856
13857 NewND = NewDecl;
13858 } else {
13859 if (auto *TD = dyn_cast_or_null<TagDecl>(Val: DeclFromDeclSpec)) {
13860 setTagNameForLinkagePurposes(TD, NewTD);
13861 handleTagNumbering(Tag: TD, TagScope: S);
13862 }
13863 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13864 NewND = NewTD;
13865 }
13866
13867 PushOnScopeChains(D: NewND, S);
13868 ActOnDocumentableDecl(NewND);
13869 return NewND;
13870}
13871
13872Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13873 SourceLocation AliasLoc,
13874 IdentifierInfo *Alias, CXXScopeSpec &SS,
13875 SourceLocation IdentLoc,
13876 IdentifierInfo *Ident) {
13877
13878 // Lookup the namespace name.
13879 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13880 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
13881
13882 if (R.isAmbiguous())
13883 return nullptr;
13884
13885 if (R.empty()) {
13886 if (!TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident)) {
13887 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13888 return nullptr;
13889 }
13890 }
13891 assert(!R.isAmbiguous() && !R.empty());
13892 NamedDecl *ND = R.getRepresentativeDecl();
13893
13894 // Check if we have a previous declaration with the same name.
13895 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13896 RedeclarationKind::ForVisibleRedeclaration);
13897 LookupName(R&: PrevR, S);
13898
13899 // Check we're not shadowing a template parameter.
13900 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13901 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13902 PrevR.clear();
13903 }
13904
13905 // Filter out any other lookup result from an enclosing scope.
13906 FilterLookupForScope(R&: PrevR, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13907 /*AllowInlineNamespace*/false);
13908
13909 // Find the previous declaration and check that we can redeclare it.
13910 NamespaceAliasDecl *Prev = nullptr;
13911 if (PrevR.isSingleResult()) {
13912 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13913 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Val: PrevDecl)) {
13914 // We already have an alias with the same name that points to the same
13915 // namespace; check that it matches.
13916 if (AD->getNamespace()->Equals(getNamespaceDecl(D: ND))) {
13917 Prev = AD;
13918 } else if (isVisible(D: PrevDecl)) {
13919 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13920 << Alias;
13921 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13922 << AD->getNamespace();
13923 return nullptr;
13924 }
13925 } else if (isVisible(D: PrevDecl)) {
13926 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13927 ? diag::err_redefinition
13928 : diag::err_redefinition_different_kind;
13929 Diag(AliasLoc, DiagID) << Alias;
13930 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13931 return nullptr;
13932 }
13933 }
13934
13935 // The use of a nested name specifier may trigger deprecation warnings.
13936 DiagnoseUseOfDecl(D: ND, Locs: IdentLoc);
13937
13938 NamespaceAliasDecl *AliasDecl =
13939 NamespaceAliasDecl::Create(C&: Context, DC: CurContext, NamespaceLoc, AliasLoc,
13940 Alias, QualifierLoc: SS.getWithLocInContext(Context),
13941 IdentLoc, Namespace: ND);
13942 if (Prev)
13943 AliasDecl->setPreviousDecl(Prev);
13944
13945 PushOnScopeChains(AliasDecl, S);
13946 return AliasDecl;
13947}
13948
13949namespace {
13950struct SpecialMemberExceptionSpecInfo
13951 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13952 SourceLocation Loc;
13953 Sema::ImplicitExceptionSpecification ExceptSpec;
13954
13955 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13956 CXXSpecialMemberKind CSM,
13957 Sema::InheritedConstructorInfo *ICI,
13958 SourceLocation Loc)
13959 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13960
13961 bool visitBase(CXXBaseSpecifier *Base);
13962 bool visitField(FieldDecl *FD);
13963
13964 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13965 unsigned Quals);
13966
13967 void visitSubobjectCall(Subobject Subobj,
13968 Sema::SpecialMemberOverloadResult SMOR);
13969};
13970}
13971
13972bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13973 auto *RT = Base->getType()->getAs<RecordType>();
13974 if (!RT)
13975 return false;
13976
13977 auto *BaseClass = cast<CXXRecordDecl>(Val: RT->getDecl());
13978 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
13979 if (auto *BaseCtor = SMOR.getMethod()) {
13980 visitSubobjectCall(Subobj: Base, SMOR: BaseCtor);
13981 return false;
13982 }
13983
13984 visitClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
13985 return false;
13986}
13987
13988bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13989 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
13990 FD->hasInClassInitializer()) {
13991 Expr *E = FD->getInClassInitializer();
13992 if (!E)
13993 // FIXME: It's a little wasteful to build and throw away a
13994 // CXXDefaultInitExpr here.
13995 // FIXME: We should have a single context note pointing at Loc, and
13996 // this location should be MD->getLocation() instead, since that's
13997 // the location where we actually use the default init expression.
13998 E = S.BuildCXXDefaultInitExpr(Loc, Field: FD).get();
13999 if (E)
14000 ExceptSpec.CalledExpr(E);
14001 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
14002 ->getAs<RecordType>()) {
14003 visitClassSubobject(Class: cast<CXXRecordDecl>(RT->getDecl()), Subobj: FD,
14004 Quals: FD->getType().getCVRQualifiers());
14005 }
14006 return false;
14007}
14008
14009void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14010 Subobject Subobj,
14011 unsigned Quals) {
14012 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14013 bool IsMutable = Field && Field->isMutable();
14014 visitSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable));
14015}
14016
14017void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14018 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14019 // Note, if lookup fails, it doesn't matter what exception specification we
14020 // choose because the special member will be deleted.
14021 if (CXXMethodDecl *MD = SMOR.getMethod())
14022 ExceptSpec.CalledDecl(CallLoc: getSubobjectLoc(Subobj), Method: MD);
14023}
14024
14025bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
14026 llvm::APSInt Result;
14027 ExprResult Converted = CheckConvertedConstantExpression(
14028 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
14029 ExplicitSpec.setExpr(Converted.get());
14030 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14031 ExplicitSpec.setKind(Result.getBoolValue()
14032 ? ExplicitSpecKind::ResolvedTrue
14033 : ExplicitSpecKind::ResolvedFalse);
14034 return true;
14035 }
14036 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
14037 return false;
14038}
14039
14040ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
14041 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
14042 if (!ExplicitExpr->isTypeDependent())
14043 tryResolveExplicitSpecifier(ExplicitSpec&: ES);
14044 return ES;
14045}
14046
14047static Sema::ImplicitExceptionSpecification
14048ComputeDefaultedSpecialMemberExceptionSpec(
14049 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
14050 Sema::InheritedConstructorInfo *ICI) {
14051 ComputingExceptionSpec CES(S, MD, Loc);
14052
14053 CXXRecordDecl *ClassDecl = MD->getParent();
14054
14055 // C++ [except.spec]p14:
14056 // An implicitly declared special member function (Clause 12) shall have an
14057 // exception-specification. [...]
14058 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14059 if (ClassDecl->isInvalidDecl())
14060 return Info.ExceptSpec;
14061
14062 // FIXME: If this diagnostic fires, we're probably missing a check for
14063 // attempting to resolve an exception specification before it's known
14064 // at a higher level.
14065 if (S.RequireCompleteType(MD->getLocation(),
14066 S.Context.getRecordType(ClassDecl),
14067 diag::err_exception_spec_incomplete_type))
14068 return Info.ExceptSpec;
14069
14070 // C++1z [except.spec]p7:
14071 // [Look for exceptions thrown by] a constructor selected [...] to
14072 // initialize a potentially constructed subobject,
14073 // C++1z [except.spec]p8:
14074 // The exception specification for an implicitly-declared destructor, or a
14075 // destructor without a noexcept-specifier, is potentially-throwing if and
14076 // only if any of the destructors for any of its potentially constructed
14077 // subojects is potentially throwing.
14078 // FIXME: We respect the first rule but ignore the "potentially constructed"
14079 // in the second rule to resolve a core issue (no number yet) that would have
14080 // us reject:
14081 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14082 // struct B : A {};
14083 // struct C : B { void f(); };
14084 // ... due to giving B::~B() a non-throwing exception specification.
14085 Info.visit(Bases: Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14086 : Info.VisitAllBases);
14087
14088 return Info.ExceptSpec;
14089}
14090
14091namespace {
14092/// RAII object to register a special member as being currently declared.
14093struct DeclaringSpecialMember {
14094 Sema &S;
14095 Sema::SpecialMemberDecl D;
14096 Sema::ContextRAII SavedContext;
14097 bool WasAlreadyBeingDeclared;
14098
14099 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14100 : S(S), D(RD, CSM), SavedContext(S, RD) {
14101 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(Ptr: D).second;
14102 if (WasAlreadyBeingDeclared)
14103 // This almost never happens, but if it does, ensure that our cache
14104 // doesn't contain a stale result.
14105 S.SpecialMemberCache.clear();
14106 else {
14107 // Register a note to be produced if we encounter an error while
14108 // declaring the special member.
14109 Sema::CodeSynthesisContext Ctx;
14110 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14111 // FIXME: We don't have a location to use here. Using the class's
14112 // location maintains the fiction that we declare all special members
14113 // with the class, but (1) it's not clear that lying about that helps our
14114 // users understand what's going on, and (2) there may be outer contexts
14115 // on the stack (some of which are relevant) and printing them exposes
14116 // our lies.
14117 Ctx.PointOfInstantiation = RD->getLocation();
14118 Ctx.Entity = RD;
14119 Ctx.SpecialMember = CSM;
14120 S.pushCodeSynthesisContext(Ctx);
14121 }
14122 }
14123 ~DeclaringSpecialMember() {
14124 if (!WasAlreadyBeingDeclared) {
14125 S.SpecialMembersBeingDeclared.erase(Ptr: D);
14126 S.popCodeSynthesisContext();
14127 }
14128 }
14129
14130 /// Are we already trying to declare this special member?
14131 bool isAlreadyBeingDeclared() const {
14132 return WasAlreadyBeingDeclared;
14133 }
14134};
14135}
14136
14137void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
14138 // Look up any existing declarations, but don't trigger declaration of all
14139 // implicit special members with this name.
14140 DeclarationName Name = FD->getDeclName();
14141 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
14142 RedeclarationKind::ForExternalRedeclaration);
14143 for (auto *D : FD->getParent()->lookup(Name))
14144 if (auto *Acceptable = R.getAcceptableDecl(D))
14145 R.addDecl(Acceptable);
14146 R.resolveKind();
14147 R.suppressDiagnostics();
14148
14149 CheckFunctionDeclaration(S, NewFD: FD, Previous&: R, /*IsMemberSpecialization*/ false,
14150 DeclIsDefn: FD->isThisDeclarationADefinition());
14151}
14152
14153void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14154 QualType ResultTy,
14155 ArrayRef<QualType> Args) {
14156 // Build an exception specification pointing back at this constructor.
14157 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(S&: *this, MD: SpecialMem);
14158
14159 LangAS AS = getDefaultCXXMethodAddrSpace();
14160 if (AS != LangAS::Default) {
14161 EPI.TypeQuals.addAddressSpace(space: AS);
14162 }
14163
14164 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14165 SpecialMem->setType(QT);
14166
14167 // During template instantiation of implicit special member functions we need
14168 // a reliable TypeSourceInfo for the function prototype in order to allow
14169 // functions to be substituted.
14170 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14171 TypeSourceInfo *TSI =
14172 Context.getTrivialTypeSourceInfo(T: SpecialMem->getType());
14173 SpecialMem->setTypeSourceInfo(TSI);
14174 }
14175}
14176
14177CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
14178 CXXRecordDecl *ClassDecl) {
14179 // C++ [class.ctor]p5:
14180 // A default constructor for a class X is a constructor of class X
14181 // that can be called without an argument. If there is no
14182 // user-declared constructor for class X, a default constructor is
14183 // implicitly declared. An implicitly-declared default constructor
14184 // is an inline public member of its class.
14185 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14186 "Should not build implicit default constructor!");
14187
14188 DeclaringSpecialMember DSM(*this, ClassDecl,
14189 CXXSpecialMemberKind::DefaultConstructor);
14190 if (DSM.isAlreadyBeingDeclared())
14191 return nullptr;
14192
14193 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14194 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, ConstArg: false);
14195
14196 // Create the actual constructor declaration.
14197 CanQualType ClassType
14198 = Context.getCanonicalType(T: Context.getTypeDeclType(ClassDecl));
14199 SourceLocation ClassLoc = ClassDecl->getLocation();
14200 DeclarationName Name
14201 = Context.DeclarationNames.getCXXConstructorName(Ty: ClassType);
14202 DeclarationNameInfo NameInfo(Name, ClassLoc);
14203 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
14204 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, /*Type*/ T: QualType(),
14205 /*TInfo=*/nullptr, ES: ExplicitSpecifier(),
14206 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14207 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14208 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14209 : ConstexprSpecKind::Unspecified);
14210 DefaultCon->setAccess(AS_public);
14211 DefaultCon->setDefaulted();
14212
14213 setupImplicitSpecialMemberType(SpecialMem: DefaultCon, ResultTy: Context.VoidTy, Args: {});
14214
14215 if (getLangOpts().CUDA)
14216 CUDA().inferTargetForImplicitSpecialMember(
14217 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14218 /* ConstRHS */ false,
14219 /* Diagnose */ false);
14220
14221 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14222 // constructors is easy to compute.
14223 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14224
14225 // Note that we have declared this constructor.
14226 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14227
14228 Scope *S = getScopeForContext(ClassDecl);
14229 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
14230
14231 if (ShouldDeleteSpecialMember(DefaultCon,
14232 CXXSpecialMemberKind::DefaultConstructor))
14233 SetDeclDeleted(DefaultCon, ClassLoc);
14234
14235 if (S)
14236 PushOnScopeChains(DefaultCon, S, false);
14237 ClassDecl->addDecl(DefaultCon);
14238
14239 return DefaultCon;
14240}
14241
14242void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14243 CXXConstructorDecl *Constructor) {
14244 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14245 !Constructor->doesThisDeclarationHaveABody() &&
14246 !Constructor->isDeleted()) &&
14247 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14248 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14249 return;
14250
14251 CXXRecordDecl *ClassDecl = Constructor->getParent();
14252 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14253 if (ClassDecl->isInvalidDecl()) {
14254 return;
14255 }
14256
14257 SynthesizedFunctionScope Scope(*this, Constructor);
14258
14259 // The exception specification is needed because we are defining the
14260 // function.
14261 ResolveExceptionSpec(Loc: CurrentLocation,
14262 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14263 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14264
14265 // Add a context note for diagnostics produced after this point.
14266 Scope.addContextNote(UseLoc: CurrentLocation);
14267
14268 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14269 Constructor->setInvalidDecl();
14270 return;
14271 }
14272
14273 SourceLocation Loc = Constructor->getEndLoc().isValid()
14274 ? Constructor->getEndLoc()
14275 : Constructor->getLocation();
14276 Constructor->setBody(new (Context) CompoundStmt(Loc));
14277 Constructor->markUsed(Context);
14278
14279 if (ASTMutationListener *L = getASTMutationListener()) {
14280 L->CompletedImplicitDefinition(Constructor);
14281 }
14282
14283 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14284}
14285
14286void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14287 // Perform any delayed checks on exception specifications.
14288 CheckDelayedMemberExceptionSpecs();
14289}
14290
14291/// Find or create the fake constructor we synthesize to model constructing an
14292/// object of a derived class via a constructor of a base class.
14293CXXConstructorDecl *
14294Sema::findInheritingConstructor(SourceLocation Loc,
14295 CXXConstructorDecl *BaseCtor,
14296 ConstructorUsingShadowDecl *Shadow) {
14297 CXXRecordDecl *Derived = Shadow->getParent();
14298 SourceLocation UsingLoc = Shadow->getLocation();
14299
14300 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14301 // For now we use the name of the base class constructor as a member of the
14302 // derived class to indicate a (fake) inherited constructor name.
14303 DeclarationName Name = BaseCtor->getDeclName();
14304
14305 // Check to see if we already have a fake constructor for this inherited
14306 // constructor call.
14307 for (NamedDecl *Ctor : Derived->lookup(Name))
14308 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
14309 ->getInheritedConstructor()
14310 .getConstructor(),
14311 BaseCtor))
14312 return cast<CXXConstructorDecl>(Ctor);
14313
14314 DeclarationNameInfo NameInfo(Name, UsingLoc);
14315 TypeSourceInfo *TInfo =
14316 Context.getTrivialTypeSourceInfo(T: BaseCtor->getType(), Loc: UsingLoc);
14317 FunctionProtoTypeLoc ProtoLoc =
14318 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14319
14320 // Check the inherited constructor is valid and find the list of base classes
14321 // from which it was inherited.
14322 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14323
14324 bool Constexpr = BaseCtor->isConstexpr() &&
14325 defaultedSpecialMemberIsConstexpr(
14326 S&: *this, ClassDecl: Derived, CSM: CXXSpecialMemberKind::DefaultConstructor,
14327 ConstArg: false, InheritedCtor: BaseCtor, Inherited: &ICI);
14328
14329 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14330 C&: Context, RD: Derived, StartLoc: UsingLoc, NameInfo, T: TInfo->getType(), TInfo,
14331 ES: BaseCtor->getExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14332 /*isInline=*/true,
14333 /*isImplicitlyDeclared=*/true,
14334 ConstexprKind: Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14335 Inherited: InheritedConstructor(Shadow, BaseCtor),
14336 TrailingRequiresClause: BaseCtor->getTrailingRequiresClause());
14337 if (Shadow->isInvalidDecl())
14338 DerivedCtor->setInvalidDecl();
14339
14340 // Build an unevaluated exception specification for this fake constructor.
14341 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14342 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14343 EPI.ExceptionSpec.Type = EST_Unevaluated;
14344 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14345 DerivedCtor->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
14346 Args: FPT->getParamTypes(), EPI));
14347
14348 // Build the parameter declarations.
14349 SmallVector<ParmVarDecl *, 16> ParamDecls;
14350 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14351 TypeSourceInfo *TInfo =
14352 Context.getTrivialTypeSourceInfo(T: FPT->getParamType(i: I), Loc: UsingLoc);
14353 ParmVarDecl *PD = ParmVarDecl::Create(
14354 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14355 FPT->getParamType(i: I), TInfo, SC_None, /*DefArg=*/nullptr);
14356 PD->setScopeInfo(scopeDepth: 0, parameterIndex: I);
14357 PD->setImplicit();
14358 // Ensure attributes are propagated onto parameters (this matters for
14359 // format, pass_object_size, ...).
14360 mergeDeclAttributes(New: PD, Old: BaseCtor->getParamDecl(I));
14361 ParamDecls.push_back(Elt: PD);
14362 ProtoLoc.setParam(I, PD);
14363 }
14364
14365 // Set up the new constructor.
14366 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14367 DerivedCtor->setAccess(BaseCtor->getAccess());
14368 DerivedCtor->setParams(ParamDecls);
14369 Derived->addDecl(DerivedCtor);
14370
14371 if (ShouldDeleteSpecialMember(DerivedCtor,
14372 CXXSpecialMemberKind::DefaultConstructor, &ICI))
14373 SetDeclDeleted(DerivedCtor, UsingLoc);
14374
14375 return DerivedCtor;
14376}
14377
14378void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14379 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14380 Ctor->getInheritedConstructor().getShadowDecl());
14381 ShouldDeleteSpecialMember(Ctor, CXXSpecialMemberKind::DefaultConstructor,
14382 &ICI,
14383 /*Diagnose*/ true);
14384}
14385
14386void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14387 CXXConstructorDecl *Constructor) {
14388 CXXRecordDecl *ClassDecl = Constructor->getParent();
14389 assert(Constructor->getInheritedConstructor() &&
14390 !Constructor->doesThisDeclarationHaveABody() &&
14391 !Constructor->isDeleted());
14392 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14393 return;
14394
14395 // Initializations are performed "as if by a defaulted default constructor",
14396 // so enter the appropriate scope.
14397 SynthesizedFunctionScope Scope(*this, Constructor);
14398
14399 // The exception specification is needed because we are defining the
14400 // function.
14401 ResolveExceptionSpec(Loc: CurrentLocation,
14402 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14403 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14404
14405 // Add a context note for diagnostics produced after this point.
14406 Scope.addContextNote(UseLoc: CurrentLocation);
14407
14408 ConstructorUsingShadowDecl *Shadow =
14409 Constructor->getInheritedConstructor().getShadowDecl();
14410 CXXConstructorDecl *InheritedCtor =
14411 Constructor->getInheritedConstructor().getConstructor();
14412
14413 // [class.inhctor.init]p1:
14414 // initialization proceeds as if a defaulted default constructor is used to
14415 // initialize the D object and each base class subobject from which the
14416 // constructor was inherited
14417
14418 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14419 CXXRecordDecl *RD = Shadow->getParent();
14420 SourceLocation InitLoc = Shadow->getLocation();
14421
14422 // Build explicit initializers for all base classes from which the
14423 // constructor was inherited.
14424 SmallVector<CXXCtorInitializer*, 8> Inits;
14425 for (bool VBase : {false, true}) {
14426 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14427 if (B.isVirtual() != VBase)
14428 continue;
14429
14430 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14431 if (!BaseRD)
14432 continue;
14433
14434 auto BaseCtor = ICI.findConstructorForBase(Base: BaseRD, Ctor: InheritedCtor);
14435 if (!BaseCtor.first)
14436 continue;
14437
14438 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14439 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14440 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14441
14442 auto *TInfo = Context.getTrivialTypeSourceInfo(T: B.getType(), Loc: InitLoc);
14443 Inits.push_back(Elt: new (Context) CXXCtorInitializer(
14444 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14445 SourceLocation()));
14446 }
14447 }
14448
14449 // We now proceed as if for a defaulted default constructor, with the relevant
14450 // initializers replaced.
14451
14452 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Initializers: Inits)) {
14453 Constructor->setInvalidDecl();
14454 return;
14455 }
14456
14457 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14458 Constructor->markUsed(Context);
14459
14460 if (ASTMutationListener *L = getASTMutationListener()) {
14461 L->CompletedImplicitDefinition(Constructor);
14462 }
14463
14464 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14465}
14466
14467CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14468 // C++ [class.dtor]p2:
14469 // If a class has no user-declared destructor, a destructor is
14470 // declared implicitly. An implicitly-declared destructor is an
14471 // inline public member of its class.
14472 assert(ClassDecl->needsImplicitDestructor());
14473
14474 DeclaringSpecialMember DSM(*this, ClassDecl,
14475 CXXSpecialMemberKind::Destructor);
14476 if (DSM.isAlreadyBeingDeclared())
14477 return nullptr;
14478
14479 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14480 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::Destructor, ConstArg: false);
14481
14482 // Create the actual destructor declaration.
14483 CanQualType ClassType
14484 = Context.getCanonicalType(T: Context.getTypeDeclType(ClassDecl));
14485 SourceLocation ClassLoc = ClassDecl->getLocation();
14486 DeclarationName Name
14487 = Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
14488 DeclarationNameInfo NameInfo(Name, ClassLoc);
14489 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14490 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), TInfo: nullptr,
14491 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14492 /*isInline=*/true,
14493 /*isImplicitlyDeclared=*/true,
14494 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14495 : ConstexprSpecKind::Unspecified);
14496 Destructor->setAccess(AS_public);
14497 Destructor->setDefaulted();
14498
14499 setupImplicitSpecialMemberType(SpecialMem: Destructor, ResultTy: Context.VoidTy, Args: {});
14500
14501 if (getLangOpts().CUDA)
14502 CUDA().inferTargetForImplicitSpecialMember(
14503 ClassDecl, CXXSpecialMemberKind::Destructor, Destructor,
14504 /* ConstRHS */ false,
14505 /* Diagnose */ false);
14506
14507 // We don't need to use SpecialMemberIsTrivial here; triviality for
14508 // destructors is easy to compute.
14509 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14510 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14511 ClassDecl->hasTrivialDestructorForCall());
14512
14513 // Note that we have declared this destructor.
14514 ++getASTContext().NumImplicitDestructorsDeclared;
14515
14516 Scope *S = getScopeForContext(ClassDecl);
14517 CheckImplicitSpecialMemberDeclaration(S, Destructor);
14518
14519 // We can't check whether an implicit destructor is deleted before we complete
14520 // the definition of the class, because its validity depends on the alignment
14521 // of the class. We'll check this from ActOnFields once the class is complete.
14522 if (ClassDecl->isCompleteDefinition() &&
14523 ShouldDeleteSpecialMember(Destructor, CXXSpecialMemberKind::Destructor))
14524 SetDeclDeleted(Destructor, ClassLoc);
14525
14526 // Introduce this destructor into its scope.
14527 if (S)
14528 PushOnScopeChains(Destructor, S, false);
14529 ClassDecl->addDecl(Destructor);
14530
14531 return Destructor;
14532}
14533
14534void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14535 CXXDestructorDecl *Destructor) {
14536 assert((Destructor->isDefaulted() &&
14537 !Destructor->doesThisDeclarationHaveABody() &&
14538 !Destructor->isDeleted()) &&
14539 "DefineImplicitDestructor - call it for implicit default dtor");
14540 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14541 return;
14542
14543 CXXRecordDecl *ClassDecl = Destructor->getParent();
14544 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14545
14546 SynthesizedFunctionScope Scope(*this, Destructor);
14547
14548 // The exception specification is needed because we are defining the
14549 // function.
14550 ResolveExceptionSpec(Loc: CurrentLocation,
14551 FPT: Destructor->getType()->castAs<FunctionProtoType>());
14552 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14553
14554 // Add a context note for diagnostics produced after this point.
14555 Scope.addContextNote(UseLoc: CurrentLocation);
14556
14557 MarkBaseAndMemberDestructorsReferenced(Location: Destructor->getLocation(),
14558 ClassDecl: Destructor->getParent());
14559
14560 if (CheckDestructor(Destructor)) {
14561 Destructor->setInvalidDecl();
14562 return;
14563 }
14564
14565 SourceLocation Loc = Destructor->getEndLoc().isValid()
14566 ? Destructor->getEndLoc()
14567 : Destructor->getLocation();
14568 Destructor->setBody(new (Context) CompoundStmt(Loc));
14569 Destructor->markUsed(Context);
14570
14571 if (ASTMutationListener *L = getASTMutationListener()) {
14572 L->CompletedImplicitDefinition(Destructor);
14573 }
14574}
14575
14576void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14577 CXXDestructorDecl *Destructor) {
14578 if (Destructor->isInvalidDecl())
14579 return;
14580
14581 CXXRecordDecl *ClassDecl = Destructor->getParent();
14582 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14583 "implicit complete dtors unneeded outside MS ABI");
14584 assert(ClassDecl->getNumVBases() > 0 &&
14585 "complete dtor only exists for classes with vbases");
14586
14587 SynthesizedFunctionScope Scope(*this, Destructor);
14588
14589 // Add a context note for diagnostics produced after this point.
14590 Scope.addContextNote(UseLoc: CurrentLocation);
14591
14592 MarkVirtualBaseDestructorsReferenced(Location: Destructor->getLocation(), ClassDecl);
14593}
14594
14595void Sema::ActOnFinishCXXMemberDecls() {
14596 // If the context is an invalid C++ class, just suppress these checks.
14597 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
14598 if (Record->isInvalidDecl()) {
14599 DelayedOverridingExceptionSpecChecks.clear();
14600 DelayedEquivalentExceptionSpecChecks.clear();
14601 return;
14602 }
14603 checkForMultipleExportedDefaultConstructors(S&: *this, Class: Record);
14604 }
14605}
14606
14607void Sema::ActOnFinishCXXNonNestedClass() {
14608 referenceDLLExportedClassMethods();
14609
14610 if (!DelayedDllExportMemberFunctions.empty()) {
14611 SmallVector<CXXMethodDecl*, 4> WorkList;
14612 std::swap(LHS&: DelayedDllExportMemberFunctions, RHS&: WorkList);
14613 for (CXXMethodDecl *M : WorkList) {
14614 DefineDefaultedFunction(*this, M, M->getLocation());
14615
14616 // Pass the method to the consumer to get emitted. This is not necessary
14617 // for explicit instantiation definitions, as they will get emitted
14618 // anyway.
14619 if (M->getParent()->getTemplateSpecializationKind() !=
14620 TSK_ExplicitInstantiationDefinition)
14621 ActOnFinishInlineFunctionDef(M);
14622 }
14623 }
14624}
14625
14626void Sema::referenceDLLExportedClassMethods() {
14627 if (!DelayedDllExportClasses.empty()) {
14628 // Calling ReferenceDllExportedMembers might cause the current function to
14629 // be called again, so use a local copy of DelayedDllExportClasses.
14630 SmallVector<CXXRecordDecl *, 4> WorkList;
14631 std::swap(LHS&: DelayedDllExportClasses, RHS&: WorkList);
14632 for (CXXRecordDecl *Class : WorkList)
14633 ReferenceDllExportedMembers(S&: *this, Class);
14634 }
14635}
14636
14637void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14638 assert(getLangOpts().CPlusPlus11 &&
14639 "adjusting dtor exception specs was introduced in c++11");
14640
14641 if (Destructor->isDependentContext())
14642 return;
14643
14644 // C++11 [class.dtor]p3:
14645 // A declaration of a destructor that does not have an exception-
14646 // specification is implicitly considered to have the same exception-
14647 // specification as an implicit declaration.
14648 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14649 if (DtorType->hasExceptionSpec())
14650 return;
14651
14652 // Replace the destructor's type, building off the existing one. Fortunately,
14653 // the only thing of interest in the destructor type is its extended info.
14654 // The return and arguments are fixed.
14655 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14656 EPI.ExceptionSpec.Type = EST_Unevaluated;
14657 EPI.ExceptionSpec.SourceDecl = Destructor;
14658 Destructor->setType(Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI));
14659
14660 // FIXME: If the destructor has a body that could throw, and the newly created
14661 // spec doesn't allow exceptions, we should emit a warning, because this
14662 // change in behavior can break conforming C++03 programs at runtime.
14663 // However, we don't have a body or an exception specification yet, so it
14664 // needs to be done somewhere else.
14665}
14666
14667namespace {
14668/// An abstract base class for all helper classes used in building the
14669// copy/move operators. These classes serve as factory functions and help us
14670// avoid using the same Expr* in the AST twice.
14671class ExprBuilder {
14672 ExprBuilder(const ExprBuilder&) = delete;
14673 ExprBuilder &operator=(const ExprBuilder&) = delete;
14674
14675protected:
14676 static Expr *assertNotNull(Expr *E) {
14677 assert(E && "Expression construction must not fail.");
14678 return E;
14679 }
14680
14681public:
14682 ExprBuilder() {}
14683 virtual ~ExprBuilder() {}
14684
14685 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14686};
14687
14688class RefBuilder: public ExprBuilder {
14689 VarDecl *Var;
14690 QualType VarType;
14691
14692public:
14693 Expr *build(Sema &S, SourceLocation Loc) const override {
14694 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14695 }
14696
14697 RefBuilder(VarDecl *Var, QualType VarType)
14698 : Var(Var), VarType(VarType) {}
14699};
14700
14701class ThisBuilder: public ExprBuilder {
14702public:
14703 Expr *build(Sema &S, SourceLocation Loc) const override {
14704 return assertNotNull(E: S.ActOnCXXThis(Loc).getAs<Expr>());
14705 }
14706};
14707
14708class CastBuilder: public ExprBuilder {
14709 const ExprBuilder &Builder;
14710 QualType Type;
14711 ExprValueKind Kind;
14712 const CXXCastPath &Path;
14713
14714public:
14715 Expr *build(Sema &S, SourceLocation Loc) const override {
14716 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14717 CK_UncheckedDerivedToBase, Kind,
14718 &Path).get());
14719 }
14720
14721 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14722 const CXXCastPath &Path)
14723 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14724};
14725
14726class DerefBuilder: public ExprBuilder {
14727 const ExprBuilder &Builder;
14728
14729public:
14730 Expr *build(Sema &S, SourceLocation Loc) const override {
14731 return assertNotNull(
14732 E: S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: Builder.build(S, Loc)).get());
14733 }
14734
14735 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14736};
14737
14738class MemberBuilder: public ExprBuilder {
14739 const ExprBuilder &Builder;
14740 QualType Type;
14741 CXXScopeSpec SS;
14742 bool IsArrow;
14743 LookupResult &MemberLookup;
14744
14745public:
14746 Expr *build(Sema &S, SourceLocation Loc) const override {
14747 return assertNotNull(S.BuildMemberReferenceExpr(
14748 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14749 nullptr, MemberLookup, nullptr, nullptr).get());
14750 }
14751
14752 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14753 LookupResult &MemberLookup)
14754 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14755 MemberLookup(MemberLookup) {}
14756};
14757
14758class MoveCastBuilder: public ExprBuilder {
14759 const ExprBuilder &Builder;
14760
14761public:
14762 Expr *build(Sema &S, SourceLocation Loc) const override {
14763 return assertNotNull(E: CastForMoving(SemaRef&: S, E: Builder.build(S, Loc)));
14764 }
14765
14766 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14767};
14768
14769class LvalueConvBuilder: public ExprBuilder {
14770 const ExprBuilder &Builder;
14771
14772public:
14773 Expr *build(Sema &S, SourceLocation Loc) const override {
14774 return assertNotNull(
14775 E: S.DefaultLvalueConversion(E: Builder.build(S, Loc)).get());
14776 }
14777
14778 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14779};
14780
14781class SubscriptBuilder: public ExprBuilder {
14782 const ExprBuilder &Base;
14783 const ExprBuilder &Index;
14784
14785public:
14786 Expr *build(Sema &S, SourceLocation Loc) const override {
14787 return assertNotNull(E: S.CreateBuiltinArraySubscriptExpr(
14788 Base: Base.build(S, Loc), LLoc: Loc, Idx: Index.build(S, Loc), RLoc: Loc).get());
14789 }
14790
14791 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14792 : Base(Base), Index(Index) {}
14793};
14794
14795} // end anonymous namespace
14796
14797/// When generating a defaulted copy or move assignment operator, if a field
14798/// should be copied with __builtin_memcpy rather than via explicit assignments,
14799/// do so. This optimization only applies for arrays of scalars, and for arrays
14800/// of class type where the selected copy/move-assignment operator is trivial.
14801static StmtResult
14802buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14803 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14804 // Compute the size of the memory buffer to be copied.
14805 QualType SizeType = S.Context.getSizeType();
14806 llvm::APInt Size(S.Context.getTypeSize(T: SizeType),
14807 S.Context.getTypeSizeInChars(T).getQuantity());
14808
14809 // Take the address of the field references for "from" and "to". We
14810 // directly construct UnaryOperators here because semantic analysis
14811 // does not permit us to take the address of an xvalue.
14812 Expr *From = FromB.build(S, Loc);
14813 From = UnaryOperator::Create(
14814 C: S.Context, input: From, opc: UO_AddrOf, type: S.Context.getPointerType(T: From->getType()),
14815 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14816 Expr *To = ToB.build(S, Loc);
14817 To = UnaryOperator::Create(
14818 C: S.Context, input: To, opc: UO_AddrOf, type: S.Context.getPointerType(T: To->getType()),
14819 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14820
14821 const Type *E = T->getBaseElementTypeUnsafe();
14822 bool NeedsCollectableMemCpy =
14823 E->isRecordType() &&
14824 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14825
14826 // Create a reference to the __builtin_objc_memmove_collectable function
14827 StringRef MemCpyName = NeedsCollectableMemCpy ?
14828 "__builtin_objc_memmove_collectable" :
14829 "__builtin_memcpy";
14830 LookupResult R(S, &S.Context.Idents.get(Name: MemCpyName), Loc,
14831 Sema::LookupOrdinaryName);
14832 S.LookupName(R, S: S.TUScope, AllowBuiltinCreation: true);
14833
14834 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14835 if (!MemCpy)
14836 // Something went horribly wrong earlier, and we will have complained
14837 // about it.
14838 return StmtError();
14839
14840 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14841 VK_PRValue, Loc, nullptr);
14842 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14843
14844 Expr *CallArgs[] = {
14845 To, From, IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc)
14846 };
14847 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14848 Loc, CallArgs, Loc);
14849
14850 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14851 return Call.getAs<Stmt>();
14852}
14853
14854/// Builds a statement that copies/moves the given entity from \p From to
14855/// \c To.
14856///
14857/// This routine is used to copy/move the members of a class with an
14858/// implicitly-declared copy/move assignment operator. When the entities being
14859/// copied are arrays, this routine builds for loops to copy them.
14860///
14861/// \param S The Sema object used for type-checking.
14862///
14863/// \param Loc The location where the implicit copy/move is being generated.
14864///
14865/// \param T The type of the expressions being copied/moved. Both expressions
14866/// must have this type.
14867///
14868/// \param To The expression we are copying/moving to.
14869///
14870/// \param From The expression we are copying/moving from.
14871///
14872/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14873/// Otherwise, it's a non-static member subobject.
14874///
14875/// \param Copying Whether we're copying or moving.
14876///
14877/// \param Depth Internal parameter recording the depth of the recursion.
14878///
14879/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14880/// if a memcpy should be used instead.
14881static StmtResult
14882buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14883 const ExprBuilder &To, const ExprBuilder &From,
14884 bool CopyingBaseSubobject, bool Copying,
14885 unsigned Depth = 0) {
14886 // C++11 [class.copy]p28:
14887 // Each subobject is assigned in the manner appropriate to its type:
14888 //
14889 // - if the subobject is of class type, as if by a call to operator= with
14890 // the subobject as the object expression and the corresponding
14891 // subobject of x as a single function argument (as if by explicit
14892 // qualification; that is, ignoring any possible virtual overriding
14893 // functions in more derived classes);
14894 //
14895 // C++03 [class.copy]p13:
14896 // - if the subobject is of class type, the copy assignment operator for
14897 // the class is used (as if by explicit qualification; that is,
14898 // ignoring any possible virtual overriding functions in more derived
14899 // classes);
14900 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14901 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: RecordTy->getDecl());
14902
14903 // Look for operator=.
14904 DeclarationName Name
14905 = S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
14906 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14907 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14908
14909 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14910 // operator.
14911 if (!S.getLangOpts().CPlusPlus11) {
14912 LookupResult::Filter F = OpLookup.makeFilter();
14913 while (F.hasNext()) {
14914 NamedDecl *D = F.next();
14915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D))
14916 if (Method->isCopyAssignmentOperator() ||
14917 (!Copying && Method->isMoveAssignmentOperator()))
14918 continue;
14919
14920 F.erase();
14921 }
14922 F.done();
14923 }
14924
14925 // Suppress the protected check (C++ [class.protected]) for each of the
14926 // assignment operators we found. This strange dance is required when
14927 // we're assigning via a base classes's copy-assignment operator. To
14928 // ensure that we're getting the right base class subobject (without
14929 // ambiguities), we need to cast "this" to that subobject type; to
14930 // ensure that we don't go through the virtual call mechanism, we need
14931 // to qualify the operator= name with the base class (see below). However,
14932 // this means that if the base class has a protected copy assignment
14933 // operator, the protected member access check will fail. So, we
14934 // rewrite "protected" access to "public" access in this case, since we
14935 // know by construction that we're calling from a derived class.
14936 if (CopyingBaseSubobject) {
14937 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14938 L != LEnd; ++L) {
14939 if (L.getAccess() == AS_protected)
14940 L.setAccess(AS_public);
14941 }
14942 }
14943
14944 // Create the nested-name-specifier that will be used to qualify the
14945 // reference to operator=; this is required to suppress the virtual
14946 // call mechanism.
14947 CXXScopeSpec SS;
14948 const Type *CanonicalT = S.Context.getCanonicalType(T: T.getTypePtr());
14949 SS.MakeTrivial(Context&: S.Context,
14950 Qualifier: NestedNameSpecifier::Create(Context: S.Context, Prefix: nullptr, T: CanonicalT),
14951 R: Loc);
14952
14953 // Create the reference to operator=.
14954 ExprResult OpEqualRef
14955 = S.BuildMemberReferenceExpr(Base: To.build(S, Loc), BaseType: T, OpLoc: Loc, /*IsArrow=*/false,
14956 SS, /*TemplateKWLoc=*/SourceLocation(),
14957 /*FirstQualifierInScope=*/nullptr,
14958 R&: OpLookup,
14959 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14960 /*SuppressQualifierCheck=*/true);
14961 if (OpEqualRef.isInvalid())
14962 return StmtError();
14963
14964 // Build the call to the assignment operator.
14965
14966 Expr *FromInst = From.build(S, Loc);
14967 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/S: nullptr,
14968 MemExpr: OpEqualRef.getAs<Expr>(),
14969 LParenLoc: Loc, Args: FromInst, RParenLoc: Loc);
14970 if (Call.isInvalid())
14971 return StmtError();
14972
14973 // If we built a call to a trivial 'operator=' while copying an array,
14974 // bail out. We'll replace the whole shebang with a memcpy.
14975 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Val: Call.get());
14976 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14977 return StmtResult((Stmt*)nullptr);
14978
14979 // Convert to an expression-statement, and clean up any produced
14980 // temporaries.
14981 return S.ActOnExprStmt(Arg: Call);
14982 }
14983
14984 // - if the subobject is of scalar type, the built-in assignment
14985 // operator is used.
14986 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14987 if (!ArrayTy) {
14988 ExprResult Assignment = S.CreateBuiltinBinOp(
14989 OpLoc: Loc, Opc: BO_Assign, LHSExpr: To.build(S, Loc), RHSExpr: From.build(S, Loc));
14990 if (Assignment.isInvalid())
14991 return StmtError();
14992 return S.ActOnExprStmt(Arg: Assignment);
14993 }
14994
14995 // - if the subobject is an array, each element is assigned, in the
14996 // manner appropriate to the element type;
14997
14998 // Construct a loop over the array bounds, e.g.,
14999 //
15000 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15001 //
15002 // that will copy each of the array elements.
15003 QualType SizeType = S.Context.getSizeType();
15004
15005 // Create the iteration variable.
15006 IdentifierInfo *IterationVarName = nullptr;
15007 {
15008 SmallString<8> Str;
15009 llvm::raw_svector_ostream OS(Str);
15010 OS << "__i" << Depth;
15011 IterationVarName = &S.Context.Idents.get(Name: OS.str());
15012 }
15013 VarDecl *IterationVar = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc,
15014 Id: IterationVarName, T: SizeType,
15015 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc),
15016 S: SC_None);
15017
15018 // Initialize the iteration variable to zero.
15019 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
15020 IterationVar->setInit(IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
15021
15022 // Creates a reference to the iteration variable.
15023 RefBuilder IterationVarRef(IterationVar, SizeType);
15024 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15025
15026 // Create the DeclStmt that holds the iteration variable.
15027 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15028
15029 // Subscript the "from" and "to" expressions with the iteration variable.
15030 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15031 MoveCastBuilder FromIndexMove(FromIndexCopy);
15032 const ExprBuilder *FromIndex;
15033 if (Copying)
15034 FromIndex = &FromIndexCopy;
15035 else
15036 FromIndex = &FromIndexMove;
15037
15038 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15039
15040 // Build the copy/move for an individual element of the array.
15041 StmtResult Copy =
15042 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
15043 ToIndex, *FromIndex, CopyingBaseSubobject,
15044 Copying, Depth + 1);
15045 // Bail out if copying fails or if we determined that we should use memcpy.
15046 if (Copy.isInvalid() || !Copy.get())
15047 return Copy;
15048
15049 // Create the comparison against the array bound.
15050 llvm::APInt Upper
15051 = ArrayTy->getSize().zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
15052 Expr *Comparison = BinaryOperator::Create(
15053 C: S.Context, lhs: IterationVarRefRVal.build(S, Loc),
15054 rhs: IntegerLiteral::Create(C: S.Context, V: Upper, type: SizeType, l: Loc), opc: BO_NE,
15055 ResTy: S.Context.BoolTy, VK: VK_PRValue, OK: OK_Ordinary, opLoc: Loc,
15056 FPFeatures: S.CurFPFeatureOverrides());
15057
15058 // Create the pre-increment of the iteration variable. We can determine
15059 // whether the increment will overflow based on the value of the array
15060 // bound.
15061 Expr *Increment = UnaryOperator::Create(
15062 C: S.Context, input: IterationVarRef.build(S, Loc), opc: UO_PreInc, type: SizeType, VK: VK_LValue,
15063 OK: OK_Ordinary, l: Loc, CanOverflow: Upper.isMaxValue(), FPFeatures: S.CurFPFeatureOverrides());
15064
15065 // Construct the loop that copies all elements of this array.
15066 return S.ActOnForStmt(
15067 ForLoc: Loc, LParenLoc: Loc, First: InitStmt,
15068 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Comparison, CK: Sema::ConditionKind::Boolean),
15069 Third: S.MakeFullDiscardedValueExpr(Arg: Increment), RParenLoc: Loc, Body: Copy.get());
15070}
15071
15072static StmtResult
15073buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
15074 const ExprBuilder &To, const ExprBuilder &From,
15075 bool CopyingBaseSubobject, bool Copying) {
15076 // Maybe we should use a memcpy?
15077 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
15078 T.isTriviallyCopyableType(Context: S.Context))
15079 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15080
15081 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15082 CopyingBaseSubobject,
15083 Copying, Depth: 0));
15084
15085 // If we ended up picking a trivial assignment operator for an array of a
15086 // non-trivially-copyable class type, just emit a memcpy.
15087 if (!Result.isInvalid() && !Result.get())
15088 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15089
15090 return Result;
15091}
15092
15093CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
15094 // Note: The following rules are largely analoguous to the copy
15095 // constructor rules. Note that virtual bases are not taken into account
15096 // for determining the argument type of the operator. Note also that
15097 // operators taking an object instead of a reference are allowed.
15098 assert(ClassDecl->needsImplicitCopyAssignment());
15099
15100 DeclaringSpecialMember DSM(*this, ClassDecl,
15101 CXXSpecialMemberKind::CopyAssignment);
15102 if (DSM.isAlreadyBeingDeclared())
15103 return nullptr;
15104
15105 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15106 ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
15107 NamedType: ArgType, OwnedTagDecl: nullptr);
15108 LangAS AS = getDefaultCXXMethodAddrSpace();
15109 if (AS != LangAS::Default)
15110 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15111 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15112 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15113 if (Const)
15114 ArgType = ArgType.withConst();
15115
15116 ArgType = Context.getLValueReferenceType(T: ArgType);
15117
15118 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15119 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Const);
15120
15121 // An implicitly-declared copy assignment operator is an inline public
15122 // member of its class.
15123 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15124 SourceLocation ClassLoc = ClassDecl->getLocation();
15125 DeclarationNameInfo NameInfo(Name, ClassLoc);
15126 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
15127 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15128 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15129 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15130 /*isInline=*/true,
15131 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15132 EndLocation: SourceLocation());
15133 CopyAssignment->setAccess(AS_public);
15134 CopyAssignment->setDefaulted();
15135 CopyAssignment->setImplicit();
15136
15137 setupImplicitSpecialMemberType(SpecialMem: CopyAssignment, ResultTy: RetType, Args: ArgType);
15138
15139 if (getLangOpts().CUDA)
15140 CUDA().inferTargetForImplicitSpecialMember(
15141 ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, MemberDecl: CopyAssignment,
15142 /* ConstRHS */ Const,
15143 /* Diagnose */ false);
15144
15145 // Add the parameter to the operator.
15146 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
15147 ClassLoc, ClassLoc,
15148 /*Id=*/nullptr, ArgType,
15149 /*TInfo=*/nullptr, SC_None,
15150 nullptr);
15151 CopyAssignment->setParams(FromParam);
15152
15153 CopyAssignment->setTrivial(
15154 ClassDecl->needsOverloadResolutionForCopyAssignment()
15155 ? SpecialMemberIsTrivial(MD: CopyAssignment,
15156 CSM: CXXSpecialMemberKind::CopyAssignment)
15157 : ClassDecl->hasTrivialCopyAssignment());
15158
15159 // Note that we have added this copy-assignment operator.
15160 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15161
15162 Scope *S = getScopeForContext(ClassDecl);
15163 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
15164
15165 if (ShouldDeleteSpecialMember(MD: CopyAssignment,
15166 CSM: CXXSpecialMemberKind::CopyAssignment)) {
15167 ClassDecl->setImplicitCopyAssignmentIsDeleted();
15168 SetDeclDeleted(CopyAssignment, ClassLoc);
15169 }
15170
15171 if (S)
15172 PushOnScopeChains(CopyAssignment, S, false);
15173 ClassDecl->addDecl(CopyAssignment);
15174
15175 return CopyAssignment;
15176}
15177
15178/// Diagnose an implicit copy operation for a class which is odr-used, but
15179/// which is deprecated because the class has a user-declared copy constructor,
15180/// copy assignment operator, or destructor.
15181static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
15182 assert(CopyOp->isImplicit());
15183
15184 CXXRecordDecl *RD = CopyOp->getParent();
15185 CXXMethodDecl *UserDeclaredOperation = nullptr;
15186
15187 if (RD->hasUserDeclaredDestructor()) {
15188 UserDeclaredOperation = RD->getDestructor();
15189 } else if (!isa<CXXConstructorDecl>(Val: CopyOp) &&
15190 RD->hasUserDeclaredCopyConstructor()) {
15191 // Find any user-declared copy constructor.
15192 for (auto *I : RD->ctors()) {
15193 if (I->isCopyConstructor()) {
15194 UserDeclaredOperation = I;
15195 break;
15196 }
15197 }
15198 assert(UserDeclaredOperation);
15199 } else if (isa<CXXConstructorDecl>(Val: CopyOp) &&
15200 RD->hasUserDeclaredCopyAssignment()) {
15201 // Find any user-declared move assignment operator.
15202 for (auto *I : RD->methods()) {
15203 if (I->isCopyAssignmentOperator()) {
15204 UserDeclaredOperation = I;
15205 break;
15206 }
15207 }
15208 assert(UserDeclaredOperation);
15209 }
15210
15211 if (UserDeclaredOperation) {
15212 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15213 bool UDOIsDestructor = isa<CXXDestructorDecl>(Val: UserDeclaredOperation);
15214 bool IsCopyAssignment = !isa<CXXConstructorDecl>(Val: CopyOp);
15215 unsigned DiagID =
15216 (UDOIsUserProvided && UDOIsDestructor)
15217 ? diag::warn_deprecated_copy_with_user_provided_dtor
15218 : (UDOIsUserProvided && !UDOIsDestructor)
15219 ? diag::warn_deprecated_copy_with_user_provided_copy
15220 : (!UDOIsUserProvided && UDOIsDestructor)
15221 ? diag::warn_deprecated_copy_with_dtor
15222 : diag::warn_deprecated_copy;
15223 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15224 << RD << IsCopyAssignment;
15225 }
15226}
15227
15228void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15229 CXXMethodDecl *CopyAssignOperator) {
15230 assert((CopyAssignOperator->isDefaulted() &&
15231 CopyAssignOperator->isOverloadedOperator() &&
15232 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15233 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15234 !CopyAssignOperator->isDeleted()) &&
15235 "DefineImplicitCopyAssignment called for wrong function");
15236 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15237 return;
15238
15239 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15240 if (ClassDecl->isInvalidDecl()) {
15241 CopyAssignOperator->setInvalidDecl();
15242 return;
15243 }
15244
15245 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15246
15247 // The exception specification is needed because we are defining the
15248 // function.
15249 ResolveExceptionSpec(Loc: CurrentLocation,
15250 FPT: CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15251
15252 // Add a context note for diagnostics produced after this point.
15253 Scope.addContextNote(UseLoc: CurrentLocation);
15254
15255 // C++11 [class.copy]p18:
15256 // The [definition of an implicitly declared copy assignment operator] is
15257 // deprecated if the class has a user-declared copy constructor or a
15258 // user-declared destructor.
15259 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15260 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyAssignOperator);
15261
15262 // C++0x [class.copy]p30:
15263 // The implicitly-defined or explicitly-defaulted copy assignment operator
15264 // for a non-union class X performs memberwise copy assignment of its
15265 // subobjects. The direct base classes of X are assigned first, in the
15266 // order of their declaration in the base-specifier-list, and then the
15267 // immediate non-static data members of X are assigned, in the order in
15268 // which they were declared in the class definition.
15269
15270 // The statements that form the synthesized function body.
15271 SmallVector<Stmt*, 8> Statements;
15272
15273 // The parameter for the "other" object, which we are copying from.
15274 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15275 Qualifiers OtherQuals = Other->getType().getQualifiers();
15276 QualType OtherRefType = Other->getType();
15277 if (OtherRefType->isLValueReferenceType()) {
15278 OtherRefType = OtherRefType->getPointeeType();
15279 OtherQuals = OtherRefType.getQualifiers();
15280 }
15281
15282 // Our location for everything implicitly-generated.
15283 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15284 ? CopyAssignOperator->getEndLoc()
15285 : CopyAssignOperator->getLocation();
15286
15287 // Builds a DeclRefExpr for the "other" object.
15288 RefBuilder OtherRef(Other, OtherRefType);
15289
15290 // Builds the function object parameter.
15291 std::optional<ThisBuilder> This;
15292 std::optional<DerefBuilder> DerefThis;
15293 std::optional<RefBuilder> ExplicitObject;
15294 bool IsArrow = false;
15295 QualType ObjectType;
15296 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15297 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15298 if (ObjectType->isReferenceType())
15299 ObjectType = ObjectType->getPointeeType();
15300 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15301 } else {
15302 ObjectType = getCurrentThisType();
15303 This.emplace();
15304 DerefThis.emplace(args&: *This);
15305 IsArrow = !LangOpts.HLSL;
15306 }
15307 ExprBuilder &ObjectParameter =
15308 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15309 : static_cast<ExprBuilder &>(*This);
15310
15311 // Assign base classes.
15312 bool Invalid = false;
15313 for (auto &Base : ClassDecl->bases()) {
15314 // Form the assignment:
15315 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15316 QualType BaseType = Base.getType().getUnqualifiedType();
15317 if (!BaseType->isRecordType()) {
15318 Invalid = true;
15319 continue;
15320 }
15321
15322 CXXCastPath BasePath;
15323 BasePath.push_back(Elt: &Base);
15324
15325 // Construct the "from" expression, which is an implicit cast to the
15326 // appropriately-qualified base type.
15327 CastBuilder From(OtherRef, Context.getQualifiedType(T: BaseType, Qs: OtherQuals),
15328 VK_LValue, BasePath);
15329
15330 // Dereference "this".
15331 CastBuilder To(
15332 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15333 : static_cast<ExprBuilder &>(*DerefThis),
15334 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15335 VK_LValue, BasePath);
15336
15337 // Build the copy.
15338 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15339 To, From,
15340 /*CopyingBaseSubobject=*/true,
15341 /*Copying=*/true);
15342 if (Copy.isInvalid()) {
15343 CopyAssignOperator->setInvalidDecl();
15344 return;
15345 }
15346
15347 // Success! Record the copy.
15348 Statements.push_back(Copy.getAs<Expr>());
15349 }
15350
15351 // Assign non-static members.
15352 for (auto *Field : ClassDecl->fields()) {
15353 // FIXME: We should form some kind of AST representation for the implied
15354 // memcpy in a union copy operation.
15355 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15356 continue;
15357
15358 if (Field->isInvalidDecl()) {
15359 Invalid = true;
15360 continue;
15361 }
15362
15363 // Check for members of reference type; we can't copy those.
15364 if (Field->getType()->isReferenceType()) {
15365 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15366 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15367 Diag(Field->getLocation(), diag::note_declared_at);
15368 Invalid = true;
15369 continue;
15370 }
15371
15372 // Check for members of const-qualified, non-class type.
15373 QualType BaseType = Context.getBaseElementType(Field->getType());
15374 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15375 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15376 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15377 Diag(Field->getLocation(), diag::note_declared_at);
15378 Invalid = true;
15379 continue;
15380 }
15381
15382 // Suppress assigning zero-width bitfields.
15383 if (Field->isZeroLengthBitField())
15384 continue;
15385
15386 QualType FieldType = Field->getType().getNonReferenceType();
15387 if (FieldType->isIncompleteArrayType()) {
15388 assert(ClassDecl->hasFlexibleArrayMember() &&
15389 "Incomplete array type is not valid");
15390 continue;
15391 }
15392
15393 // Build references to the field in the object we're copying from and to.
15394 CXXScopeSpec SS; // Intentionally empty
15395 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15396 LookupMemberName);
15397 MemberLookup.addDecl(Field);
15398 MemberLookup.resolveKind();
15399
15400 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15401 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15402 // Build the copy of this field.
15403 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15404 To, From,
15405 /*CopyingBaseSubobject=*/false,
15406 /*Copying=*/true);
15407 if (Copy.isInvalid()) {
15408 CopyAssignOperator->setInvalidDecl();
15409 return;
15410 }
15411
15412 // Success! Record the copy.
15413 Statements.push_back(Copy.getAs<Stmt>());
15414 }
15415
15416 if (!Invalid) {
15417 // Add a "return *this;"
15418 Expr *ThisExpr =
15419 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15420 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15421 : static_cast<ExprBuilder &>(*DerefThis))
15422 .build(*this, Loc);
15423 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15424 if (Return.isInvalid())
15425 Invalid = true;
15426 else
15427 Statements.push_back(Elt: Return.getAs<Stmt>());
15428 }
15429
15430 if (Invalid) {
15431 CopyAssignOperator->setInvalidDecl();
15432 return;
15433 }
15434
15435 StmtResult Body;
15436 {
15437 CompoundScopeRAII CompoundScope(*this);
15438 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15439 /*isStmtExpr=*/false);
15440 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15441 }
15442 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15443 CopyAssignOperator->markUsed(Context);
15444
15445 if (ASTMutationListener *L = getASTMutationListener()) {
15446 L->CompletedImplicitDefinition(CopyAssignOperator);
15447 }
15448}
15449
15450CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15451 assert(ClassDecl->needsImplicitMoveAssignment());
15452
15453 DeclaringSpecialMember DSM(*this, ClassDecl,
15454 CXXSpecialMemberKind::MoveAssignment);
15455 if (DSM.isAlreadyBeingDeclared())
15456 return nullptr;
15457
15458 // Note: The following rules are largely analoguous to the move
15459 // constructor rules.
15460
15461 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15462 ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
15463 NamedType: ArgType, OwnedTagDecl: nullptr);
15464 LangAS AS = getDefaultCXXMethodAddrSpace();
15465 if (AS != LangAS::Default)
15466 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15467 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15468 ArgType = Context.getRValueReferenceType(T: ArgType);
15469
15470 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15471 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, ConstArg: false);
15472
15473 // An implicitly-declared move assignment operator is an inline public
15474 // member of its class.
15475 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15476 SourceLocation ClassLoc = ClassDecl->getLocation();
15477 DeclarationNameInfo NameInfo(Name, ClassLoc);
15478 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15479 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15480 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15481 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15482 /*isInline=*/true,
15483 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15484 EndLocation: SourceLocation());
15485 MoveAssignment->setAccess(AS_public);
15486 MoveAssignment->setDefaulted();
15487 MoveAssignment->setImplicit();
15488
15489 setupImplicitSpecialMemberType(SpecialMem: MoveAssignment, ResultTy: RetType, Args: ArgType);
15490
15491 if (getLangOpts().CUDA)
15492 CUDA().inferTargetForImplicitSpecialMember(
15493 ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, MemberDecl: MoveAssignment,
15494 /* ConstRHS */ false,
15495 /* Diagnose */ false);
15496
15497 // Add the parameter to the operator.
15498 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
15499 ClassLoc, ClassLoc,
15500 /*Id=*/nullptr, ArgType,
15501 /*TInfo=*/nullptr, SC_None,
15502 nullptr);
15503 MoveAssignment->setParams(FromParam);
15504
15505 MoveAssignment->setTrivial(
15506 ClassDecl->needsOverloadResolutionForMoveAssignment()
15507 ? SpecialMemberIsTrivial(MD: MoveAssignment,
15508 CSM: CXXSpecialMemberKind::MoveAssignment)
15509 : ClassDecl->hasTrivialMoveAssignment());
15510
15511 // Note that we have added this copy-assignment operator.
15512 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15513
15514 Scope *S = getScopeForContext(ClassDecl);
15515 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
15516
15517 if (ShouldDeleteSpecialMember(MD: MoveAssignment,
15518 CSM: CXXSpecialMemberKind::MoveAssignment)) {
15519 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15520 SetDeclDeleted(MoveAssignment, ClassLoc);
15521 }
15522
15523 if (S)
15524 PushOnScopeChains(MoveAssignment, S, false);
15525 ClassDecl->addDecl(MoveAssignment);
15526
15527 return MoveAssignment;
15528}
15529
15530/// Check if we're implicitly defining a move assignment operator for a class
15531/// with virtual bases. Such a move assignment might move-assign the virtual
15532/// base multiple times.
15533static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15534 SourceLocation CurrentLocation) {
15535 assert(!Class->isDependentContext() && "should not define dependent move");
15536
15537 // Only a virtual base could get implicitly move-assigned multiple times.
15538 // Only a non-trivial move assignment can observe this. We only want to
15539 // diagnose if we implicitly define an assignment operator that assigns
15540 // two base classes, both of which move-assign the same virtual base.
15541 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15542 Class->getNumBases() < 2)
15543 return;
15544
15545 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15546 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15547 VBaseMap VBases;
15548
15549 for (auto &BI : Class->bases()) {
15550 Worklist.push_back(Elt: &BI);
15551 while (!Worklist.empty()) {
15552 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15553 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15554
15555 // If the base has no non-trivial move assignment operators,
15556 // we don't care about moves from it.
15557 if (!Base->hasNonTrivialMoveAssignment())
15558 continue;
15559
15560 // If there's nothing virtual here, skip it.
15561 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15562 continue;
15563
15564 // If we're not actually going to call a move assignment for this base,
15565 // or the selected move assignment is trivial, skip it.
15566 Sema::SpecialMemberOverloadResult SMOR =
15567 S.LookupSpecialMember(D: Base, SM: CXXSpecialMemberKind::MoveAssignment,
15568 /*ConstArg*/ false, /*VolatileArg*/ false,
15569 /*RValueThis*/ true, /*ConstThis*/ false,
15570 /*VolatileThis*/ false);
15571 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15572 !SMOR.getMethod()->isMoveAssignmentOperator())
15573 continue;
15574
15575 if (BaseSpec->isVirtual()) {
15576 // We're going to move-assign this virtual base, and its move
15577 // assignment operator is not trivial. If this can happen for
15578 // multiple distinct direct bases of Class, diagnose it. (If it
15579 // only happens in one base, we'll diagnose it when synthesizing
15580 // that base class's move assignment operator.)
15581 CXXBaseSpecifier *&Existing =
15582 VBases.insert(KV: std::make_pair(x: Base->getCanonicalDecl(), y: &BI))
15583 .first->second;
15584 if (Existing && Existing != &BI) {
15585 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15586 << Class << Base;
15587 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15588 << (Base->getCanonicalDecl() ==
15589 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15590 << Base << Existing->getType() << Existing->getSourceRange();
15591 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15592 << (Base->getCanonicalDecl() ==
15593 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15594 << Base << BI.getType() << BaseSpec->getSourceRange();
15595
15596 // Only diagnose each vbase once.
15597 Existing = nullptr;
15598 }
15599 } else {
15600 // Only walk over bases that have defaulted move assignment operators.
15601 // We assume that any user-provided move assignment operator handles
15602 // the multiple-moves-of-vbase case itself somehow.
15603 if (!SMOR.getMethod()->isDefaulted())
15604 continue;
15605
15606 // We're going to move the base classes of Base. Add them to the list.
15607 llvm::append_range(C&: Worklist, R: llvm::make_pointer_range(Range: Base->bases()));
15608 }
15609 }
15610 }
15611}
15612
15613void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15614 CXXMethodDecl *MoveAssignOperator) {
15615 assert((MoveAssignOperator->isDefaulted() &&
15616 MoveAssignOperator->isOverloadedOperator() &&
15617 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15618 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15619 !MoveAssignOperator->isDeleted()) &&
15620 "DefineImplicitMoveAssignment called for wrong function");
15621 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15622 return;
15623
15624 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15625 if (ClassDecl->isInvalidDecl()) {
15626 MoveAssignOperator->setInvalidDecl();
15627 return;
15628 }
15629
15630 // C++0x [class.copy]p28:
15631 // The implicitly-defined or move assignment operator for a non-union class
15632 // X performs memberwise move assignment of its subobjects. The direct base
15633 // classes of X are assigned first, in the order of their declaration in the
15634 // base-specifier-list, and then the immediate non-static data members of X
15635 // are assigned, in the order in which they were declared in the class
15636 // definition.
15637
15638 // Issue a warning if our implicit move assignment operator will move
15639 // from a virtual base more than once.
15640 checkMoveAssignmentForRepeatedMove(S&: *this, Class: ClassDecl, CurrentLocation);
15641
15642 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15643
15644 // The exception specification is needed because we are defining the
15645 // function.
15646 ResolveExceptionSpec(Loc: CurrentLocation,
15647 FPT: MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15648
15649 // Add a context note for diagnostics produced after this point.
15650 Scope.addContextNote(UseLoc: CurrentLocation);
15651
15652 // The statements that form the synthesized function body.
15653 SmallVector<Stmt*, 8> Statements;
15654
15655 // The parameter for the "other" object, which we are move from.
15656 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15657 QualType OtherRefType =
15658 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15659
15660 // Our location for everything implicitly-generated.
15661 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15662 ? MoveAssignOperator->getEndLoc()
15663 : MoveAssignOperator->getLocation();
15664
15665 // Builds a reference to the "other" object.
15666 RefBuilder OtherRef(Other, OtherRefType);
15667 // Cast to rvalue.
15668 MoveCastBuilder MoveOther(OtherRef);
15669
15670 // Builds the function object parameter.
15671 std::optional<ThisBuilder> This;
15672 std::optional<DerefBuilder> DerefThis;
15673 std::optional<RefBuilder> ExplicitObject;
15674 QualType ObjectType;
15675 bool IsArrow = false;
15676 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15677 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15678 if (ObjectType->isReferenceType())
15679 ObjectType = ObjectType->getPointeeType();
15680 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15681 } else {
15682 ObjectType = getCurrentThisType();
15683 This.emplace();
15684 DerefThis.emplace(args&: *This);
15685 IsArrow = !getLangOpts().HLSL;
15686 }
15687 ExprBuilder &ObjectParameter =
15688 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15689
15690 // Assign base classes.
15691 bool Invalid = false;
15692 for (auto &Base : ClassDecl->bases()) {
15693 // C++11 [class.copy]p28:
15694 // It is unspecified whether subobjects representing virtual base classes
15695 // are assigned more than once by the implicitly-defined copy assignment
15696 // operator.
15697 // FIXME: Do not assign to a vbase that will be assigned by some other base
15698 // class. For a move-assignment, this can result in the vbase being moved
15699 // multiple times.
15700
15701 // Form the assignment:
15702 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15703 QualType BaseType = Base.getType().getUnqualifiedType();
15704 if (!BaseType->isRecordType()) {
15705 Invalid = true;
15706 continue;
15707 }
15708
15709 CXXCastPath BasePath;
15710 BasePath.push_back(Elt: &Base);
15711
15712 // Construct the "from" expression, which is an implicit cast to the
15713 // appropriately-qualified base type.
15714 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15715
15716 // Implicitly cast "this" to the appropriately-qualified base type.
15717 // Dereference "this".
15718 CastBuilder To(
15719 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15720 : static_cast<ExprBuilder &>(*DerefThis),
15721 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15722 VK_LValue, BasePath);
15723
15724 // Build the move.
15725 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15726 To, From,
15727 /*CopyingBaseSubobject=*/true,
15728 /*Copying=*/false);
15729 if (Move.isInvalid()) {
15730 MoveAssignOperator->setInvalidDecl();
15731 return;
15732 }
15733
15734 // Success! Record the move.
15735 Statements.push_back(Move.getAs<Expr>());
15736 }
15737
15738 // Assign non-static members.
15739 for (auto *Field : ClassDecl->fields()) {
15740 // FIXME: We should form some kind of AST representation for the implied
15741 // memcpy in a union copy operation.
15742 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15743 continue;
15744
15745 if (Field->isInvalidDecl()) {
15746 Invalid = true;
15747 continue;
15748 }
15749
15750 // Check for members of reference type; we can't move those.
15751 if (Field->getType()->isReferenceType()) {
15752 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15753 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15754 Diag(Field->getLocation(), diag::note_declared_at);
15755 Invalid = true;
15756 continue;
15757 }
15758
15759 // Check for members of const-qualified, non-class type.
15760 QualType BaseType = Context.getBaseElementType(Field->getType());
15761 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15762 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15763 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15764 Diag(Field->getLocation(), diag::note_declared_at);
15765 Invalid = true;
15766 continue;
15767 }
15768
15769 // Suppress assigning zero-width bitfields.
15770 if (Field->isZeroLengthBitField())
15771 continue;
15772
15773 QualType FieldType = Field->getType().getNonReferenceType();
15774 if (FieldType->isIncompleteArrayType()) {
15775 assert(ClassDecl->hasFlexibleArrayMember() &&
15776 "Incomplete array type is not valid");
15777 continue;
15778 }
15779
15780 // Build references to the field in the object we're copying from and to.
15781 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15782 LookupMemberName);
15783 MemberLookup.addDecl(Field);
15784 MemberLookup.resolveKind();
15785 MemberBuilder From(MoveOther, OtherRefType,
15786 /*IsArrow=*/false, MemberLookup);
15787 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15788
15789 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15790 "Member reference with rvalue base must be rvalue except for reference "
15791 "members, which aren't allowed for move assignment.");
15792
15793 // Build the move of this field.
15794 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15795 To, From,
15796 /*CopyingBaseSubobject=*/false,
15797 /*Copying=*/false);
15798 if (Move.isInvalid()) {
15799 MoveAssignOperator->setInvalidDecl();
15800 return;
15801 }
15802
15803 // Success! Record the copy.
15804 Statements.push_back(Move.getAs<Stmt>());
15805 }
15806
15807 if (!Invalid) {
15808 // Add a "return *this;"
15809 Expr *ThisExpr =
15810 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15811 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15812 : static_cast<ExprBuilder &>(*DerefThis))
15813 .build(S&: *this, Loc);
15814
15815 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15816 if (Return.isInvalid())
15817 Invalid = true;
15818 else
15819 Statements.push_back(Elt: Return.getAs<Stmt>());
15820 }
15821
15822 if (Invalid) {
15823 MoveAssignOperator->setInvalidDecl();
15824 return;
15825 }
15826
15827 StmtResult Body;
15828 {
15829 CompoundScopeRAII CompoundScope(*this);
15830 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15831 /*isStmtExpr=*/false);
15832 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15833 }
15834 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15835 MoveAssignOperator->markUsed(Context);
15836
15837 if (ASTMutationListener *L = getASTMutationListener()) {
15838 L->CompletedImplicitDefinition(MoveAssignOperator);
15839 }
15840}
15841
15842CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15843 CXXRecordDecl *ClassDecl) {
15844 // C++ [class.copy]p4:
15845 // If the class definition does not explicitly declare a copy
15846 // constructor, one is declared implicitly.
15847 assert(ClassDecl->needsImplicitCopyConstructor());
15848
15849 DeclaringSpecialMember DSM(*this, ClassDecl,
15850 CXXSpecialMemberKind::CopyConstructor);
15851 if (DSM.isAlreadyBeingDeclared())
15852 return nullptr;
15853
15854 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15855 QualType ArgType = ClassType;
15856 ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
15857 NamedType: ArgType, OwnedTagDecl: nullptr);
15858 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15859 if (Const)
15860 ArgType = ArgType.withConst();
15861
15862 LangAS AS = getDefaultCXXMethodAddrSpace();
15863 if (AS != LangAS::Default)
15864 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15865
15866 ArgType = Context.getLValueReferenceType(T: ArgType);
15867
15868 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15869 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Const);
15870
15871 DeclarationName Name
15872 = Context.DeclarationNames.getCXXConstructorName(
15873 Ty: Context.getCanonicalType(T: ClassType));
15874 SourceLocation ClassLoc = ClassDecl->getLocation();
15875 DeclarationNameInfo NameInfo(Name, ClassLoc);
15876
15877 // An implicitly-declared copy constructor is an inline public
15878 // member of its class.
15879 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15880 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
15881 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15882 /*isInline=*/true,
15883 /*isImplicitlyDeclared=*/true,
15884 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
15885 : ConstexprSpecKind::Unspecified);
15886 CopyConstructor->setAccess(AS_public);
15887 CopyConstructor->setDefaulted();
15888
15889 setupImplicitSpecialMemberType(SpecialMem: CopyConstructor, ResultTy: Context.VoidTy, Args: ArgType);
15890
15891 if (getLangOpts().CUDA)
15892 CUDA().inferTargetForImplicitSpecialMember(
15893 ClassDecl, CXXSpecialMemberKind::CopyConstructor, CopyConstructor,
15894 /* ConstRHS */ Const,
15895 /* Diagnose */ false);
15896
15897 // During template instantiation of special member functions we need a
15898 // reliable TypeSourceInfo for the parameter types in order to allow functions
15899 // to be substituted.
15900 TypeSourceInfo *TSI = nullptr;
15901 if (inTemplateInstantiation() && ClassDecl->isLambda())
15902 TSI = Context.getTrivialTypeSourceInfo(T: ArgType);
15903
15904 // Add the parameter to the constructor.
15905 ParmVarDecl *FromParam =
15906 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15907 /*IdentifierInfo=*/nullptr, ArgType,
15908 /*TInfo=*/TSI, SC_None, nullptr);
15909 CopyConstructor->setParams(FromParam);
15910
15911 CopyConstructor->setTrivial(
15912 ClassDecl->needsOverloadResolutionForCopyConstructor()
15913 ? SpecialMemberIsTrivial(CopyConstructor,
15914 CXXSpecialMemberKind::CopyConstructor)
15915 : ClassDecl->hasTrivialCopyConstructor());
15916
15917 CopyConstructor->setTrivialForCall(
15918 ClassDecl->hasAttr<TrivialABIAttr>() ||
15919 (ClassDecl->needsOverloadResolutionForCopyConstructor()
15920 ? SpecialMemberIsTrivial(CopyConstructor,
15921 CXXSpecialMemberKind::CopyConstructor,
15922 TrivialABIHandling::ConsiderTrivialABI)
15923 : ClassDecl->hasTrivialCopyConstructorForCall()));
15924
15925 // Note that we have declared this constructor.
15926 ++getASTContext().NumImplicitCopyConstructorsDeclared;
15927
15928 Scope *S = getScopeForContext(ClassDecl);
15929 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15930
15931 if (ShouldDeleteSpecialMember(CopyConstructor,
15932 CXXSpecialMemberKind::CopyConstructor)) {
15933 ClassDecl->setImplicitCopyConstructorIsDeleted();
15934 SetDeclDeleted(CopyConstructor, ClassLoc);
15935 }
15936
15937 if (S)
15938 PushOnScopeChains(CopyConstructor, S, false);
15939 ClassDecl->addDecl(CopyConstructor);
15940
15941 return CopyConstructor;
15942}
15943
15944void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15945 CXXConstructorDecl *CopyConstructor) {
15946 assert((CopyConstructor->isDefaulted() &&
15947 CopyConstructor->isCopyConstructor() &&
15948 !CopyConstructor->doesThisDeclarationHaveABody() &&
15949 !CopyConstructor->isDeleted()) &&
15950 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15951 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15952 return;
15953
15954 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15955 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15956
15957 SynthesizedFunctionScope Scope(*this, CopyConstructor);
15958
15959 // The exception specification is needed because we are defining the
15960 // function.
15961 ResolveExceptionSpec(Loc: CurrentLocation,
15962 FPT: CopyConstructor->getType()->castAs<FunctionProtoType>());
15963 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
15964
15965 // Add a context note for diagnostics produced after this point.
15966 Scope.addContextNote(UseLoc: CurrentLocation);
15967
15968 // C++11 [class.copy]p7:
15969 // The [definition of an implicitly declared copy constructor] is
15970 // deprecated if the class has a user-declared copy assignment operator
15971 // or a user-declared destructor.
15972 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15973 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15974
15975 if (SetCtorInitializers(Constructor: CopyConstructor, /*AnyErrors=*/false)) {
15976 CopyConstructor->setInvalidDecl();
15977 } else {
15978 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15979 ? CopyConstructor->getEndLoc()
15980 : CopyConstructor->getLocation();
15981 Sema::CompoundScopeRAII CompoundScope(*this);
15982 CopyConstructor->setBody(
15983 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
15984 CopyConstructor->markUsed(Context);
15985 }
15986
15987 if (ASTMutationListener *L = getASTMutationListener()) {
15988 L->CompletedImplicitDefinition(CopyConstructor);
15989 }
15990}
15991
15992CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15993 CXXRecordDecl *ClassDecl) {
15994 assert(ClassDecl->needsImplicitMoveConstructor());
15995
15996 DeclaringSpecialMember DSM(*this, ClassDecl,
15997 CXXSpecialMemberKind::MoveConstructor);
15998 if (DSM.isAlreadyBeingDeclared())
15999 return nullptr;
16000
16001 QualType ClassType = Context.getTypeDeclType(ClassDecl);
16002
16003 QualType ArgType = ClassType;
16004 ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
16005 NamedType: ArgType, OwnedTagDecl: nullptr);
16006 LangAS AS = getDefaultCXXMethodAddrSpace();
16007 if (AS != LangAS::Default)
16008 ArgType = Context.getAddrSpaceQualType(T: ClassType, AddressSpace: AS);
16009 ArgType = Context.getRValueReferenceType(T: ArgType);
16010
16011 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16012 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, ConstArg: false);
16013
16014 DeclarationName Name
16015 = Context.DeclarationNames.getCXXConstructorName(
16016 Ty: Context.getCanonicalType(T: ClassType));
16017 SourceLocation ClassLoc = ClassDecl->getLocation();
16018 DeclarationNameInfo NameInfo(Name, ClassLoc);
16019
16020 // C++11 [class.copy]p11:
16021 // An implicitly-declared copy/move constructor is an inline public
16022 // member of its class.
16023 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
16024 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16025 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16026 /*isInline=*/true,
16027 /*isImplicitlyDeclared=*/true,
16028 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16029 : ConstexprSpecKind::Unspecified);
16030 MoveConstructor->setAccess(AS_public);
16031 MoveConstructor->setDefaulted();
16032
16033 setupImplicitSpecialMemberType(SpecialMem: MoveConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16034
16035 if (getLangOpts().CUDA)
16036 CUDA().inferTargetForImplicitSpecialMember(
16037 ClassDecl, CXXSpecialMemberKind::MoveConstructor, MoveConstructor,
16038 /* ConstRHS */ false,
16039 /* Diagnose */ false);
16040
16041 // Add the parameter to the constructor.
16042 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
16043 ClassLoc, ClassLoc,
16044 /*IdentifierInfo=*/nullptr,
16045 ArgType, /*TInfo=*/nullptr,
16046 SC_None, nullptr);
16047 MoveConstructor->setParams(FromParam);
16048
16049 MoveConstructor->setTrivial(
16050 ClassDecl->needsOverloadResolutionForMoveConstructor()
16051 ? SpecialMemberIsTrivial(MoveConstructor,
16052 CXXSpecialMemberKind::MoveConstructor)
16053 : ClassDecl->hasTrivialMoveConstructor());
16054
16055 MoveConstructor->setTrivialForCall(
16056 ClassDecl->hasAttr<TrivialABIAttr>() ||
16057 (ClassDecl->needsOverloadResolutionForMoveConstructor()
16058 ? SpecialMemberIsTrivial(MoveConstructor,
16059 CXXSpecialMemberKind::MoveConstructor,
16060 TrivialABIHandling::ConsiderTrivialABI)
16061 : ClassDecl->hasTrivialMoveConstructorForCall()));
16062
16063 // Note that we have declared this constructor.
16064 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16065
16066 Scope *S = getScopeForContext(ClassDecl);
16067 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
16068
16069 if (ShouldDeleteSpecialMember(MoveConstructor,
16070 CXXSpecialMemberKind::MoveConstructor)) {
16071 ClassDecl->setImplicitMoveConstructorIsDeleted();
16072 SetDeclDeleted(MoveConstructor, ClassLoc);
16073 }
16074
16075 if (S)
16076 PushOnScopeChains(MoveConstructor, S, false);
16077 ClassDecl->addDecl(MoveConstructor);
16078
16079 return MoveConstructor;
16080}
16081
16082void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
16083 CXXConstructorDecl *MoveConstructor) {
16084 assert((MoveConstructor->isDefaulted() &&
16085 MoveConstructor->isMoveConstructor() &&
16086 !MoveConstructor->doesThisDeclarationHaveABody() &&
16087 !MoveConstructor->isDeleted()) &&
16088 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16089 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16090 return;
16091
16092 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16093 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16094
16095 SynthesizedFunctionScope Scope(*this, MoveConstructor);
16096
16097 // The exception specification is needed because we are defining the
16098 // function.
16099 ResolveExceptionSpec(Loc: CurrentLocation,
16100 FPT: MoveConstructor->getType()->castAs<FunctionProtoType>());
16101 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16102
16103 // Add a context note for diagnostics produced after this point.
16104 Scope.addContextNote(UseLoc: CurrentLocation);
16105
16106 if (SetCtorInitializers(Constructor: MoveConstructor, /*AnyErrors=*/false)) {
16107 MoveConstructor->setInvalidDecl();
16108 } else {
16109 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16110 ? MoveConstructor->getEndLoc()
16111 : MoveConstructor->getLocation();
16112 Sema::CompoundScopeRAII CompoundScope(*this);
16113 MoveConstructor->setBody(
16114 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16115 MoveConstructor->markUsed(Context);
16116 }
16117
16118 if (ASTMutationListener *L = getASTMutationListener()) {
16119 L->CompletedImplicitDefinition(MoveConstructor);
16120 }
16121}
16122
16123bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
16124 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD);
16125}
16126
16127void Sema::DefineImplicitLambdaToFunctionPointerConversion(
16128 SourceLocation CurrentLocation,
16129 CXXConversionDecl *Conv) {
16130 SynthesizedFunctionScope Scope(*this, Conv);
16131 assert(!Conv->getReturnType()->isUndeducedType());
16132
16133 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16134 CallingConv CC =
16135 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16136
16137 CXXRecordDecl *Lambda = Conv->getParent();
16138 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16139 FunctionDecl *Invoker =
16140 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16141 ? CallOp
16142 : Lambda->getLambdaStaticInvoker(CC);
16143
16144 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16145 CallOp = InstantiateFunctionDeclaration(
16146 FTD: CallOp->getDescribedFunctionTemplate(), Args: TemplateArgs, Loc: CurrentLocation);
16147 if (!CallOp)
16148 return;
16149
16150 if (CallOp != Invoker) {
16151 Invoker = InstantiateFunctionDeclaration(
16152 FTD: Invoker->getDescribedFunctionTemplate(), Args: TemplateArgs,
16153 Loc: CurrentLocation);
16154 if (!Invoker)
16155 return;
16156 }
16157 }
16158
16159 if (CallOp->isInvalidDecl())
16160 return;
16161
16162 // Mark the call operator referenced (and add to pending instantiations
16163 // if necessary).
16164 // For both the conversion and static-invoker template specializations
16165 // we construct their body's in this function, so no need to add them
16166 // to the PendingInstantiations.
16167 MarkFunctionReferenced(Loc: CurrentLocation, Func: CallOp);
16168
16169 if (Invoker != CallOp) {
16170 // Fill in the __invoke function with a dummy implementation. IR generation
16171 // will fill in the actual details. Update its type in case it contained
16172 // an 'auto'.
16173 Invoker->markUsed(Context);
16174 Invoker->setReferenced();
16175 Invoker->setType(Conv->getReturnType()->getPointeeType());
16176 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16177 }
16178
16179 // Construct the body of the conversion function { return __invoke; }.
16180 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16181 Conv->getLocation());
16182 assert(FunctionRef && "Can't refer to __invoke function?");
16183 Stmt *Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: FunctionRef).get();
16184 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: Return, FPFeatures: FPOptionsOverride(),
16185 LB: Conv->getLocation(), RB: Conv->getLocation()));
16186 Conv->markUsed(Context);
16187 Conv->setReferenced();
16188
16189 if (ASTMutationListener *L = getASTMutationListener()) {
16190 L->CompletedImplicitDefinition(Conv);
16191 if (Invoker != CallOp)
16192 L->CompletedImplicitDefinition(D: Invoker);
16193 }
16194}
16195
16196void Sema::DefineImplicitLambdaToBlockPointerConversion(
16197 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16198 assert(!Conv->getParent()->isGenericLambda());
16199
16200 SynthesizedFunctionScope Scope(*this, Conv);
16201
16202 // Copy-initialize the lambda object as needed to capture it.
16203 Expr *This = ActOnCXXThis(Loc: CurrentLocation).get();
16204 Expr *DerefThis =CreateBuiltinUnaryOp(OpLoc: CurrentLocation, Opc: UO_Deref, InputExpr: This).get();
16205
16206 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16207 ConvLocation: Conv->getLocation(),
16208 Conv, Src: DerefThis);
16209
16210 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16211 // behavior. Note that only the general conversion function does this
16212 // (since it's unusable otherwise); in the case where we inline the
16213 // block literal, it has block literal lifetime semantics.
16214 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16215 BuildBlock = ImplicitCastExpr::Create(
16216 Context, T: BuildBlock.get()->getType(), Kind: CK_CopyAndAutoreleaseBlockObject,
16217 Operand: BuildBlock.get(), BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
16218
16219 if (BuildBlock.isInvalid()) {
16220 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16221 Conv->setInvalidDecl();
16222 return;
16223 }
16224
16225 // Create the return statement that returns the block from the conversion
16226 // function.
16227 StmtResult Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: BuildBlock.get());
16228 if (Return.isInvalid()) {
16229 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16230 Conv->setInvalidDecl();
16231 return;
16232 }
16233
16234 // Set the body of the conversion function.
16235 Stmt *ReturnS = Return.get();
16236 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: ReturnS, FPFeatures: FPOptionsOverride(),
16237 LB: Conv->getLocation(), RB: Conv->getLocation()));
16238 Conv->markUsed(Context);
16239
16240 // We're done; notify the mutation listener, if any.
16241 if (ASTMutationListener *L = getASTMutationListener()) {
16242 L->CompletedImplicitDefinition(Conv);
16243 }
16244}
16245
16246/// Determine whether the given list arguments contains exactly one
16247/// "real" (non-default) argument.
16248static bool hasOneRealArgument(MultiExprArg Args) {
16249 switch (Args.size()) {
16250 case 0:
16251 return false;
16252
16253 default:
16254 if (!Args[1]->isDefaultArgument())
16255 return false;
16256
16257 [[fallthrough]];
16258 case 1:
16259 return !Args[0]->isDefaultArgument();
16260 }
16261
16262 return false;
16263}
16264
16265ExprResult Sema::BuildCXXConstructExpr(
16266 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16267 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16268 bool HadMultipleCandidates, bool IsListInitialization,
16269 bool IsStdInitListInitialization, bool RequiresZeroInit,
16270 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16271 bool Elidable = false;
16272
16273 // C++0x [class.copy]p34:
16274 // When certain criteria are met, an implementation is allowed to
16275 // omit the copy/move construction of a class object, even if the
16276 // copy/move constructor and/or destructor for the object have
16277 // side effects. [...]
16278 // - when a temporary class object that has not been bound to a
16279 // reference (12.2) would be copied/moved to a class object
16280 // with the same cv-unqualified type, the copy/move operation
16281 // can be omitted by constructing the temporary object
16282 // directly into the target of the omitted copy/move
16283 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16284 // FIXME: Converting constructors should also be accepted.
16285 // But to fix this, the logic that digs down into a CXXConstructExpr
16286 // to find the source object needs to handle it.
16287 // Right now it assumes the source object is passed directly as the
16288 // first argument.
16289 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(Args: ExprArgs)) {
16290 Expr *SubExpr = ExprArgs[0];
16291 // FIXME: Per above, this is also incorrect if we want to accept
16292 // converting constructors, as isTemporaryObject will
16293 // reject temporaries with different type from the
16294 // CXXRecord itself.
16295 Elidable = SubExpr->isTemporaryObject(
16296 Ctx&: Context, TempTy: cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
16297 }
16298
16299 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16300 FoundDecl, Constructor,
16301 Elidable, Exprs: ExprArgs, HadMultipleCandidates,
16302 IsListInitialization,
16303 IsStdInitListInitialization, RequiresZeroInit,
16304 ConstructKind, ParenRange);
16305}
16306
16307ExprResult Sema::BuildCXXConstructExpr(
16308 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16309 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16310 bool HadMultipleCandidates, bool IsListInitialization,
16311 bool IsStdInitListInitialization, bool RequiresZeroInit,
16312 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16313 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl)) {
16314 Constructor = findInheritingConstructor(Loc: ConstructLoc, BaseCtor: Constructor, Shadow);
16315 // The only way to get here is if we did overload resolution to find the
16316 // shadow decl, so we don't need to worry about re-checking the trailing
16317 // requires clause.
16318 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16319 return ExprError();
16320 }
16321
16322 return BuildCXXConstructExpr(
16323 ConstructLoc, DeclInitType, Constructor, Elidable, Exprs: ExprArgs,
16324 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16325 RequiresZeroInit, ConstructKind, ParenRange);
16326}
16327
16328/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16329/// including handling of its default argument expressions.
16330ExprResult Sema::BuildCXXConstructExpr(
16331 SourceLocation ConstructLoc, QualType DeclInitType,
16332 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16333 bool HadMultipleCandidates, bool IsListInitialization,
16334 bool IsStdInitListInitialization, bool RequiresZeroInit,
16335 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16336 assert(declaresSameEntity(
16337 Constructor->getParent(),
16338 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16339 "given constructor for wrong type");
16340 MarkFunctionReferenced(ConstructLoc, Constructor);
16341 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16342 return ExprError();
16343
16344 return CheckForImmediateInvocation(
16345 CXXConstructExpr::Create(
16346 Ctx: Context, Ty: DeclInitType, Loc: ConstructLoc, Ctor: Constructor, Elidable, Args: ExprArgs,
16347 HadMultipleCandidates, ListInitialization: IsListInitialization,
16348 StdInitListInitialization: IsStdInitListInitialization, ZeroInitialization: RequiresZeroInit,
16349 ConstructKind: static_cast<CXXConstructionKind>(ConstructKind), ParenOrBraceRange: ParenRange),
16350 Constructor);
16351}
16352
16353void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
16354 if (VD->isInvalidDecl()) return;
16355 // If initializing the variable failed, don't also diagnose problems with
16356 // the destructor, they're likely related.
16357 if (VD->getInit() && VD->getInit()->containsErrors())
16358 return;
16359
16360 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Record->getDecl());
16361 if (ClassDecl->isInvalidDecl()) return;
16362 if (ClassDecl->hasIrrelevantDestructor()) return;
16363 if (ClassDecl->isDependentContext()) return;
16364
16365 if (VD->isNoDestroy(getASTContext()))
16366 return;
16367
16368 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
16369 // The result of `LookupDestructor` might be nullptr if the destructor is
16370 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16371 // will not be selected by `CXXRecordDecl::getDestructor()`.
16372 if (!Destructor)
16373 return;
16374 // If this is an array, we'll require the destructor during initialization, so
16375 // we can skip over this. We still want to emit exit-time destructor warnings
16376 // though.
16377 if (!VD->getType()->isArrayType()) {
16378 MarkFunctionReferenced(Loc: VD->getLocation(), Func: Destructor);
16379 CheckDestructorAccess(VD->getLocation(), Destructor,
16380 PDiag(diag::err_access_dtor_var)
16381 << VD->getDeclName() << VD->getType());
16382 DiagnoseUseOfDecl(D: Destructor, Locs: VD->getLocation());
16383 }
16384
16385 if (Destructor->isTrivial()) return;
16386
16387 // If the destructor is constexpr, check whether the variable has constant
16388 // destruction now.
16389 if (Destructor->isConstexpr()) {
16390 bool HasConstantInit = false;
16391 if (VD->getInit() && !VD->getInit()->isValueDependent())
16392 HasConstantInit = VD->evaluateValue();
16393 SmallVector<PartialDiagnosticAt, 8> Notes;
16394 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16395 HasConstantInit) {
16396 Diag(VD->getLocation(),
16397 diag::err_constexpr_var_requires_const_destruction) << VD;
16398 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16399 Diag(Notes[I].first, Notes[I].second);
16400 }
16401 }
16402
16403 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Ctx: Context))
16404 return;
16405
16406 // Emit warning for non-trivial dtor in global scope (a real global,
16407 // class-static, function-static).
16408 if (!VD->hasAttr<AlwaysDestroyAttr>())
16409 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16410
16411 // TODO: this should be re-enabled for static locals by !CXAAtExit
16412 if (!VD->isStaticLocal())
16413 Diag(VD->getLocation(), diag::warn_global_destructor);
16414}
16415
16416bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16417 QualType DeclInitType, MultiExprArg ArgsPtr,
16418 SourceLocation Loc,
16419 SmallVectorImpl<Expr *> &ConvertedArgs,
16420 bool AllowExplicit,
16421 bool IsListInitialization) {
16422 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16423 unsigned NumArgs = ArgsPtr.size();
16424 Expr **Args = ArgsPtr.data();
16425
16426 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16427 unsigned NumParams = Proto->getNumParams();
16428
16429 // If too few arguments are available, we'll fill in the rest with defaults.
16430 if (NumArgs < NumParams)
16431 ConvertedArgs.reserve(N: NumParams);
16432 else
16433 ConvertedArgs.reserve(N: NumArgs);
16434
16435 VariadicCallType CallType = Proto->isVariadic()
16436 ? VariadicCallType::Constructor
16437 : VariadicCallType::DoesNotApply;
16438 SmallVector<Expr *, 8> AllArgs;
16439 bool Invalid = GatherArgumentsForCall(
16440 CallLoc: Loc, FDecl: Constructor, Proto: Proto, FirstParam: 0, Args: llvm::ArrayRef(Args, NumArgs), AllArgs,
16441 CallType, AllowExplicit, IsListInitialization);
16442 ConvertedArgs.append(in_start: AllArgs.begin(), in_end: AllArgs.end());
16443
16444 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16445
16446 CheckConstructorCall(FDecl: Constructor, ThisType: DeclInitType,
16447 Args: llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto: Proto,
16448 Loc);
16449
16450 return Invalid;
16451}
16452
16453TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {
16454 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16455 return typeAwareAllocationModeFromBool(IsTypeAwareAllocation: SeenTypedOperators);
16456}
16457
16458FunctionDecl *
16459Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,
16460 QualType DeallocType, SourceLocation Loc) {
16461 if (DeallocType.isNull())
16462 return nullptr;
16463
16464 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16465 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16466 return nullptr;
16467
16468 if (FnDecl->isVariadic())
16469 return nullptr;
16470
16471 unsigned NumParams = FnDecl->getNumParams();
16472 constexpr unsigned RequiredParameterCount =
16473 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16474 // A usual deallocation function has no placement parameters
16475 if (NumParams != RequiredParameterCount)
16476 return nullptr;
16477
16478 // A type aware allocation is only usual if the only dependent parameter is
16479 // the first parameter.
16480 if (llvm::any_of(Range: FnDecl->parameters().drop_front(),
16481 P: [](const ParmVarDecl *ParamDecl) {
16482 return ParamDecl->getType()->isDependentType();
16483 }))
16484 return nullptr;
16485
16486 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(Type: DeallocType, Loc);
16487 if (SpecializedTypeIdentity.isNull())
16488 return nullptr;
16489
16490 SmallVector<QualType, RequiredParameterCount> ArgTypes;
16491 ArgTypes.reserve(N: NumParams);
16492
16493 // The first parameter to a type aware operator delete is by definition the
16494 // type-identity argument, so we explicitly set this to the target
16495 // type-identity type, the remaining usual parameters should then simply match
16496 // the type declared in the function template.
16497 ArgTypes.push_back(Elt: SpecializedTypeIdentity);
16498 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16499 ArgTypes.push_back(Elt: FnDecl->getParamDecl(i: ParamIdx)->getType());
16500
16501 FunctionProtoType::ExtProtoInfo EPI;
16502 QualType ExpectedFunctionType =
16503 Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI);
16504 sema::TemplateDeductionInfo Info(Loc);
16505 FunctionDecl *Result;
16506 if (DeduceTemplateArguments(FunctionTemplate: FnTemplateDecl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType,
16507 Specialization&: Result, Info) != TemplateDeductionResult::Success)
16508 return nullptr;
16509 return Result;
16510}
16511
16512static inline bool
16513CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16514 const FunctionDecl *FnDecl) {
16515 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16516 if (isa<NamespaceDecl>(Val: DC)) {
16517 return SemaRef.Diag(FnDecl->getLocation(),
16518 diag::err_operator_new_delete_declared_in_namespace)
16519 << FnDecl->getDeclName();
16520 }
16521
16522 if (isa<TranslationUnitDecl>(Val: DC) &&
16523 FnDecl->getStorageClass() == SC_Static) {
16524 return SemaRef.Diag(FnDecl->getLocation(),
16525 diag::err_operator_new_delete_declared_static)
16526 << FnDecl->getDeclName();
16527 }
16528
16529 return false;
16530}
16531
16532static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16533 const PointerType *PtrTy) {
16534 auto &Ctx = SemaRef.Context;
16535 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16536 PtrQuals.removeAddressSpace();
16537 return Ctx.getPointerType(T: Ctx.getCanonicalType(T: Ctx.getQualifiedType(
16538 T: PtrTy->getPointeeType().getUnqualifiedType(), Qs: PtrQuals)));
16539}
16540
16541enum class AllocationOperatorKind { New, Delete };
16542
16543static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
16544 const FunctionDecl *FD,
16545 bool *WasMalformed) {
16546 const Decl *MalformedDecl = nullptr;
16547 if (FD->getNumParams() > 0 &&
16548 SemaRef.isStdTypeIdentity(Ty: FD->getParamDecl(i: 0)->getType(),
16549 /*TypeArgument=*/Element: nullptr, MalformedDecl: &MalformedDecl))
16550 return true;
16551
16552 if (!MalformedDecl)
16553 return false;
16554
16555 if (WasMalformed)
16556 *WasMalformed = true;
16557
16558 return true;
16559}
16560
16561static bool isDestroyingDeleteT(QualType Type) {
16562 auto *RD = Type->getAsCXXRecordDecl();
16563 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16564 RD->getIdentifier()->isStr("destroying_delete_t");
16565}
16566
16567static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
16568 const FunctionDecl *FD) {
16569 // C++ P0722:
16570 // Within a class C, a single object deallocation function with signature
16571 // (T, std::destroying_delete_t, <more params>)
16572 // is a destroying operator delete.
16573 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16574 SemaRef, FD, /*WasMalformed=*/nullptr);
16575 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16576 return isa<CXXMethodDecl>(Val: FD) && FD->getOverloadedOperator() == OO_Delete &&
16577 FD->getNumParams() > DestroyingDeleteIdx &&
16578 isDestroyingDeleteT(FD->getParamDecl(i: DestroyingDeleteIdx)->getType());
16579}
16580
16581static inline bool CheckOperatorNewDeleteTypes(
16582 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16583 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16584 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16585 auto NormalizeType = [&SemaRef](QualType T) {
16586 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16587 // The operator is valid on any address space for OpenCL.
16588 // Drop address space from actual and expected result types.
16589 if (const auto PtrTy = T->template getAs<PointerType>())
16590 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16591 }
16592 return SemaRef.Context.getCanonicalType(T);
16593 };
16594
16595 const unsigned NumParams = FnDecl->getNumParams();
16596 unsigned FirstNonTypeParam = 0;
16597 bool MalformedTypeIdentity = false;
16598 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16599 SemaRef, FD: FnDecl, WasMalformed: &MalformedTypeIdentity);
16600 unsigned MinimumMandatoryArgumentCount = 1;
16601 unsigned SizeParameterIndex = 0;
16602 if (IsPotentiallyTypeAware) {
16603 // We don't emit this diagnosis for template instantiations as we will
16604 // have already emitted it for the original template declaration.
16605 if (!FnDecl->isTemplateInstantiation()) {
16606 unsigned DiagID = SemaRef.getLangOpts().CPlusPlus26
16607 ? diag::warn_cxx26_type_aware_allocators
16608 : diag::ext_cxx26_type_aware_allocators;
16609 SemaRef.Diag(FnDecl->getLocation(), DiagID);
16610 }
16611
16612 if (OperatorKind == AllocationOperatorKind::New) {
16613 SizeParameterIndex = 1;
16614 MinimumMandatoryArgumentCount =
16615 FunctionDecl::RequiredTypeAwareNewParameterCount;
16616 } else {
16617 SizeParameterIndex = 2;
16618 MinimumMandatoryArgumentCount =
16619 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16620 }
16621 FirstNonTypeParam = 1;
16622 }
16623
16624 bool IsPotentiallyDestroyingDelete =
16625 IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: FnDecl);
16626
16627 if (IsPotentiallyDestroyingDelete) {
16628 ++MinimumMandatoryArgumentCount;
16629 ++SizeParameterIndex;
16630 }
16631
16632 if (NumParams < MinimumMandatoryArgumentCount)
16633 return SemaRef.Diag(FnDecl->getLocation(),
16634 diag::err_operator_new_delete_too_few_parameters)
16635 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16636 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16637
16638 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16639 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: Idx);
16640 if (ParamDecl->hasDefaultArg())
16641 return SemaRef.Diag(FnDecl->getLocation(),
16642 diag::err_operator_new_default_arg)
16643 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16644 }
16645
16646 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16647 QualType CanResultType = NormalizeType(FnType->getReturnType());
16648 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16649 QualType CanExpectedSizeOrAddressParamType =
16650 NormalizeType(ExpectedSizeOrAddressParamType);
16651
16652 // Check that the result type is what we expect.
16653 if (CanResultType != CanExpectedResultType) {
16654 // Reject even if the type is dependent; an operator delete function is
16655 // required to have a non-dependent result type.
16656 return SemaRef.Diag(
16657 FnDecl->getLocation(),
16658 CanResultType->isDependentType()
16659 ? diag::err_operator_new_delete_dependent_result_type
16660 : diag::err_operator_new_delete_invalid_result_type)
16661 << FnDecl->getDeclName() << ExpectedResultType;
16662 }
16663
16664 // A function template must have at least 2 parameters.
16665 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16666 return SemaRef.Diag(FnDecl->getLocation(),
16667 diag::err_operator_new_delete_template_too_few_parameters)
16668 << FnDecl->getDeclName();
16669
16670 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16671 auto FallbackType) -> bool {
16672 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: ParamIdx);
16673 if (ExpectedType.isNull()) {
16674 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
16675 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16676 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16677 << ParamDecl->getSourceRange();
16678 }
16679 CanQualType CanExpectedTy =
16680 NormalizeType(SemaRef.Context.getCanonicalType(T: ExpectedType));
16681 auto ActualParamType =
16682 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16683 if (ActualParamType == CanExpectedTy)
16684 return false;
16685 unsigned Diagnostic = ActualParamType->isDependentType()
16686 ? DependentParamTypeDiag
16687 : InvalidParamTypeDiag;
16688 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
16689 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16690 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16691 << FallbackType << ParamDecl->getSourceRange();
16692 };
16693
16694 // Check that the first parameter type is what we expect.
16695 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16696 return true;
16697
16698 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16699
16700 // If the first parameter type is not a type-identity we're done, otherwise
16701 // we need to ensure the size and alignment parameters have the correct type
16702 if (!IsPotentiallyTypeAware)
16703 return false;
16704
16705 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16706 return true;
16707 TypeDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16708 QualType StdAlignValT =
16709 StdAlignValTDecl ? SemaRef.Context.getTypeDeclType(Decl: StdAlignValTDecl)
16710 : QualType();
16711 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16712 return true;
16713
16714 FnDecl->setIsTypeAwareOperatorNewOrDelete();
16715 return MalformedTypeIdentity;
16716}
16717
16718static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16719 // C++ [basic.stc.dynamic.allocation]p1:
16720 // A program is ill-formed if an allocation function is declared in a
16721 // namespace scope other than global scope or declared static in global
16722 // scope.
16723 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16724 return true;
16725
16726 CanQualType SizeTy =
16727 SemaRef.Context.getCanonicalType(T: SemaRef.Context.getSizeType());
16728
16729 // C++ [basic.stc.dynamic.allocation]p1:
16730 // The return type shall be void*. The first parameter shall have type
16731 // std::size_t.
16732 return CheckOperatorNewDeleteTypes(
16733 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
16734 SizeTy, diag::err_operator_new_dependent_param_type,
16735 diag::err_operator_new_param_type);
16736}
16737
16738static bool
16739CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16740 // C++ [basic.stc.dynamic.deallocation]p1:
16741 // A program is ill-formed if deallocation functions are declared in a
16742 // namespace scope other than global scope or declared static in global
16743 // scope.
16744 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16745 return true;
16746
16747 auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl);
16748 auto ConstructDestroyingDeleteAddressType = [&]() {
16749 assert(MD);
16750 return SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
16751 SemaRef.Context.getRecordType(MD->getParent())));
16752 };
16753
16754 // C++ P2719: A destroying operator delete cannot be type aware
16755 // so for QoL we actually check for this explicitly by considering
16756 // an destroying-delete appropriate address type and the presence of
16757 // any parameter of type destroying_delete_t as an erroneous attempt
16758 // to declare a type aware destroying delete, rather than emitting a
16759 // pile of incorrect parameter type errors.
16760 if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(
16761 SemaRef, MD, /*WasMalformed=*/nullptr)) {
16762 QualType AddressParamType =
16763 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
16764 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16765 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16766 // The address parameter type implies an author trying to construct a
16767 // type aware destroying delete, so we'll see if we can find a parameter
16768 // of type `std::destroying_delete_t`, and if we find it we'll report
16769 // this as being an attempt at a type aware destroying delete just stop
16770 // here. If we don't do this, the resulting incorrect parameter ordering
16771 // results in a pile mismatched argument type errors that don't explain
16772 // the core problem.
16773 for (auto Param : MD->parameters()) {
16774 if (isDestroyingDeleteT(Param->getType())) {
16775 SemaRef.Diag(MD->getLocation(),
16776 diag::err_type_aware_destroying_operator_delete)
16777 << Param->getSourceRange();
16778 return true;
16779 }
16780 }
16781 }
16782 }
16783
16784 // C++ P0722:
16785 // Within a class C, the first parameter of a destroying operator delete
16786 // shall be of type C *. The first parameter of any other deallocation
16787 // function shall be of type void *.
16788 CanQualType ExpectedAddressParamType =
16789 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
16790 ? SemaRef.Context.getCanonicalType(T: SemaRef.Context.getPointerType(
16791 T: SemaRef.Context.getRecordType(MD->getParent())))
16792 : SemaRef.Context.VoidPtrTy;
16793
16794 // C++ [basic.stc.dynamic.deallocation]p2:
16795 // Each deallocation function shall return void
16796 if (CheckOperatorNewDeleteTypes(
16797 SemaRef, FnDecl, AllocationOperatorKind::Delete,
16798 SemaRef.Context.VoidTy, ExpectedAddressParamType,
16799 diag::err_operator_delete_dependent_param_type,
16800 diag::err_operator_delete_param_type))
16801 return true;
16802
16803 // C++ P0722:
16804 // A destroying operator delete shall be a usual deallocation function.
16805 if (MD && !MD->getParent()->isDependentContext() &&
16806 MD->isDestroyingOperatorDelete()) {
16807 if (!SemaRef.isUsualDeallocationFunction(FD: MD)) {
16808 SemaRef.Diag(MD->getLocation(),
16809 diag::err_destroying_operator_delete_not_usual);
16810 return true;
16811 }
16812 }
16813
16814 return false;
16815}
16816
16817bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16818 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16819 "Expected an overloaded operator declaration");
16820
16821 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16822
16823 // C++ [over.oper]p5:
16824 // The allocation and deallocation functions, operator new,
16825 // operator new[], operator delete and operator delete[], are
16826 // described completely in 3.7.3. The attributes and restrictions
16827 // found in the rest of this subclause do not apply to them unless
16828 // explicitly stated in 3.7.3.
16829 if (Op == OO_Delete || Op == OO_Array_Delete)
16830 return CheckOperatorDeleteDeclaration(SemaRef&: *this, FnDecl);
16831
16832 if (Op == OO_New || Op == OO_Array_New)
16833 return CheckOperatorNewDeclaration(SemaRef&: *this, FnDecl);
16834
16835 // C++ [over.oper]p7:
16836 // An operator function shall either be a member function or
16837 // be a non-member function and have at least one parameter
16838 // whose type is a class, a reference to a class, an enumeration,
16839 // or a reference to an enumeration.
16840 // Note: Before C++23, a member function could not be static. The only member
16841 // function allowed to be static is the call operator function.
16842 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
16843 if (MethodDecl->isStatic()) {
16844 if (Op == OO_Call || Op == OO_Subscript)
16845 Diag(FnDecl->getLocation(),
16846 (LangOpts.CPlusPlus23
16847 ? diag::warn_cxx20_compat_operator_overload_static
16848 : diag::ext_operator_overload_static))
16849 << FnDecl;
16850 else
16851 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16852 << FnDecl;
16853 }
16854 } else {
16855 bool ClassOrEnumParam = false;
16856 for (auto *Param : FnDecl->parameters()) {
16857 QualType ParamType = Param->getType().getNonReferenceType();
16858 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16859 ParamType->isEnumeralType()) {
16860 ClassOrEnumParam = true;
16861 break;
16862 }
16863 }
16864
16865 if (!ClassOrEnumParam)
16866 return Diag(FnDecl->getLocation(),
16867 diag::err_operator_overload_needs_class_or_enum)
16868 << FnDecl->getDeclName();
16869 }
16870
16871 // C++ [over.oper]p8:
16872 // An operator function cannot have default arguments (8.3.6),
16873 // except where explicitly stated below.
16874 //
16875 // Only the function-call operator (C++ [over.call]p1) and the subscript
16876 // operator (CWG2507) allow default arguments.
16877 if (Op != OO_Call) {
16878 ParmVarDecl *FirstDefaultedParam = nullptr;
16879 for (auto *Param : FnDecl->parameters()) {
16880 if (Param->hasDefaultArg()) {
16881 FirstDefaultedParam = Param;
16882 break;
16883 }
16884 }
16885 if (FirstDefaultedParam) {
16886 if (Op == OO_Subscript) {
16887 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16888 ? diag::ext_subscript_overload
16889 : diag::error_subscript_overload)
16890 << FnDecl->getDeclName() << 1
16891 << FirstDefaultedParam->getDefaultArgRange();
16892 } else {
16893 return Diag(FirstDefaultedParam->getLocation(),
16894 diag::err_operator_overload_default_arg)
16895 << FnDecl->getDeclName()
16896 << FirstDefaultedParam->getDefaultArgRange();
16897 }
16898 }
16899 }
16900
16901 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16902 { false, false, false }
16903#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16904 , { Unary, Binary, MemberOnly }
16905#include "clang/Basic/OperatorKinds.def"
16906 };
16907
16908 bool CanBeUnaryOperator = OperatorUses[Op][0];
16909 bool CanBeBinaryOperator = OperatorUses[Op][1];
16910 bool MustBeMemberOperator = OperatorUses[Op][2];
16911
16912 // C++ [over.oper]p8:
16913 // [...] Operator functions cannot have more or fewer parameters
16914 // than the number required for the corresponding operator, as
16915 // described in the rest of this subclause.
16916 unsigned NumParams = FnDecl->getNumParams() +
16917 (isa<CXXMethodDecl>(Val: FnDecl) &&
16918 !FnDecl->hasCXXExplicitFunctionObjectParameter()
16919 ? 1
16920 : 0);
16921 if (Op != OO_Call && Op != OO_Subscript &&
16922 ((NumParams == 1 && !CanBeUnaryOperator) ||
16923 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16924 (NumParams > 2))) {
16925 // We have the wrong number of parameters.
16926 unsigned ErrorKind;
16927 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16928 ErrorKind = 2; // 2 -> unary or binary.
16929 } else if (CanBeUnaryOperator) {
16930 ErrorKind = 0; // 0 -> unary
16931 } else {
16932 assert(CanBeBinaryOperator &&
16933 "All non-call overloaded operators are unary or binary!");
16934 ErrorKind = 1; // 1 -> binary
16935 }
16936 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16937 << FnDecl->getDeclName() << NumParams << ErrorKind;
16938 }
16939
16940 if (Op == OO_Subscript && NumParams != 2) {
16941 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16942 ? diag::ext_subscript_overload
16943 : diag::error_subscript_overload)
16944 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16945 }
16946
16947 // Overloaded operators other than operator() and operator[] cannot be
16948 // variadic.
16949 if (Op != OO_Call &&
16950 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16951 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16952 << FnDecl->getDeclName();
16953 }
16954
16955 // Some operators must be member functions.
16956 if (MustBeMemberOperator && !isa<CXXMethodDecl>(Val: FnDecl)) {
16957 return Diag(FnDecl->getLocation(),
16958 diag::err_operator_overload_must_be_member)
16959 << FnDecl->getDeclName();
16960 }
16961
16962 // C++ [over.inc]p1:
16963 // The user-defined function called operator++ implements the
16964 // prefix and postfix ++ operator. If this function is a member
16965 // function with no parameters, or a non-member function with one
16966 // parameter of class or enumeration type, it defines the prefix
16967 // increment operator ++ for objects of that type. If the function
16968 // is a member function with one parameter (which shall be of type
16969 // int) or a non-member function with two parameters (the second
16970 // of which shall be of type int), it defines the postfix
16971 // increment operator ++ for objects of that type.
16972 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16973 ParmVarDecl *LastParam = FnDecl->getParamDecl(i: FnDecl->getNumParams() - 1);
16974 QualType ParamType = LastParam->getType();
16975
16976 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16977 !ParamType->isDependentType())
16978 return Diag(LastParam->getLocation(),
16979 diag::err_operator_overload_post_incdec_must_be_int)
16980 << LastParam->getType() << (Op == OO_MinusMinus);
16981 }
16982
16983 return false;
16984}
16985
16986static bool
16987checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16988 FunctionTemplateDecl *TpDecl) {
16989 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16990
16991 // Must have one or two template parameters.
16992 if (TemplateParams->size() == 1) {
16993 NonTypeTemplateParmDecl *PmDecl =
16994 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 0));
16995
16996 // The template parameter must be a char parameter pack.
16997 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16998 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16999 return false;
17000
17001 // C++20 [over.literal]p5:
17002 // A string literal operator template is a literal operator template
17003 // whose template-parameter-list comprises a single non-type
17004 // template-parameter of class type.
17005 //
17006 // As a DR resolution, we also allow placeholders for deduced class
17007 // template specializations.
17008 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17009 !PmDecl->isTemplateParameterPack() &&
17010 (PmDecl->getType()->isRecordType() ||
17011 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17012 return false;
17013 } else if (TemplateParams->size() == 2) {
17014 TemplateTypeParmDecl *PmType =
17015 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17016 NonTypeTemplateParmDecl *PmArgs =
17017 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 1));
17018
17019 // The second template parameter must be a parameter pack with the
17020 // first template parameter as its type.
17021 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17022 PmArgs->isTemplateParameterPack()) {
17023 const TemplateTypeParmType *TArgs =
17024 PmArgs->getType()->getAs<TemplateTypeParmType>();
17025 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
17026 TArgs->getIndex() == PmType->getIndex()) {
17027 if (!SemaRef.inTemplateInstantiation())
17028 SemaRef.Diag(TpDecl->getLocation(),
17029 diag::ext_string_literal_operator_template);
17030 return false;
17031 }
17032 }
17033 }
17034
17035 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17036 diag::err_literal_operator_template)
17037 << TpDecl->getTemplateParameters()->getSourceRange();
17038 return true;
17039}
17040
17041bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
17042 if (isa<CXXMethodDecl>(Val: FnDecl)) {
17043 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
17044 << FnDecl->getDeclName();
17045 return true;
17046 }
17047
17048 if (FnDecl->isExternC()) {
17049 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
17050 if (const LinkageSpecDecl *LSD =
17051 FnDecl->getDeclContext()->getExternCContext())
17052 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
17053 return true;
17054 }
17055
17056 // This might be the definition of a literal operator template.
17057 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
17058
17059 // This might be a specialization of a literal operator template.
17060 if (!TpDecl)
17061 TpDecl = FnDecl->getPrimaryTemplate();
17062
17063 // template <char...> type operator "" name() and
17064 // template <class T, T...> type operator "" name() are the only valid
17065 // template signatures, and the only valid signatures with no parameters.
17066 //
17067 // C++20 also allows template <SomeClass T> type operator "" name().
17068 if (TpDecl) {
17069 if (FnDecl->param_size() != 0) {
17070 Diag(FnDecl->getLocation(),
17071 diag::err_literal_operator_template_with_params);
17072 return true;
17073 }
17074
17075 if (checkLiteralOperatorTemplateParameterList(SemaRef&: *this, TpDecl))
17076 return true;
17077
17078 } else if (FnDecl->param_size() == 1) {
17079 const ParmVarDecl *Param = FnDecl->getParamDecl(i: 0);
17080
17081 QualType ParamType = Param->getType().getUnqualifiedType();
17082
17083 // Only unsigned long long int, long double, any character type, and const
17084 // char * are allowed as the only parameters.
17085 if (ParamType->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
17086 ParamType->isSpecificBuiltinType(K: BuiltinType::LongDouble) ||
17087 Context.hasSameType(ParamType, Context.CharTy) ||
17088 Context.hasSameType(ParamType, Context.WideCharTy) ||
17089 Context.hasSameType(ParamType, Context.Char8Ty) ||
17090 Context.hasSameType(ParamType, Context.Char16Ty) ||
17091 Context.hasSameType(ParamType, Context.Char32Ty)) {
17092 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17093 QualType InnerType = Ptr->getPointeeType();
17094
17095 // Pointer parameter must be a const char *.
17096 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17097 Context.CharTy) &&
17098 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17099 Diag(Param->getSourceRange().getBegin(),
17100 diag::err_literal_operator_param)
17101 << ParamType << "'const char *'" << Param->getSourceRange();
17102 return true;
17103 }
17104
17105 } else if (ParamType->isRealFloatingType()) {
17106 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17107 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17108 return true;
17109
17110 } else if (ParamType->isIntegerType()) {
17111 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17112 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17113 return true;
17114
17115 } else {
17116 Diag(Param->getSourceRange().getBegin(),
17117 diag::err_literal_operator_invalid_param)
17118 << ParamType << Param->getSourceRange();
17119 return true;
17120 }
17121
17122 } else if (FnDecl->param_size() == 2) {
17123 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17124
17125 // First, verify that the first parameter is correct.
17126
17127 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17128
17129 // Two parameter function must have a pointer to const as a
17130 // first parameter; let's strip those qualifiers.
17131 const PointerType *PT = FirstParamType->getAs<PointerType>();
17132
17133 if (!PT) {
17134 Diag((*Param)->getSourceRange().getBegin(),
17135 diag::err_literal_operator_param)
17136 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17137 return true;
17138 }
17139
17140 QualType PointeeType = PT->getPointeeType();
17141 // First parameter must be const
17142 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17143 Diag((*Param)->getSourceRange().getBegin(),
17144 diag::err_literal_operator_param)
17145 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17146 return true;
17147 }
17148
17149 QualType InnerType = PointeeType.getUnqualifiedType();
17150 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17151 // const char32_t* are allowed as the first parameter to a two-parameter
17152 // function
17153 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17154 Context.hasSameType(InnerType, Context.WideCharTy) ||
17155 Context.hasSameType(InnerType, Context.Char8Ty) ||
17156 Context.hasSameType(InnerType, Context.Char16Ty) ||
17157 Context.hasSameType(InnerType, Context.Char32Ty))) {
17158 Diag((*Param)->getSourceRange().getBegin(),
17159 diag::err_literal_operator_param)
17160 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17161 return true;
17162 }
17163
17164 // Move on to the second and final parameter.
17165 ++Param;
17166
17167 // The second parameter must be a std::size_t.
17168 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17169 if (!Context.hasSameType(T1: SecondParamType, T2: Context.getSizeType())) {
17170 Diag((*Param)->getSourceRange().getBegin(),
17171 diag::err_literal_operator_param)
17172 << SecondParamType << Context.getSizeType()
17173 << (*Param)->getSourceRange();
17174 return true;
17175 }
17176 } else {
17177 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17178 return true;
17179 }
17180
17181 // Parameters are good.
17182
17183 // A parameter-declaration-clause containing a default argument is not
17184 // equivalent to any of the permitted forms.
17185 for (auto *Param : FnDecl->parameters()) {
17186 if (Param->hasDefaultArg()) {
17187 Diag(Param->getDefaultArgRange().getBegin(),
17188 diag::err_literal_operator_default_argument)
17189 << Param->getDefaultArgRange();
17190 break;
17191 }
17192 }
17193
17194 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17195 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
17196 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
17197 !getSourceManager().isInSystemHeader(Loc: FnDecl->getLocation())) {
17198 // C++23 [usrlit.suffix]p1:
17199 // Literal suffix identifiers that do not start with an underscore are
17200 // reserved for future standardization. Literal suffix identifiers that
17201 // contain a double underscore __ are reserved for use by C++
17202 // implementations.
17203 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17204 << static_cast<int>(Status)
17205 << StringLiteralParser::isValidUDSuffix(getLangOpts(), II->getName());
17206 }
17207
17208 return false;
17209}
17210
17211Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
17212 Expr *LangStr,
17213 SourceLocation LBraceLoc) {
17214 StringLiteral *Lit = cast<StringLiteral>(Val: LangStr);
17215 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17216
17217 StringRef Lang = Lit->getString();
17218 LinkageSpecLanguageIDs Language;
17219 if (Lang == "C")
17220 Language = LinkageSpecLanguageIDs::C;
17221 else if (Lang == "C++")
17222 Language = LinkageSpecLanguageIDs::CXX;
17223 else {
17224 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17225 << LangStr->getSourceRange();
17226 return nullptr;
17227 }
17228
17229 // FIXME: Add all the various semantics of linkage specifications
17230
17231 LinkageSpecDecl *D = LinkageSpecDecl::Create(C&: Context, DC: CurContext, ExternLoc,
17232 LangLoc: LangStr->getExprLoc(), Lang: Language,
17233 HasBraces: LBraceLoc.isValid());
17234
17235 /// C++ [module.unit]p7.2.3
17236 /// - Otherwise, if the declaration
17237 /// - ...
17238 /// - ...
17239 /// - appears within a linkage-specification,
17240 /// it is attached to the global module.
17241 ///
17242 /// If the declaration is already in global module fragment, we don't
17243 /// need to attach it again.
17244 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17245 Module *GlobalModule = PushImplicitGlobalModuleFragment(BeginLoc: ExternLoc);
17246 D->setLocalOwningModule(GlobalModule);
17247 }
17248
17249 CurContext->addDecl(D);
17250 PushDeclContext(S, D);
17251 return D;
17252}
17253
17254Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
17255 Decl *LinkageSpec,
17256 SourceLocation RBraceLoc) {
17257 if (RBraceLoc.isValid()) {
17258 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(Val: LinkageSpec);
17259 LSDecl->setRBraceLoc(RBraceLoc);
17260 }
17261
17262 // If the current module doesn't has Parent, it implies that the
17263 // LinkageSpec isn't in the module created by itself. So we don't
17264 // need to pop it.
17265 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17266 getCurrentModule()->isImplicitGlobalModule() &&
17267 getCurrentModule()->Parent)
17268 PopImplicitGlobalModuleFragment();
17269
17270 PopDeclContext();
17271 return LinkageSpec;
17272}
17273
17274Decl *Sema::ActOnEmptyDeclaration(Scope *S,
17275 const ParsedAttributesView &AttrList,
17276 SourceLocation SemiLoc) {
17277 Decl *ED = EmptyDecl::Create(C&: Context, DC: CurContext, L: SemiLoc);
17278 // Attribute declarations appertain to empty declaration so we handle
17279 // them here.
17280 ProcessDeclAttributeList(S, D: ED, AttrList);
17281
17282 CurContext->addDecl(D: ED);
17283 return ED;
17284}
17285
17286VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
17287 SourceLocation StartLoc,
17288 SourceLocation Loc,
17289 const IdentifierInfo *Name) {
17290 bool Invalid = false;
17291 QualType ExDeclType = TInfo->getType();
17292
17293 // Arrays and functions decay.
17294 if (ExDeclType->isArrayType())
17295 ExDeclType = Context.getArrayDecayedType(T: ExDeclType);
17296 else if (ExDeclType->isFunctionType())
17297 ExDeclType = Context.getPointerType(T: ExDeclType);
17298
17299 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17300 // The exception-declaration shall not denote a pointer or reference to an
17301 // incomplete type, other than [cv] void*.
17302 // N2844 forbids rvalue references.
17303 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17304 Diag(Loc, diag::err_catch_rvalue_ref);
17305 Invalid = true;
17306 }
17307
17308 if (ExDeclType->isVariablyModifiedType()) {
17309 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17310 Invalid = true;
17311 }
17312
17313 QualType BaseType = ExDeclType;
17314 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17315 unsigned DK = diag::err_catch_incomplete;
17316 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17317 BaseType = Ptr->getPointeeType();
17318 Mode = 1;
17319 DK = diag::err_catch_incomplete_ptr;
17320 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17321 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17322 BaseType = Ref->getPointeeType();
17323 Mode = 2;
17324 DK = diag::err_catch_incomplete_ref;
17325 }
17326 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17327 !BaseType->isDependentType() && RequireCompleteType(Loc, T: BaseType, DiagID: DK))
17328 Invalid = true;
17329
17330 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17331 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17332 Invalid = true;
17333 }
17334
17335 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17336 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17337 Invalid = true;
17338 }
17339
17340 if (!Invalid && !ExDeclType->isDependentType() &&
17341 RequireNonAbstractType(Loc, ExDeclType,
17342 diag::err_abstract_type_in_decl,
17343 AbstractVariableType))
17344 Invalid = true;
17345
17346 // Only the non-fragile NeXT runtime currently supports C++ catches
17347 // of ObjC types, and no runtime supports catching ObjC types by value.
17348 if (!Invalid && getLangOpts().ObjC) {
17349 QualType T = ExDeclType;
17350 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17351 T = RT->getPointeeType();
17352
17353 if (T->isObjCObjectType()) {
17354 Diag(Loc, diag::err_objc_object_catch);
17355 Invalid = true;
17356 } else if (T->isObjCObjectPointerType()) {
17357 // FIXME: should this be a test for macosx-fragile specifically?
17358 if (getLangOpts().ObjCRuntime.isFragile())
17359 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17360 }
17361 }
17362
17363 VarDecl *ExDecl = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: Loc, Id: Name,
17364 T: ExDeclType, TInfo, S: SC_None);
17365 ExDecl->setExceptionVariable(true);
17366
17367 // In ARC, infer 'retaining' for variables of retainable type.
17368 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17369 Invalid = true;
17370
17371 if (!Invalid && !ExDeclType->isDependentType()) {
17372 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
17373 // Insulate this from anything else we might currently be parsing.
17374 EnterExpressionEvaluationContext scope(
17375 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17376
17377 // C++ [except.handle]p16:
17378 // The object declared in an exception-declaration or, if the
17379 // exception-declaration does not specify a name, a temporary (12.2) is
17380 // copy-initialized (8.5) from the exception object. [...]
17381 // The object is destroyed when the handler exits, after the destruction
17382 // of any automatic objects initialized within the handler.
17383 //
17384 // We just pretend to initialize the object with itself, then make sure
17385 // it can be destroyed later.
17386 QualType initType = Context.getExceptionObjectType(T: ExDeclType);
17387
17388 InitializedEntity entity =
17389 InitializedEntity::InitializeVariable(Var: ExDecl);
17390 InitializationKind initKind =
17391 InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation());
17392
17393 Expr *opaqueValue =
17394 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17395 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17396 ExprResult result = sequence.Perform(S&: *this, Entity: entity, Kind: initKind, Args: opaqueValue);
17397 if (result.isInvalid())
17398 Invalid = true;
17399 else {
17400 // If the constructor used was non-trivial, set this as the
17401 // "initializer".
17402 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17403 if (!construct->getConstructor()->isTrivial()) {
17404 Expr *init = MaybeCreateExprWithCleanups(construct);
17405 ExDecl->setInit(init);
17406 }
17407
17408 // And make sure it's destructable.
17409 FinalizeVarWithDestructor(VD: ExDecl, Record: recordType);
17410 }
17411 }
17412 }
17413
17414 if (Invalid)
17415 ExDecl->setInvalidDecl();
17416
17417 return ExDecl;
17418}
17419
17420Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17421 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17422 bool Invalid = D.isInvalidType();
17423
17424 // Check for unexpanded parameter packs.
17425 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
17426 UPPC: UPPC_ExceptionType)) {
17427 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
17428 Loc: D.getIdentifierLoc());
17429 Invalid = true;
17430 }
17431
17432 const IdentifierInfo *II = D.getIdentifier();
17433 if (NamedDecl *PrevDecl =
17434 LookupSingleName(S, Name: II, Loc: D.getIdentifierLoc(), NameKind: LookupOrdinaryName,
17435 Redecl: RedeclarationKind::ForVisibleRedeclaration)) {
17436 // The scope should be freshly made just for us. There is just no way
17437 // it contains any previous declaration, except for function parameters in
17438 // a function-try-block's catch statement.
17439 assert(!S->isDeclScope(PrevDecl));
17440 if (isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
17441 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17442 << D.getIdentifier();
17443 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17444 Invalid = true;
17445 } else if (PrevDecl->isTemplateParameter())
17446 // Maybe we will complain about the shadowed template parameter.
17447 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17448 }
17449
17450 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17451 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17452 << D.getCXXScopeSpec().getRange();
17453 Invalid = true;
17454 }
17455
17456 VarDecl *ExDecl = BuildExceptionDeclaration(
17457 S, TInfo, StartLoc: D.getBeginLoc(), Loc: D.getIdentifierLoc(), Name: D.getIdentifier());
17458 if (Invalid)
17459 ExDecl->setInvalidDecl();
17460
17461 // Add the exception declaration into this scope.
17462 if (II)
17463 PushOnScopeChains(ExDecl, S);
17464 else
17465 CurContext->addDecl(ExDecl);
17466
17467 ProcessDeclAttributes(S, ExDecl, D);
17468 return ExDecl;
17469}
17470
17471Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17472 Expr *AssertExpr,
17473 Expr *AssertMessageExpr,
17474 SourceLocation RParenLoc) {
17475 if (DiagnoseUnexpandedParameterPack(E: AssertExpr, UPPC: UPPC_StaticAssertExpression))
17476 return nullptr;
17477
17478 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17479 AssertMessageExpr, RParenLoc, Failed: false);
17480}
17481
17482static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17483 switch (BTK) {
17484 case BuiltinType::Char_S:
17485 case BuiltinType::Char_U:
17486 break;
17487 case BuiltinType::Char8:
17488 OS << "u8";
17489 break;
17490 case BuiltinType::Char16:
17491 OS << 'u';
17492 break;
17493 case BuiltinType::Char32:
17494 OS << 'U';
17495 break;
17496 case BuiltinType::WChar_S:
17497 case BuiltinType::WChar_U:
17498 OS << 'L';
17499 break;
17500 default:
17501 llvm_unreachable("Non-character type");
17502 }
17503}
17504
17505/// Convert character's value, interpreted as a code unit, to a string.
17506/// The value needs to be zero-extended to 32-bits.
17507/// FIXME: This assumes Unicode literal encodings
17508static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17509 unsigned TyWidth,
17510 SmallVectorImpl<char> &Str) {
17511 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17512 char *Ptr = Arr;
17513 BuiltinType::Kind K = BTy->getKind();
17514 llvm::raw_svector_ostream OS(Str);
17515
17516 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17517 // other types.
17518 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17519 K == BuiltinType::Char8 || Value <= 0x7F) {
17520 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Value);
17521 if (!Escaped.empty())
17522 EscapeStringForDiagnostic(Str: Escaped, OutStr&: Str);
17523 else
17524 OS << static_cast<char>(Value);
17525 return;
17526 }
17527
17528 switch (K) {
17529 case BuiltinType::Char16:
17530 case BuiltinType::Char32:
17531 case BuiltinType::WChar_S:
17532 case BuiltinType::WChar_U: {
17533 if (llvm::ConvertCodePointToUTF8(Source: Value, ResultPtr&: Ptr))
17534 EscapeStringForDiagnostic(Str: StringRef(Arr, Ptr - Arr), OutStr&: Str);
17535 else
17536 OS << "\\x"
17537 << llvm::format_hex_no_prefix(N: Value, Width: TyWidth / 4, /*Upper=*/true);
17538 break;
17539 }
17540 default:
17541 llvm_unreachable("Non-character type is passed");
17542 }
17543}
17544
17545/// Convert \V to a string we can present to the user in a diagnostic
17546/// \T is the type of the expression that has been evaluated into \V
17547static bool ConvertAPValueToString(const APValue &V, QualType T,
17548 SmallVectorImpl<char> &Str,
17549 ASTContext &Context) {
17550 if (!V.hasValue())
17551 return false;
17552
17553 switch (V.getKind()) {
17554 case APValue::ValueKind::Int:
17555 if (T->isBooleanType()) {
17556 // Bools are reduced to ints during evaluation, but for
17557 // diagnostic purposes we want to print them as
17558 // true or false.
17559 int64_t BoolValue = V.getInt().getExtValue();
17560 assert((BoolValue == 0 || BoolValue == 1) &&
17561 "Bool type, but value is not 0 or 1");
17562 llvm::raw_svector_ostream OS(Str);
17563 OS << (BoolValue ? "true" : "false");
17564 } else {
17565 llvm::raw_svector_ostream OS(Str);
17566 // Same is true for chars.
17567 // We want to print the character representation for textual types
17568 const auto *BTy = T->getAs<BuiltinType>();
17569 if (BTy) {
17570 switch (BTy->getKind()) {
17571 case BuiltinType::Char_S:
17572 case BuiltinType::Char_U:
17573 case BuiltinType::Char8:
17574 case BuiltinType::Char16:
17575 case BuiltinType::Char32:
17576 case BuiltinType::WChar_S:
17577 case BuiltinType::WChar_U: {
17578 unsigned TyWidth = Context.getIntWidth(T);
17579 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17580 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17581 WriteCharTypePrefix(BTK: BTy->getKind(), OS);
17582 OS << '\'';
17583 WriteCharValueForDiagnostic(Value: CodeUnit, BTy, TyWidth, Str);
17584 OS << "' (0x"
17585 << llvm::format_hex_no_prefix(N: CodeUnit, /*Width=*/2,
17586 /*Upper=*/true)
17587 << ", " << V.getInt() << ')';
17588 return true;
17589 }
17590 default:
17591 break;
17592 }
17593 }
17594 V.getInt().toString(Str);
17595 }
17596
17597 break;
17598
17599 case APValue::ValueKind::Float:
17600 V.getFloat().toString(Str);
17601 break;
17602
17603 case APValue::ValueKind::LValue:
17604 if (V.isNullPointer()) {
17605 llvm::raw_svector_ostream OS(Str);
17606 OS << "nullptr";
17607 } else
17608 return false;
17609 break;
17610
17611 case APValue::ValueKind::ComplexFloat: {
17612 llvm::raw_svector_ostream OS(Str);
17613 OS << '(';
17614 V.getComplexFloatReal().toString(Str);
17615 OS << " + ";
17616 V.getComplexFloatImag().toString(Str);
17617 OS << "i)";
17618 } break;
17619
17620 case APValue::ValueKind::ComplexInt: {
17621 llvm::raw_svector_ostream OS(Str);
17622 OS << '(';
17623 V.getComplexIntReal().toString(Str);
17624 OS << " + ";
17625 V.getComplexIntImag().toString(Str);
17626 OS << "i)";
17627 } break;
17628
17629 default:
17630 return false;
17631 }
17632
17633 return true;
17634}
17635
17636/// Some Expression types are not useful to print notes about,
17637/// e.g. literals and values that have already been expanded
17638/// before such as int-valued template parameters.
17639static bool UsefulToPrintExpr(const Expr *E) {
17640 E = E->IgnoreParenImpCasts();
17641 // Literals are pretty easy for humans to understand.
17642 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17643 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(Val: E))
17644 return false;
17645
17646 // These have been substituted from template parameters
17647 // and appear as literals in the static assert error.
17648 if (isa<SubstNonTypeTemplateParmExpr>(Val: E))
17649 return false;
17650
17651 // -5 is also simple to understand.
17652 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E))
17653 return UsefulToPrintExpr(E: UnaryOp->getSubExpr());
17654
17655 // Only print nested arithmetic operators.
17656 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E))
17657 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17658 BO->isBitwiseOp());
17659
17660 return true;
17661}
17662
17663void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17664 if (const auto *Op = dyn_cast<BinaryOperator>(Val: E);
17665 Op && Op->getOpcode() != BO_LOr) {
17666 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17667 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17668
17669 // Ignore comparisons of boolean expressions with a boolean literal.
17670 if ((isa<CXXBoolLiteralExpr>(Val: LHS) && RHS->getType()->isBooleanType()) ||
17671 (isa<CXXBoolLiteralExpr>(Val: RHS) && LHS->getType()->isBooleanType()))
17672 return;
17673
17674 // Don't print obvious expressions.
17675 if (!UsefulToPrintExpr(E: LHS) && !UsefulToPrintExpr(E: RHS))
17676 return;
17677
17678 struct {
17679 const clang::Expr *Cond;
17680 Expr::EvalResult Result;
17681 SmallString<12> ValueString;
17682 bool Print;
17683 } DiagSide[2] = {{.Cond: LHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false},
17684 {.Cond: RHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}};
17685 for (unsigned I = 0; I < 2; I++) {
17686 const Expr *Side = DiagSide[I].Cond;
17687
17688 Side->EvaluateAsRValue(Result&: DiagSide[I].Result, Ctx: Context, InConstantContext: true);
17689
17690 DiagSide[I].Print =
17691 ConvertAPValueToString(V: DiagSide[I].Result.Val, T: Side->getType(),
17692 Str&: DiagSide[I].ValueString, Context);
17693 }
17694 if (DiagSide[0].Print && DiagSide[1].Print) {
17695 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17696 << DiagSide[0].ValueString << Op->getOpcodeStr()
17697 << DiagSide[1].ValueString << Op->getSourceRange();
17698 }
17699 } else {
17700 DiagnoseTypeTraitDetails(E);
17701 }
17702}
17703
17704template <typename ResultType>
17705static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17706 ResultType &Result, ASTContext &Ctx,
17707 Sema::StringEvaluationContext EvalContext,
17708 bool ErrorOnInvalidMessage) {
17709
17710 assert(Message);
17711 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17712 "can't evaluate a dependant static assert message");
17713
17714 if (const auto *SL = dyn_cast<StringLiteral>(Val: Message)) {
17715 assert(SL->isUnevaluated() && "expected an unevaluated string");
17716 if constexpr (std::is_same_v<APValue, ResultType>) {
17717 Result =
17718 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17719 const ConstantArrayType *CAT =
17720 SemaRef.getASTContext().getAsConstantArrayType(T: SL->getType());
17721 assert(CAT && "string literal isn't an array");
17722 QualType CharType = CAT->getElementType();
17723 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(T: CharType),
17724 CharType->isUnsignedIntegerType());
17725 for (unsigned I = 0; I < SL->getLength(); I++) {
17726 Value = SL->getCodeUnit(i: I);
17727 Result.getArrayInitializedElt(I) = APValue(Value);
17728 }
17729 } else {
17730 Result.assign(SL->getString().begin(), SL->getString().end());
17731 }
17732 return true;
17733 }
17734
17735 SourceLocation Loc = Message->getBeginLoc();
17736 QualType T = Message->getType().getNonReferenceType();
17737 auto *RD = T->getAsCXXRecordDecl();
17738 if (!RD) {
17739 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
17740 return false;
17741 }
17742
17743 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17744 DeclarationName DN = SemaRef.PP.getIdentifierInfo(Name: Member);
17745 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17746 SemaRef.LookupQualifiedName(MemberLookup, RD);
17747 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17748 OverloadCandidateSet::CSK_Normal);
17749 if (MemberLookup.empty())
17750 return std::nullopt;
17751 return std::move(MemberLookup);
17752 };
17753
17754 std::optional<LookupResult> SizeMember = FindMember("size");
17755 std::optional<LookupResult> DataMember = FindMember("data");
17756 if (!SizeMember || !DataMember) {
17757 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
17758 << EvalContext
17759 << ((!SizeMember && !DataMember) ? 2
17760 : !SizeMember ? 0
17761 : 1);
17762 return false;
17763 }
17764
17765 auto BuildExpr = [&](LookupResult &LR) {
17766 ExprResult Res = SemaRef.BuildMemberReferenceExpr(
17767 Message, Message->getType(), Message->getBeginLoc(), false,
17768 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17769 if (Res.isInvalid())
17770 return ExprError();
17771 Res = SemaRef.BuildCallExpr(S: nullptr, Fn: Res.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr,
17772 IsExecConfig: false, AllowRecovery: true);
17773 if (Res.isInvalid())
17774 return ExprError();
17775 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17776 return ExprError();
17777 return SemaRef.TemporaryMaterializationConversion(E: Res.get());
17778 };
17779
17780 ExprResult SizeE = BuildExpr(*SizeMember);
17781 ExprResult DataE = BuildExpr(*DataMember);
17782
17783 QualType SizeT = SemaRef.Context.getSizeType();
17784 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17785 SemaRef.Context.getConstType(T: SemaRef.Context.CharTy));
17786
17787 ExprResult EvaluatedSize =
17788 SizeE.isInvalid()
17789 ? ExprError()
17790 : SemaRef.BuildConvertedConstantExpression(
17791 From: SizeE.get(), T: SizeT, CCE: CCEKind::StaticAssertMessageSize);
17792 if (EvaluatedSize.isInvalid()) {
17793 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17794 << EvalContext << /*size*/ 0;
17795 return false;
17796 }
17797
17798 ExprResult EvaluatedData =
17799 DataE.isInvalid()
17800 ? ExprError()
17801 : SemaRef.BuildConvertedConstantExpression(
17802 From: DataE.get(), T: ConstCharPtr, CCE: CCEKind::StaticAssertMessageData);
17803 if (EvaluatedData.isInvalid()) {
17804 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17805 << EvalContext << /*data*/ 1;
17806 return false;
17807 }
17808
17809 if (!ErrorOnInvalidMessage &&
17810 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
17811 return true;
17812
17813 Expr::EvalResult Status;
17814 SmallVector<PartialDiagnosticAt, 8> Notes;
17815 Status.Diag = &Notes;
17816 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17817 EvaluatedData.get(), Ctx, Status) ||
17818 !Notes.empty()) {
17819 SemaRef.Diag(Message->getBeginLoc(),
17820 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17821 : diag::warn_user_defined_msg_constexpr)
17822 << EvalContext;
17823 for (const auto &Note : Notes)
17824 SemaRef.Diag(Note.first, Note.second);
17825 return !ErrorOnInvalidMessage;
17826 }
17827 return true;
17828}
17829
17830bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
17831 StringEvaluationContext EvalContext,
17832 bool ErrorOnInvalidMessage) {
17833 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
17834 ErrorOnInvalidMessage);
17835}
17836
17837bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17838 StringEvaluationContext EvalContext,
17839 bool ErrorOnInvalidMessage) {
17840 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
17841 ErrorOnInvalidMessage);
17842}
17843
17844Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17845 Expr *AssertExpr, Expr *AssertMessage,
17846 SourceLocation RParenLoc,
17847 bool Failed) {
17848 assert(AssertExpr != nullptr && "Expected non-null condition");
17849 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17850 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17851 !AssertMessage->isValueDependent())) &&
17852 !Failed) {
17853 // In a static_assert-declaration, the constant-expression shall be a
17854 // constant expression that can be contextually converted to bool.
17855 ExprResult Converted = PerformContextuallyConvertToBool(From: AssertExpr);
17856 if (Converted.isInvalid())
17857 Failed = true;
17858
17859 ExprResult FullAssertExpr =
17860 ActOnFinishFullExpr(Expr: Converted.get(), CC: StaticAssertLoc,
17861 /*DiscardedValue*/ false,
17862 /*IsConstexpr*/ true);
17863 if (FullAssertExpr.isInvalid())
17864 Failed = true;
17865 else
17866 AssertExpr = FullAssertExpr.get();
17867
17868 llvm::APSInt Cond;
17869 Expr *BaseExpr = AssertExpr;
17870 AllowFoldKind FoldKind = AllowFoldKind::No;
17871
17872 if (!getLangOpts().CPlusPlus) {
17873 // In C mode, allow folding as an extension for better compatibility with
17874 // C++ in terms of expressions like static_assert("test") or
17875 // static_assert(nullptr).
17876 FoldKind = AllowFoldKind::Allow;
17877 }
17878
17879 if (!Failed && VerifyIntegerConstantExpression(
17880 BaseExpr, &Cond,
17881 diag::err_static_assert_expression_is_not_constant,
17882 FoldKind).isInvalid())
17883 Failed = true;
17884
17885 // If the static_assert passes, only verify that
17886 // the message is grammatically valid without evaluating it.
17887 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17888 std::string Str;
17889 EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
17890 EvalContext: StringEvaluationContext::StaticAssert,
17891 /*ErrorOnInvalidMessage=*/false);
17892 }
17893
17894 // CWG2518
17895 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17896 // template definition, the declaration has no effect.
17897 bool InTemplateDefinition =
17898 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17899
17900 if (!Failed && !Cond && !InTemplateDefinition) {
17901 SmallString<256> MsgBuffer;
17902 llvm::raw_svector_ostream Msg(MsgBuffer);
17903 bool HasMessage = AssertMessage;
17904 if (AssertMessage) {
17905 std::string Str;
17906 HasMessage = EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
17907 EvalContext: StringEvaluationContext::StaticAssert,
17908 /*ErrorOnInvalidMessage=*/true) ||
17909 !Str.empty();
17910 Msg << Str;
17911 }
17912 Expr *InnerCond = nullptr;
17913 std::string InnerCondDescription;
17914 std::tie(args&: InnerCond, args&: InnerCondDescription) =
17915 findFailedBooleanCondition(Cond: Converted.get());
17916 if (const auto *ConceptIDExpr =
17917 dyn_cast_or_null<ConceptSpecializationExpr>(Val: InnerCond)) {
17918 // Drill down into concept specialization expressions to see why they
17919 // weren't satisfied.
17920 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17921 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17922 ConstraintSatisfaction Satisfaction;
17923 if (!CheckConstraintSatisfaction(ConstraintExpr: ConceptIDExpr, Satisfaction))
17924 DiagnoseUnsatisfiedConstraint(Satisfaction);
17925 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(Val: InnerCond) &&
17926 !isa<IntegerLiteral>(Val: InnerCond)) {
17927 Diag(InnerCond->getBeginLoc(),
17928 diag::err_static_assert_requirement_failed)
17929 << InnerCondDescription << !HasMessage << Msg.str()
17930 << InnerCond->getSourceRange();
17931 DiagnoseStaticAssertDetails(E: InnerCond);
17932 } else {
17933 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17934 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17935 PrintContextStack();
17936 }
17937 Failed = true;
17938 }
17939 } else {
17940 ExprResult FullAssertExpr = ActOnFinishFullExpr(Expr: AssertExpr, CC: StaticAssertLoc,
17941 /*DiscardedValue*/false,
17942 /*IsConstexpr*/true);
17943 if (FullAssertExpr.isInvalid())
17944 Failed = true;
17945 else
17946 AssertExpr = FullAssertExpr.get();
17947 }
17948
17949 Decl *Decl = StaticAssertDecl::Create(C&: Context, DC: CurContext, StaticAssertLoc,
17950 AssertExpr, Message: AssertMessage, RParenLoc,
17951 Failed);
17952
17953 CurContext->addDecl(D: Decl);
17954 return Decl;
17955}
17956
17957DeclResult Sema::ActOnTemplatedFriendTag(
17958 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17959 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17960 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
17961 MultiTemplateParamsArg TempParamLists) {
17962 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17963
17964 bool IsMemberSpecialization = false;
17965 bool Invalid = false;
17966
17967 if (TemplateParameterList *TemplateParams =
17968 MatchTemplateParametersToScopeSpecifier(
17969 DeclStartLoc: TagLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TempParamLists, /*friend*/ IsFriend: true,
17970 IsMemberSpecialization, Invalid)) {
17971 if (TemplateParams->size() > 0) {
17972 // This is a declaration of a class template.
17973 if (Invalid)
17974 return true;
17975
17976 return CheckClassTemplate(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS,
17977 Name, NameLoc, Attr, TemplateParams, AS: AS_public,
17978 /*ModulePrivateLoc=*/SourceLocation(),
17979 FriendLoc, NumOuterTemplateParamLists: TempParamLists.size() - 1,
17980 OuterTemplateParamLists: TempParamLists.data())
17981 .get();
17982 } else {
17983 // The "template<>" header is extraneous.
17984 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17985 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17986 IsMemberSpecialization = true;
17987 }
17988 }
17989
17990 if (Invalid) return true;
17991
17992 bool isAllExplicitSpecializations = true;
17993 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17994 if (TempParamLists[I]->size()) {
17995 isAllExplicitSpecializations = false;
17996 break;
17997 }
17998 }
17999
18000 // FIXME: don't ignore attributes.
18001
18002 // If it's explicit specializations all the way down, just forget
18003 // about the template header and build an appropriate non-templated
18004 // friend. TODO: for source fidelity, remember the headers.
18005 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
18006 if (isAllExplicitSpecializations) {
18007 if (SS.isEmpty()) {
18008 bool Owned = false;
18009 bool IsDependent = false;
18010 return ActOnTag(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc,
18011 Attr, AS: AS_public,
18012 /*ModulePrivateLoc=*/SourceLocation(),
18013 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent,
18014 /*ScopedEnumKWLoc=*/SourceLocation(),
18015 /*ScopedEnumUsesClassTag=*/false,
18016 /*UnderlyingType=*/TypeResult(),
18017 /*IsTypeSpecifier=*/false,
18018 /*IsTemplateParamOrArg=*/false,
18019 /*OOK=*/OffsetOfKind::Outside);
18020 }
18021
18022 ElaboratedTypeKeyword Keyword
18023 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18024 QualType T = CheckTypenameType(Keyword, KeywordLoc: TagLoc, QualifierLoc,
18025 II: *Name, IILoc: NameLoc);
18026 if (T.isNull())
18027 return true;
18028
18029 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18030 if (isa<DependentNameType>(Val: T)) {
18031 DependentNameTypeLoc TL =
18032 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18033 TL.setElaboratedKeywordLoc(TagLoc);
18034 TL.setQualifierLoc(QualifierLoc);
18035 TL.setNameLoc(NameLoc);
18036 } else {
18037 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
18038 TL.setElaboratedKeywordLoc(TagLoc);
18039 TL.setQualifierLoc(QualifierLoc);
18040 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
18041 }
18042
18043 FriendDecl *Friend =
18044 FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend_: TSI, FriendL: FriendLoc,
18045 EllipsisLoc, FriendTypeTPLists: TempParamLists);
18046 Friend->setAccess(AS_public);
18047 CurContext->addDecl(Friend);
18048 return Friend;
18049 }
18050
18051 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18052
18053 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
18054 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
18055 // shall not have been introduced by the template-declaration.
18056 SmallVector<UnexpandedParameterPack, 1> Unexpanded;
18057 collectUnexpandedParameterPacks(NNS: QualifierLoc, Unexpanded);
18058 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18059 for (UnexpandedParameterPack &U : Unexpanded) {
18060 if (getDepthAndIndex(UPP: U).first >= FriendDeclDepth) {
18061 auto *ND = dyn_cast<NamedDecl *>(Val&: U.first);
18062 if (!ND)
18063 ND = cast<const TemplateTypeParmType *>(Val&: U.first)->getDecl();
18064 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18065 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18066 return true;
18067 }
18068 }
18069
18070 // Handle the case of a templated-scope friend class. e.g.
18071 // template <class T> class A<T>::B;
18072 // FIXME: we don't support these right now.
18073 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
18074 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
18075 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18076 QualType T = Context.getDependentNameType(Keyword: ETK, NNS: SS.getScopeRep(), Name);
18077 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18078 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18079 TL.setElaboratedKeywordLoc(TagLoc);
18080 TL.setQualifierLoc(SS.getWithLocInContext(Context));
18081 TL.setNameLoc(NameLoc);
18082
18083 FriendDecl *Friend =
18084 FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend_: TSI, FriendL: FriendLoc,
18085 EllipsisLoc, FriendTypeTPLists: TempParamLists);
18086 Friend->setAccess(AS_public);
18087 Friend->setUnsupportedFriend(true);
18088 CurContext->addDecl(Friend);
18089 return Friend;
18090}
18091
18092Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
18093 MultiTemplateParamsArg TempParams,
18094 SourceLocation EllipsisLoc) {
18095 SourceLocation Loc = DS.getBeginLoc();
18096 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18097
18098 assert(DS.isFriendSpecified());
18099 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18100
18101 // C++ [class.friend]p3:
18102 // A friend declaration that does not declare a function shall have one of
18103 // the following forms:
18104 // friend elaborated-type-specifier ;
18105 // friend simple-type-specifier ;
18106 // friend typename-specifier ;
18107 //
18108 // If the friend keyword isn't first, or if the declarations has any type
18109 // qualifiers, then the declaration doesn't have that form.
18110 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
18111 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
18112 if (DS.getTypeQualifiers()) {
18113 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
18114 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
18115 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
18116 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
18117 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
18118 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
18119 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
18120 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
18121 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
18122 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
18123 }
18124
18125 // Try to convert the decl specifier to a type. This works for
18126 // friend templates because ActOnTag never produces a ClassTemplateDecl
18127 // for a TagUseKind::Friend.
18128 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18129 DeclaratorContext::Member);
18130 TypeSourceInfo *TSI = GetTypeForDeclarator(D&: TheDeclarator);
18131 QualType T = TSI->getType();
18132 if (TheDeclarator.isInvalidType())
18133 return nullptr;
18134
18135 // If '...' is present, the type must contain an unexpanded parameter
18136 // pack, and vice versa.
18137 bool Invalid = false;
18138 if (EllipsisLoc.isInvalid() &&
18139 DiagnoseUnexpandedParameterPack(Loc, T: TSI, UPPC: UPPC_FriendDeclaration))
18140 return nullptr;
18141 if (EllipsisLoc.isValid() &&
18142 !TSI->getType()->containsUnexpandedParameterPack()) {
18143 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18144 << TSI->getTypeLoc().getSourceRange();
18145 Invalid = true;
18146 }
18147
18148 if (!T->isElaboratedTypeSpecifier()) {
18149 if (TempParams.size()) {
18150 // C++23 [dcl.pre]p5:
18151 // In a simple-declaration, the optional init-declarator-list can be
18152 // omitted only when declaring a class or enumeration, that is, when
18153 // the decl-specifier-seq contains either a class-specifier, an
18154 // elaborated-type-specifier with a class-key, or an enum-specifier.
18155 //
18156 // The declaration of a template-declaration or explicit-specialization
18157 // is never a member-declaration, so this must be a simple-declaration
18158 // with no init-declarator-list. Therefore, this is ill-formed.
18159 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
18160 return nullptr;
18161 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18162 SmallString<16> InsertionText(" ");
18163 InsertionText += RD->getKindName();
18164
18165 Diag(Loc, getLangOpts().CPlusPlus11
18166 ? diag::warn_cxx98_compat_unelaborated_friend_type
18167 : diag::ext_unelaborated_friend_type)
18168 << (unsigned)RD->getTagKind() << T
18169 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
18170 InsertionText);
18171 } else {
18172 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
18173 << T << DS.getSourceRange();
18174 }
18175 }
18176
18177 // C++98 [class.friend]p1: A friend of a class is a function
18178 // or class that is not a member of the class . . .
18179 // This is fixed in DR77, which just barely didn't make the C++03
18180 // deadline. It's also a very silly restriction that seriously
18181 // affects inner classes and which nobody else seems to implement;
18182 // thus we never diagnose it, not even in -pedantic.
18183 //
18184 // But note that we could warn about it: it's always useless to
18185 // friend one of your own members (it's not, however, worthless to
18186 // friend a member of an arbitrary specialization of your template).
18187
18188 Decl *D;
18189 if (!TempParams.empty())
18190 // TODO: Support variadic friend template decls?
18191 D = FriendTemplateDecl::Create(Context, DC: CurContext, Loc, Params: TempParams, Friend: TSI,
18192 FriendLoc);
18193 else
18194 D = FriendDecl::Create(C&: Context, DC: CurContext, L: TSI->getTypeLoc().getBeginLoc(),
18195 Friend_: TSI, FriendL: FriendLoc, EllipsisLoc);
18196
18197 if (!D)
18198 return nullptr;
18199
18200 D->setAccess(AS_public);
18201 CurContext->addDecl(D);
18202
18203 if (Invalid)
18204 D->setInvalidDecl();
18205
18206 return D;
18207}
18208
18209NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
18210 MultiTemplateParamsArg TemplateParams) {
18211 const DeclSpec &DS = D.getDeclSpec();
18212
18213 assert(DS.isFriendSpecified());
18214 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18215
18216 SourceLocation Loc = D.getIdentifierLoc();
18217 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18218
18219 // C++ [class.friend]p1
18220 // A friend of a class is a function or class....
18221 // Note that this sees through typedefs, which is intended.
18222 // It *doesn't* see through dependent types, which is correct
18223 // according to [temp.arg.type]p3:
18224 // If a declaration acquires a function type through a
18225 // type dependent on a template-parameter and this causes
18226 // a declaration that does not use the syntactic form of a
18227 // function declarator to have a function type, the program
18228 // is ill-formed.
18229 if (!TInfo->getType()->isFunctionType()) {
18230 Diag(Loc, diag::err_unexpected_friend);
18231
18232 // It might be worthwhile to try to recover by creating an
18233 // appropriate declaration.
18234 return nullptr;
18235 }
18236
18237 // C++ [namespace.memdef]p3
18238 // - If a friend declaration in a non-local class first declares a
18239 // class or function, the friend class or function is a member
18240 // of the innermost enclosing namespace.
18241 // - The name of the friend is not found by simple name lookup
18242 // until a matching declaration is provided in that namespace
18243 // scope (either before or after the class declaration granting
18244 // friendship).
18245 // - If a friend function is called, its name may be found by the
18246 // name lookup that considers functions from namespaces and
18247 // classes associated with the types of the function arguments.
18248 // - When looking for a prior declaration of a class or a function
18249 // declared as a friend, scopes outside the innermost enclosing
18250 // namespace scope are not considered.
18251
18252 CXXScopeSpec &SS = D.getCXXScopeSpec();
18253 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
18254 assert(NameInfo.getName());
18255
18256 // Check for unexpanded parameter packs.
18257 if (DiagnoseUnexpandedParameterPack(Loc, T: TInfo, UPPC: UPPC_FriendDeclaration) ||
18258 DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_FriendDeclaration) ||
18259 DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_FriendDeclaration))
18260 return nullptr;
18261
18262 // The context we found the declaration in, or in which we should
18263 // create the declaration.
18264 DeclContext *DC;
18265 Scope *DCScope = S;
18266 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18267 RedeclarationKind::ForExternalRedeclaration);
18268
18269 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18270
18271 // There are five cases here.
18272 // - There's no scope specifier and we're in a local class. Only look
18273 // for functions declared in the immediately-enclosing block scope.
18274 // We recover from invalid scope qualifiers as if they just weren't there.
18275 FunctionDecl *FunctionContainingLocalClass = nullptr;
18276 if ((SS.isInvalid() || !SS.isSet()) &&
18277 (FunctionContainingLocalClass =
18278 cast<CXXRecordDecl>(Val: CurContext)->isLocalClass())) {
18279 // C++11 [class.friend]p11:
18280 // If a friend declaration appears in a local class and the name
18281 // specified is an unqualified name, a prior declaration is
18282 // looked up without considering scopes that are outside the
18283 // innermost enclosing non-class scope. For a friend function
18284 // declaration, if there is no prior declaration, the program is
18285 // ill-formed.
18286
18287 // Find the innermost enclosing non-class scope. This is the block
18288 // scope containing the local class definition (or for a nested class,
18289 // the outer local class).
18290 DCScope = S->getFnParent();
18291
18292 // Look up the function name in the scope.
18293 Previous.clear(Kind: LookupLocalFriendName);
18294 LookupName(R&: Previous, S, /*AllowBuiltinCreation*/false);
18295
18296 if (!Previous.empty()) {
18297 // All possible previous declarations must have the same context:
18298 // either they were declared at block scope or they are members of
18299 // one of the enclosing local classes.
18300 DC = Previous.getRepresentativeDecl()->getDeclContext();
18301 } else {
18302 // This is ill-formed, but provide the context that we would have
18303 // declared the function in, if we were permitted to, for error recovery.
18304 DC = FunctionContainingLocalClass;
18305 }
18306 adjustContextForLocalExternDecl(DC);
18307
18308 // - There's no scope specifier, in which case we just go to the
18309 // appropriate scope and look for a function or function template
18310 // there as appropriate.
18311 } else if (SS.isInvalid() || !SS.isSet()) {
18312 // C++11 [namespace.memdef]p3:
18313 // If the name in a friend declaration is neither qualified nor
18314 // a template-id and the declaration is a function or an
18315 // elaborated-type-specifier, the lookup to determine whether
18316 // the entity has been previously declared shall not consider
18317 // any scopes outside the innermost enclosing namespace.
18318
18319 // Find the appropriate context according to the above.
18320 DC = CurContext;
18321
18322 // Skip class contexts. If someone can cite chapter and verse
18323 // for this behavior, that would be nice --- it's what GCC and
18324 // EDG do, and it seems like a reasonable intent, but the spec
18325 // really only says that checks for unqualified existing
18326 // declarations should stop at the nearest enclosing namespace,
18327 // not that they should only consider the nearest enclosing
18328 // namespace.
18329 while (DC->isRecord())
18330 DC = DC->getParent();
18331
18332 DeclContext *LookupDC = DC->getNonTransparentContext();
18333 while (true) {
18334 LookupQualifiedName(R&: Previous, LookupCtx: LookupDC);
18335
18336 if (!Previous.empty()) {
18337 DC = LookupDC;
18338 break;
18339 }
18340
18341 if (isTemplateId) {
18342 if (isa<TranslationUnitDecl>(Val: LookupDC)) break;
18343 } else {
18344 if (LookupDC->isFileContext()) break;
18345 }
18346 LookupDC = LookupDC->getParent();
18347 }
18348
18349 DCScope = getScopeForDeclContext(S, DC);
18350
18351 // - There's a non-dependent scope specifier, in which case we
18352 // compute it and do a previous lookup there for a function
18353 // or function template.
18354 } else if (!SS.getScopeRep()->isDependent()) {
18355 DC = computeDeclContext(SS);
18356 if (!DC) return nullptr;
18357
18358 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18359
18360 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18361
18362 // C++ [class.friend]p1: A friend of a class is a function or
18363 // class that is not a member of the class . . .
18364 if (DC->Equals(CurContext))
18365 Diag(DS.getFriendSpecLoc(),
18366 getLangOpts().CPlusPlus11 ?
18367 diag::warn_cxx98_compat_friend_is_member :
18368 diag::err_friend_is_member);
18369
18370 // - There's a scope specifier that does not match any template
18371 // parameter lists, in which case we use some arbitrary context,
18372 // create a method or method template, and wait for instantiation.
18373 // - There's a scope specifier that does match some template
18374 // parameter lists, which we don't handle right now.
18375 } else {
18376 DC = CurContext;
18377 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18378 }
18379
18380 if (!DC->isRecord()) {
18381 int DiagArg = -1;
18382 switch (D.getName().getKind()) {
18383 case UnqualifiedIdKind::IK_ConstructorTemplateId:
18384 case UnqualifiedIdKind::IK_ConstructorName:
18385 DiagArg = 0;
18386 break;
18387 case UnqualifiedIdKind::IK_DestructorName:
18388 DiagArg = 1;
18389 break;
18390 case UnqualifiedIdKind::IK_ConversionFunctionId:
18391 DiagArg = 2;
18392 break;
18393 case UnqualifiedIdKind::IK_DeductionGuideName:
18394 DiagArg = 3;
18395 break;
18396 case UnqualifiedIdKind::IK_Identifier:
18397 case UnqualifiedIdKind::IK_ImplicitSelfParam:
18398 case UnqualifiedIdKind::IK_LiteralOperatorId:
18399 case UnqualifiedIdKind::IK_OperatorFunctionId:
18400 case UnqualifiedIdKind::IK_TemplateId:
18401 break;
18402 }
18403 // This implies that it has to be an operator or function.
18404 if (DiagArg >= 0) {
18405 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18406 return nullptr;
18407 }
18408 }
18409
18410 // FIXME: This is an egregious hack to cope with cases where the scope stack
18411 // does not contain the declaration context, i.e., in an out-of-line
18412 // definition of a class.
18413 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18414 if (!DCScope) {
18415 FakeDCScope.setEntity(DC);
18416 DCScope = &FakeDCScope;
18417 }
18418
18419 bool AddToScope = true;
18420 NamedDecl *ND = ActOnFunctionDeclarator(S: DCScope, D, DC, TInfo, Previous,
18421 TemplateParamLists: TemplateParams, AddToScope);
18422 if (!ND) return nullptr;
18423
18424 assert(ND->getLexicalDeclContext() == CurContext);
18425
18426 // If we performed typo correction, we might have added a scope specifier
18427 // and changed the decl context.
18428 DC = ND->getDeclContext();
18429
18430 // Add the function declaration to the appropriate lookup tables,
18431 // adjusting the redeclarations list as necessary. We don't
18432 // want to do this yet if the friending class is dependent.
18433 //
18434 // Also update the scope-based lookup if the target context's
18435 // lookup context is in lexical scope.
18436 if (!CurContext->isDependentContext()) {
18437 DC = DC->getRedeclContext();
18438 DC->makeDeclVisibleInContext(D: ND);
18439 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18440 PushOnScopeChains(D: ND, S: EnclosingScope, /*AddToContext=*/ false);
18441 }
18442
18443 FriendDecl *FrD = FriendDecl::Create(C&: Context, DC: CurContext,
18444 L: D.getIdentifierLoc(), Friend_: ND,
18445 FriendL: DS.getFriendSpecLoc());
18446 FrD->setAccess(AS_public);
18447 CurContext->addDecl(FrD);
18448
18449 if (ND->isInvalidDecl()) {
18450 FrD->setInvalidDecl();
18451 } else {
18452 if (DC->isRecord()) CheckFriendAccess(D: ND);
18453
18454 FunctionDecl *FD;
18455 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: ND))
18456 FD = FTD->getTemplatedDecl();
18457 else
18458 FD = cast<FunctionDecl>(Val: ND);
18459
18460 // C++ [class.friend]p6:
18461 // A function may be defined in a friend declaration of a class if and
18462 // only if the class is a non-local class, and the function name is
18463 // unqualified.
18464 if (D.isFunctionDefinition()) {
18465 // Qualified friend function definition.
18466 if (SS.isNotEmpty()) {
18467 // FIXME: We should only do this if the scope specifier names the
18468 // innermost enclosing namespace; otherwise the fixit changes the
18469 // meaning of the code.
18470 SemaDiagnosticBuilder DB =
18471 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18472
18473 DB << SS.getScopeRep();
18474 if (DC->isFileContext())
18475 DB << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
18476
18477 // Friend function defined in a local class.
18478 } else if (FunctionContainingLocalClass) {
18479 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18480
18481 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18482 // a template-id, the function name is not unqualified because these is
18483 // no name. While the wording requires some reading in-between the
18484 // lines, GCC, MSVC, and EDG all consider a friend function
18485 // specialization definitions to be de facto explicit specialization
18486 // and diagnose them as such.
18487 } else if (isTemplateId) {
18488 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18489 }
18490 }
18491
18492 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18493 // default argument expression, that declaration shall be a definition
18494 // and shall be the only declaration of the function or function
18495 // template in the translation unit.
18496 if (functionDeclHasDefaultArgument(FD)) {
18497 // We can't look at FD->getPreviousDecl() because it may not have been set
18498 // if we're in a dependent context. If the function is known to be a
18499 // redeclaration, we will have narrowed Previous down to the right decl.
18500 if (D.isRedeclaration()) {
18501 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18502 Diag(Previous.getRepresentativeDecl()->getLocation(),
18503 diag::note_previous_declaration);
18504 } else if (!D.isFunctionDefinition())
18505 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18506 }
18507
18508 // Mark templated-scope function declarations as unsupported.
18509 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18510 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18511 << SS.getScopeRep() << SS.getRange()
18512 << cast<CXXRecordDecl>(CurContext);
18513 FrD->setUnsupportedFriend(true);
18514 }
18515 }
18516
18517 warnOnReservedIdentifier(D: ND);
18518
18519 return ND;
18520}
18521
18522void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
18523 StringLiteral *Message) {
18524 AdjustDeclIfTemplate(Decl&: Dcl);
18525
18526 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: Dcl);
18527 if (!Fn) {
18528 Diag(DelLoc, diag::err_deleted_non_function);
18529 return;
18530 }
18531
18532 // Deleted function does not have a body.
18533 Fn->setWillHaveBody(false);
18534
18535 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18536 // Don't consider the implicit declaration we generate for explicit
18537 // specializations. FIXME: Do not generate these implicit declarations.
18538 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18539 Prev->getPreviousDecl()) &&
18540 !Prev->isDefined()) {
18541 Diag(DelLoc, diag::err_deleted_decl_not_first);
18542 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18543 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18544 : diag::note_previous_declaration);
18545 // We can't recover from this; the declaration might have already
18546 // been used.
18547 Fn->setInvalidDecl();
18548 return;
18549 }
18550
18551 // To maintain the invariant that functions are only deleted on their first
18552 // declaration, mark the implicitly-instantiated declaration of the
18553 // explicitly-specialized function as deleted instead of marking the
18554 // instantiated redeclaration.
18555 Fn = Fn->getCanonicalDecl();
18556 }
18557
18558 // dllimport/dllexport cannot be deleted.
18559 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18560 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18561 Fn->setInvalidDecl();
18562 }
18563
18564 // C++11 [basic.start.main]p3:
18565 // A program that defines main as deleted [...] is ill-formed.
18566 if (Fn->isMain())
18567 Diag(DelLoc, diag::err_deleted_main);
18568
18569 // C++11 [dcl.fct.def.delete]p4:
18570 // A deleted function is implicitly inline.
18571 Fn->setImplicitlyInline();
18572 Fn->setDeletedAsWritten(D: true, Message);
18573}
18574
18575void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18576 if (!Dcl || Dcl->isInvalidDecl())
18577 return;
18578
18579 auto *FD = dyn_cast<FunctionDecl>(Val: Dcl);
18580 if (!FD) {
18581 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Dcl)) {
18582 if (getDefaultedFunctionKind(FD: FTD->getTemplatedDecl()).isComparison()) {
18583 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18584 return;
18585 }
18586 }
18587
18588 Diag(DefaultLoc, diag::err_default_special_members)
18589 << getLangOpts().CPlusPlus20;
18590 return;
18591 }
18592
18593 // Reject if this can't possibly be a defaultable function.
18594 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
18595 if (!DefKind &&
18596 // A dependent function that doesn't locally look defaultable can
18597 // still instantiate to a defaultable function if it's a constructor
18598 // or assignment operator.
18599 (!FD->isDependentContext() ||
18600 (!isa<CXXConstructorDecl>(Val: FD) &&
18601 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18602 Diag(DefaultLoc, diag::err_default_special_members)
18603 << getLangOpts().CPlusPlus20;
18604 return;
18605 }
18606
18607 // Issue compatibility warning. We already warned if the operator is
18608 // 'operator<=>' when parsing the '<=>' token.
18609 if (DefKind.isComparison() &&
18610 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18611 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18612 ? diag::warn_cxx17_compat_defaulted_comparison
18613 : diag::ext_defaulted_comparison);
18614 }
18615
18616 FD->setDefaulted();
18617 FD->setExplicitlyDefaulted();
18618 FD->setDefaultLoc(DefaultLoc);
18619
18620 // Defer checking functions that are defaulted in a dependent context.
18621 if (FD->isDependentContext())
18622 return;
18623
18624 // Unset that we will have a body for this function. We might not,
18625 // if it turns out to be trivial, and we don't need this marking now
18626 // that we've marked it as defaulted.
18627 FD->setWillHaveBody(false);
18628
18629 if (DefKind.isComparison()) {
18630 // If this comparison's defaulting occurs within the definition of its
18631 // lexical class context, we have to do the checking when complete.
18632 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18633 if (!RD->isCompleteDefinition())
18634 return;
18635 }
18636
18637 // If this member fn was defaulted on its first declaration, we will have
18638 // already performed the checking in CheckCompletedCXXClass. Such a
18639 // declaration doesn't trigger an implicit definition.
18640 if (isa<CXXMethodDecl>(Val: FD)) {
18641 const FunctionDecl *Primary = FD;
18642 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18643 // Ask the template instantiation pattern that actually had the
18644 // '= default' on it.
18645 Primary = Pattern;
18646 if (Primary->getCanonicalDecl()->isDefaulted())
18647 return;
18648 }
18649
18650 if (DefKind.isComparison()) {
18651 if (CheckExplicitlyDefaultedComparison(S: nullptr, FD, DCK: DefKind.asComparison()))
18652 FD->setInvalidDecl();
18653 else
18654 DefineDefaultedComparison(UseLoc: DefaultLoc, FD, DCK: DefKind.asComparison());
18655 } else {
18656 auto *MD = cast<CXXMethodDecl>(Val: FD);
18657
18658 if (CheckExplicitlyDefaultedSpecialMember(MD, CSM: DefKind.asSpecialMember(),
18659 DefaultLoc))
18660 MD->setInvalidDecl();
18661 else
18662 DefineDefaultedFunction(*this, MD, DefaultLoc);
18663 }
18664}
18665
18666static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18667 for (Stmt *SubStmt : S->children()) {
18668 if (!SubStmt)
18669 continue;
18670 if (isa<ReturnStmt>(SubStmt))
18671 Self.Diag(SubStmt->getBeginLoc(),
18672 diag::err_return_in_constructor_handler);
18673 if (!isa<Expr>(Val: SubStmt))
18674 SearchForReturnInStmt(Self, S: SubStmt);
18675 }
18676}
18677
18678void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18679 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18680 CXXCatchStmt *Handler = TryBlock->getHandler(i: I);
18681 SearchForReturnInStmt(Self&: *this, S: Handler);
18682 }
18683}
18684
18685void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
18686 StringLiteral *DeletedMessage) {
18687 switch (BodyKind) {
18688 case FnBodyKind::Delete:
18689 SetDeclDeleted(Dcl: D, DelLoc: Loc, Message: DeletedMessage);
18690 break;
18691 case FnBodyKind::Default:
18692 SetDeclDefaulted(Dcl: D, DefaultLoc: Loc);
18693 break;
18694 case FnBodyKind::Other:
18695 llvm_unreachable(
18696 "Parsed function body should be '= delete;' or '= default;'");
18697 }
18698}
18699
18700bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
18701 const CXXMethodDecl *Old) {
18702 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18703 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18704
18705 if (OldFT->hasExtParameterInfos()) {
18706 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18707 // A parameter of the overriding method should be annotated with noescape
18708 // if the corresponding parameter of the overridden method is annotated.
18709 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18710 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18711 Diag(New->getParamDecl(I)->getLocation(),
18712 diag::warn_overriding_method_missing_noescape);
18713 Diag(Old->getParamDecl(I)->getLocation(),
18714 diag::note_overridden_marked_noescape);
18715 }
18716 }
18717
18718 // SME attributes must match when overriding a function declaration.
18719 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
18720 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18721 << New << New->getType() << Old->getType();
18722 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18723 return true;
18724 }
18725
18726 // Virtual overrides must have the same code_seg.
18727 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18728 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18729 if ((NewCSA || OldCSA) &&
18730 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18731 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18732 Diag(Old->getLocation(), diag::note_previous_declaration);
18733 return true;
18734 }
18735
18736 // Virtual overrides: check for matching effects.
18737 if (Context.hasAnyFunctionEffects()) {
18738 const auto OldFX = Old->getFunctionEffects();
18739 const auto NewFXOrig = New->getFunctionEffects();
18740
18741 if (OldFX != NewFXOrig) {
18742 FunctionEffectSet NewFX(NewFXOrig);
18743 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18744 FunctionEffectSet::Conflicts Errs;
18745 for (const auto &Diff : Diffs) {
18746 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18747 case FunctionEffectDiff::OverrideResult::NoAction:
18748 break;
18749 case FunctionEffectDiff::OverrideResult::Warn:
18750 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18751 << Diff.effectName();
18752 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18753 << Old->getReturnTypeSourceRange();
18754 break;
18755 case FunctionEffectDiff::OverrideResult::Merge: {
18756 NewFX.insert(Diff.Old.value(), Errs);
18757 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18758 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18759 EPI.FunctionEffects = FunctionEffectsRef(NewFX);
18760 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18761 NewFT->getParamTypes(), EPI);
18762 New->setType(ModQT);
18763 break;
18764 }
18765 }
18766 }
18767 if (!Errs.empty())
18768 diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
18769 Old->getLocation());
18770 }
18771 }
18772
18773 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18774
18775 // If the calling conventions match, everything is fine
18776 if (NewCC == OldCC)
18777 return false;
18778
18779 // If the calling conventions mismatch because the new function is static,
18780 // suppress the calling convention mismatch error; the error about static
18781 // function override (err_static_overrides_virtual from
18782 // Sema::CheckFunctionDeclaration) is more clear.
18783 if (New->getStorageClass() == SC_Static)
18784 return false;
18785
18786 Diag(New->getLocation(),
18787 diag::err_conflicting_overriding_cc_attributes)
18788 << New->getDeclName() << New->getType() << Old->getType();
18789 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18790 return true;
18791}
18792
18793bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
18794 const CXXMethodDecl *Old) {
18795 // CWG2553
18796 // A virtual function shall not be an explicit object member function.
18797 if (!New->isExplicitObjectMemberFunction())
18798 return true;
18799 Diag(New->getParamDecl(0)->getBeginLoc(),
18800 diag::err_explicit_object_parameter_nonmember)
18801 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18802 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18803 New->setInvalidDecl();
18804 return false;
18805}
18806
18807bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18808 const CXXMethodDecl *Old) {
18809 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18810 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18811
18812 if (Context.hasSameType(T1: NewTy, T2: OldTy) ||
18813 NewTy->isDependentType() || OldTy->isDependentType())
18814 return false;
18815
18816 // Check if the return types are covariant
18817 QualType NewClassTy, OldClassTy;
18818
18819 /// Both types must be pointers or references to classes.
18820 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18821 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18822 NewClassTy = NewPT->getPointeeType();
18823 OldClassTy = OldPT->getPointeeType();
18824 }
18825 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18826 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18827 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18828 NewClassTy = NewRT->getPointeeType();
18829 OldClassTy = OldRT->getPointeeType();
18830 }
18831 }
18832 }
18833
18834 // The return types aren't either both pointers or references to a class type.
18835 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
18836 Diag(New->getLocation(),
18837 diag::err_different_return_type_for_overriding_virtual_function)
18838 << New->getDeclName() << NewTy << OldTy
18839 << New->getReturnTypeSourceRange();
18840 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18841 << Old->getReturnTypeSourceRange();
18842
18843 return true;
18844 }
18845
18846 if (!Context.hasSameUnqualifiedType(T1: NewClassTy, T2: OldClassTy)) {
18847 // C++14 [class.virtual]p8:
18848 // If the class type in the covariant return type of D::f differs from
18849 // that of B::f, the class type in the return type of D::f shall be
18850 // complete at the point of declaration of D::f or shall be the class
18851 // type D.
18852 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18853 if (!RT->isBeingDefined() &&
18854 RequireCompleteType(New->getLocation(), NewClassTy,
18855 diag::err_covariant_return_incomplete,
18856 New->getDeclName()))
18857 return true;
18858 }
18859
18860 // Check if the new class derives from the old class.
18861 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18862 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18863 << New->getDeclName() << NewTy << OldTy
18864 << New->getReturnTypeSourceRange();
18865 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18866 << Old->getReturnTypeSourceRange();
18867 return true;
18868 }
18869
18870 // Check if we the conversion from derived to base is valid.
18871 if (CheckDerivedToBaseConversion(
18872 NewClassTy, OldClassTy,
18873 diag::err_covariant_return_inaccessible_base,
18874 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18875 New->getLocation(), New->getReturnTypeSourceRange(),
18876 New->getDeclName(), nullptr)) {
18877 // FIXME: this note won't trigger for delayed access control
18878 // diagnostics, and it's impossible to get an undelayed error
18879 // here from access control during the original parse because
18880 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18881 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18882 << Old->getReturnTypeSourceRange();
18883 return true;
18884 }
18885 }
18886
18887 // The qualifiers of the return types must be the same.
18888 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18889 Diag(New->getLocation(),
18890 diag::err_covariant_return_type_different_qualifications)
18891 << New->getDeclName() << NewTy << OldTy
18892 << New->getReturnTypeSourceRange();
18893 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18894 << Old->getReturnTypeSourceRange();
18895 return true;
18896 }
18897
18898
18899 // The new class type must have the same or less qualifiers as the old type.
18900 if (!OldClassTy.isAtLeastAsQualifiedAs(other: NewClassTy, Ctx: getASTContext())) {
18901 Diag(New->getLocation(),
18902 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
18903 << New->getDeclName() << NewTy << OldTy
18904 << New->getReturnTypeSourceRange();
18905 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18906 << Old->getReturnTypeSourceRange();
18907 return true;
18908 }
18909
18910 return false;
18911}
18912
18913bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
18914 SourceLocation EndLoc = InitRange.getEnd();
18915 if (EndLoc.isValid())
18916 Method->setRangeEnd(EndLoc);
18917
18918 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18919 Method->setIsPureVirtual();
18920 return false;
18921 }
18922
18923 if (!Method->isInvalidDecl())
18924 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18925 << Method->getDeclName() << InitRange;
18926 return true;
18927}
18928
18929void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
18930 if (D->getFriendObjectKind())
18931 Diag(D->getLocation(), diag::err_pure_friend);
18932 else if (auto *M = dyn_cast<CXXMethodDecl>(Val: D))
18933 CheckPureMethod(Method: M, InitRange: ZeroLoc);
18934 else
18935 Diag(D->getLocation(), diag::err_illegal_initializer);
18936}
18937
18938/// Invoked when we are about to parse an initializer for the declaration
18939/// 'Dcl'.
18940///
18941/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18942/// static data member of class X, names should be looked up in the scope of
18943/// class X. If the declaration had a scope specifier, a scope will have
18944/// been created and passed in for this purpose. Otherwise, S will be null.
18945void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
18946 assert(D && !D->isInvalidDecl());
18947
18948 // We will always have a nested name specifier here, but this declaration
18949 // might not be out of line if the specifier names the current namespace:
18950 // extern int n;
18951 // int ::n = 0;
18952 if (S && D->isOutOfLine())
18953 EnterDeclaratorContext(S, DC: D->getDeclContext());
18954
18955 PushExpressionEvaluationContext(
18956 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, LambdaContextDecl: D);
18957}
18958
18959void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
18960 assert(D);
18961
18962 if (S && D->isOutOfLine())
18963 ExitDeclaratorContext(S);
18964
18965 if (getLangOpts().CPlusPlus23) {
18966 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18967 // [...]
18968 // - the initializer of a variable that is usable in constant expressions or
18969 // has constant initialization.
18970 if (auto *VD = dyn_cast<VarDecl>(Val: D);
18971 VD && (VD->isUsableInConstantExpressions(C: Context) ||
18972 VD->hasConstantInitialization())) {
18973 // An expression or conversion is in an 'immediate function context' if it
18974 // is potentially evaluated and either:
18975 // [...]
18976 // - it is a subexpression of a manifestly constant-evaluated expression
18977 // or conversion.
18978 ExprEvalContexts.back().InImmediateFunctionContext = true;
18979 }
18980 }
18981
18982 // Unless the initializer is in an immediate function context (as determined
18983 // above), this will evaluate all contained immediate function calls as
18984 // constant expressions. If the initializer IS an immediate function context,
18985 // the initializer has been determined to be a constant expression, and all
18986 // such evaluations will be elided (i.e., as if we "knew the whole time" that
18987 // it was a constant expression).
18988 PopExpressionEvaluationContext();
18989}
18990
18991DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
18992 // C++ 6.4p2:
18993 // The declarator shall not specify a function or an array.
18994 // The type-specifier-seq shall not contain typedef and shall not declare a
18995 // new class or enumeration.
18996 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18997 "Parser allowed 'typedef' as storage class of condition decl.");
18998
18999 Decl *Dcl = ActOnDeclarator(S, D);
19000 if (!Dcl)
19001 return true;
19002
19003 if (isa<FunctionDecl>(Val: Dcl)) { // The declarator shall not specify a function.
19004 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
19005 << D.getSourceRange();
19006 return true;
19007 }
19008
19009 if (auto *VD = dyn_cast<VarDecl>(Val: Dcl))
19010 VD->setCXXCondDecl();
19011
19012 return Dcl;
19013}
19014
19015void Sema::LoadExternalVTableUses() {
19016 if (!ExternalSource)
19017 return;
19018
19019 SmallVector<ExternalVTableUse, 4> VTables;
19020 ExternalSource->ReadUsedVTables(VTables);
19021 SmallVector<VTableUse, 4> NewUses;
19022 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
19023 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
19024 = VTablesUsed.find(Val: VTables[I].Record);
19025 // Even if a definition wasn't required before, it may be required now.
19026 if (Pos != VTablesUsed.end()) {
19027 if (!Pos->second && VTables[I].DefinitionRequired)
19028 Pos->second = true;
19029 continue;
19030 }
19031
19032 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
19033 NewUses.push_back(Elt: VTableUse(VTables[I].Record, VTables[I].Location));
19034 }
19035
19036 VTableUses.insert(I: VTableUses.begin(), From: NewUses.begin(), To: NewUses.end());
19037}
19038
19039void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
19040 bool DefinitionRequired) {
19041 // Ignore any vtable uses in unevaluated operands or for classes that do
19042 // not have a vtable.
19043 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19044 CurContext->isDependentContext() || isUnevaluatedContext())
19045 return;
19046 // Do not mark as used if compiling for the device outside of the target
19047 // region.
19048 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19049 !OpenMP().isInOpenMPDeclareTargetContext() &&
19050 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19051 if (!DefinitionRequired)
19052 MarkVirtualMembersReferenced(Loc, RD: Class);
19053 return;
19054 }
19055
19056 // Try to insert this class into the map.
19057 LoadExternalVTableUses();
19058 Class = Class->getCanonicalDecl();
19059 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19060 Pos = VTablesUsed.insert(KV: std::make_pair(x&: Class, y&: DefinitionRequired));
19061 if (!Pos.second) {
19062 // If we already had an entry, check to see if we are promoting this vtable
19063 // to require a definition. If so, we need to reappend to the VTableUses
19064 // list, since we may have already processed the first entry.
19065 if (DefinitionRequired && !Pos.first->second) {
19066 Pos.first->second = true;
19067 } else {
19068 // Otherwise, we can early exit.
19069 return;
19070 }
19071 } else {
19072 // The Microsoft ABI requires that we perform the destructor body
19073 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19074 // the deleting destructor is emitted with the vtable, not with the
19075 // destructor definition as in the Itanium ABI.
19076 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19077 CXXDestructorDecl *DD = Class->getDestructor();
19078 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19079 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19080 // If this is an out-of-line declaration, marking it referenced will
19081 // not do anything. Manually call CheckDestructor to look up operator
19082 // delete().
19083 ContextRAII SavedContext(*this, DD);
19084 CheckDestructor(Destructor: DD);
19085 } else {
19086 MarkFunctionReferenced(Loc, Class->getDestructor());
19087 }
19088 }
19089 }
19090 }
19091
19092 // Local classes need to have their virtual members marked
19093 // immediately. For all other classes, we mark their virtual members
19094 // at the end of the translation unit.
19095 if (Class->isLocalClass())
19096 MarkVirtualMembersReferenced(Loc, RD: Class->getDefinition());
19097 else
19098 VTableUses.push_back(Elt: std::make_pair(x&: Class, y&: Loc));
19099}
19100
19101bool Sema::DefineUsedVTables() {
19102 LoadExternalVTableUses();
19103 if (VTableUses.empty())
19104 return false;
19105
19106 // Note: The VTableUses vector could grow as a result of marking
19107 // the members of a class as "used", so we check the size each
19108 // time through the loop and prefer indices (which are stable) to
19109 // iterators (which are not).
19110 bool DefinedAnything = false;
19111 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19112 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19113 if (!Class)
19114 continue;
19115 TemplateSpecializationKind ClassTSK =
19116 Class->getTemplateSpecializationKind();
19117
19118 SourceLocation Loc = VTableUses[I].second;
19119
19120 bool DefineVTable = true;
19121
19122 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(RD: Class);
19123 // V-tables for non-template classes with an owning module are always
19124 // uniquely emitted in that module.
19125 if (Class->isInCurrentModuleUnit()) {
19126 DefineVTable = true;
19127 } else if (KeyFunction && !KeyFunction->hasBody()) {
19128 // If this class has a key function, but that key function is
19129 // defined in another translation unit, we don't need to emit the
19130 // vtable even though we're using it.
19131 // The key function is in another translation unit.
19132 DefineVTable = false;
19133 TemplateSpecializationKind TSK =
19134 KeyFunction->getTemplateSpecializationKind();
19135 assert(TSK != TSK_ExplicitInstantiationDefinition &&
19136 TSK != TSK_ImplicitInstantiation &&
19137 "Instantiations don't have key functions");
19138 (void)TSK;
19139 } else if (!KeyFunction) {
19140 // If we have a class with no key function that is the subject
19141 // of an explicit instantiation declaration, suppress the
19142 // vtable; it will live with the explicit instantiation
19143 // definition.
19144 bool IsExplicitInstantiationDeclaration =
19145 ClassTSK == TSK_ExplicitInstantiationDeclaration;
19146 for (auto *R : Class->redecls()) {
19147 TemplateSpecializationKind TSK
19148 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
19149 if (TSK == TSK_ExplicitInstantiationDeclaration)
19150 IsExplicitInstantiationDeclaration = true;
19151 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19152 IsExplicitInstantiationDeclaration = false;
19153 break;
19154 }
19155 }
19156
19157 if (IsExplicitInstantiationDeclaration)
19158 DefineVTable = false;
19159 }
19160
19161 // The exception specifications for all virtual members may be needed even
19162 // if we are not providing an authoritative form of the vtable in this TU.
19163 // We may choose to emit it available_externally anyway.
19164 if (!DefineVTable) {
19165 MarkVirtualMemberExceptionSpecsNeeded(Loc, RD: Class);
19166 continue;
19167 }
19168
19169 // Mark all of the virtual members of this class as referenced, so
19170 // that we can build a vtable. Then, tell the AST consumer that a
19171 // vtable for this class is required.
19172 DefinedAnything = true;
19173 MarkVirtualMembersReferenced(Loc, RD: Class);
19174 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19175 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
19176 Consumer.HandleVTable(RD: Class);
19177
19178 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19179 // no key function or the key function is inlined. Don't warn in C++ ABIs
19180 // that lack key functions, since the user won't be able to make one.
19181 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19182 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
19183 ClassTSK != TSK_ExplicitInstantiationDefinition) {
19184 const FunctionDecl *KeyFunctionDef = nullptr;
19185 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
19186 KeyFunctionDef->isInlined()))
19187 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
19188 }
19189 }
19190 VTableUses.clear();
19191
19192 return DefinedAnything;
19193}
19194
19195void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
19196 const CXXRecordDecl *RD) {
19197 for (const auto *I : RD->methods())
19198 if (I->isVirtual() && !I->isPureVirtual())
19199 ResolveExceptionSpec(Loc, FPT: I->getType()->castAs<FunctionProtoType>());
19200}
19201
19202void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
19203 const CXXRecordDecl *RD,
19204 bool ConstexprOnly) {
19205 // Mark all functions which will appear in RD's vtable as used.
19206 CXXFinalOverriderMap FinalOverriders;
19207 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
19208 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
19209 E = FinalOverriders.end();
19210 I != E; ++I) {
19211 for (OverridingMethods::const_iterator OI = I->second.begin(),
19212 OE = I->second.end();
19213 OI != OE; ++OI) {
19214 assert(OI->second.size() > 0 && "no final overrider");
19215 CXXMethodDecl *Overrider = OI->second.front().Method;
19216
19217 // C++ [basic.def.odr]p2:
19218 // [...] A virtual member function is used if it is not pure. [...]
19219 if (!Overrider->isPureVirtual() &&
19220 (!ConstexprOnly || Overrider->isConstexpr()))
19221 MarkFunctionReferenced(Loc, Overrider);
19222 }
19223 }
19224
19225 // Only classes that have virtual bases need a VTT.
19226 if (RD->getNumVBases() == 0)
19227 return;
19228
19229 for (const auto &I : RD->bases()) {
19230 const auto *Base =
19231 cast<CXXRecordDecl>(Val: I.getType()->castAs<RecordType>()->getDecl());
19232 if (Base->getNumVBases() == 0)
19233 continue;
19234 MarkVirtualMembersReferenced(Loc, RD: Base);
19235 }
19236}
19237
19238static
19239void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
19240 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
19241 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
19242 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
19243 Sema &S) {
19244 if (Ctor->isInvalidDecl())
19245 return;
19246
19247 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
19248
19249 // Target may not be determinable yet, for instance if this is a dependent
19250 // call in an uninstantiated template.
19251 if (Target) {
19252 const FunctionDecl *FNTarget = nullptr;
19253 (void)Target->hasBody(FNTarget);
19254 Target = const_cast<CXXConstructorDecl*>(
19255 cast_or_null<CXXConstructorDecl>(Val: FNTarget));
19256 }
19257
19258 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19259 // Avoid dereferencing a null pointer here.
19260 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19261
19262 if (!Current.insert(Ptr: Canonical).second)
19263 return;
19264
19265 // We know that beyond here, we aren't chaining into a cycle.
19266 if (!Target || !Target->isDelegatingConstructor() ||
19267 Target->isInvalidDecl() || Valid.count(Ptr: TCanonical)) {
19268 Valid.insert_range(R&: Current);
19269 Current.clear();
19270 // We've hit a cycle.
19271 } else if (TCanonical == Canonical || Invalid.count(Ptr: TCanonical) ||
19272 Current.count(Ptr: TCanonical)) {
19273 // If we haven't diagnosed this cycle yet, do so now.
19274 if (!Invalid.count(Ptr: TCanonical)) {
19275 S.Diag((*Ctor->init_begin())->getSourceLocation(),
19276 diag::warn_delegating_ctor_cycle)
19277 << Ctor;
19278
19279 // Don't add a note for a function delegating directly to itself.
19280 if (TCanonical != Canonical)
19281 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
19282
19283 CXXConstructorDecl *C = Target;
19284 while (C->getCanonicalDecl() != Canonical) {
19285 const FunctionDecl *FNTarget = nullptr;
19286 (void)C->getTargetConstructor()->hasBody(FNTarget);
19287 assert(FNTarget && "Ctor cycle through bodiless function");
19288
19289 C = const_cast<CXXConstructorDecl*>(
19290 cast<CXXConstructorDecl>(Val: FNTarget));
19291 S.Diag(C->getLocation(), diag::note_which_delegates_to);
19292 }
19293 }
19294
19295 Invalid.insert_range(R&: Current);
19296 Current.clear();
19297 } else {
19298 DelegatingCycleHelper(Ctor: Target, Valid, Invalid, Current, S);
19299 }
19300}
19301
19302
19303void Sema::CheckDelegatingCtorCycles() {
19304 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
19305
19306 for (DelegatingCtorDeclsType::iterator
19307 I = DelegatingCtorDecls.begin(source: ExternalSource.get()),
19308 E = DelegatingCtorDecls.end();
19309 I != E; ++I)
19310 DelegatingCycleHelper(Ctor: *I, Valid, Invalid, Current, S&: *this);
19311
19312 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
19313 (*CI)->setInvalidDecl();
19314}
19315
19316namespace {
19317 /// AST visitor that finds references to the 'this' expression.
19318class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19319 Sema &S;
19320
19321public:
19322 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19323
19324 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19325 S.Diag(E->getLocation(), diag::err_this_static_member_func)
19326 << E->isImplicit();
19327 return false;
19328 }
19329};
19330}
19331
19332bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
19333 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19334 if (!TSInfo)
19335 return false;
19336
19337 TypeLoc TL = TSInfo->getTypeLoc();
19338 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19339 if (!ProtoTL)
19340 return false;
19341
19342 // C++11 [expr.prim.general]p3:
19343 // [The expression this] shall not appear before the optional
19344 // cv-qualifier-seq and it shall not appear within the declaration of a
19345 // static member function (although its type and value category are defined
19346 // within a static member function as they are within a non-static member
19347 // function). [ Note: this is because declaration matching does not occur
19348 // until the complete declarator is known. - end note ]
19349 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19350 FindCXXThisExpr Finder(*this);
19351
19352 // If the return type came after the cv-qualifier-seq, check it now.
19353 if (Proto->hasTrailingReturn() &&
19354 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19355 return true;
19356
19357 // Check the exception specification.
19358 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
19359 return true;
19360
19361 // Check the trailing requires clause
19362 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19363 if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))
19364 return true;
19365
19366 return checkThisInStaticMemberFunctionAttributes(Method);
19367}
19368
19369bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
19370 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19371 if (!TSInfo)
19372 return false;
19373
19374 TypeLoc TL = TSInfo->getTypeLoc();
19375 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19376 if (!ProtoTL)
19377 return false;
19378
19379 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19380 FindCXXThisExpr Finder(*this);
19381
19382 switch (Proto->getExceptionSpecType()) {
19383 case EST_Unparsed:
19384 case EST_Uninstantiated:
19385 case EST_Unevaluated:
19386 case EST_BasicNoexcept:
19387 case EST_NoThrow:
19388 case EST_DynamicNone:
19389 case EST_MSAny:
19390 case EST_None:
19391 break;
19392
19393 case EST_DependentNoexcept:
19394 case EST_NoexceptFalse:
19395 case EST_NoexceptTrue:
19396 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19397 return true;
19398 [[fallthrough]];
19399
19400 case EST_Dynamic:
19401 for (const auto &E : Proto->exceptions()) {
19402 if (!Finder.TraverseType(E))
19403 return true;
19404 }
19405 break;
19406 }
19407
19408 return false;
19409}
19410
19411bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19412 FindCXXThisExpr Finder(*this);
19413
19414 // Check attributes.
19415 for (const auto *A : Method->attrs()) {
19416 // FIXME: This should be emitted by tblgen.
19417 Expr *Arg = nullptr;
19418 ArrayRef<Expr *> Args;
19419 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19420 Arg = G->getArg();
19421 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19422 Arg = G->getArg();
19423 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19424 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19425 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19426 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19427 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19428 Arg = LR->getArg();
19429 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19430 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19431 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19432 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19433 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19434 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19435 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {
19436 Arg = AC->getSuccessValue();
19437 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19438 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19439 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19440
19441 if (Arg && !Finder.TraverseStmt(Arg))
19442 return true;
19443
19444 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
19445 if (!Finder.TraverseStmt(Args[I]))
19446 return true;
19447 }
19448 }
19449
19450 return false;
19451}
19452
19453void Sema::checkExceptionSpecification(
19454 bool IsTopLevel, ExceptionSpecificationType EST,
19455 ArrayRef<ParsedType> DynamicExceptions,
19456 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19457 SmallVectorImpl<QualType> &Exceptions,
19458 FunctionProtoType::ExceptionSpecInfo &ESI) {
19459 Exceptions.clear();
19460 ESI.Type = EST;
19461 if (EST == EST_Dynamic) {
19462 Exceptions.reserve(N: DynamicExceptions.size());
19463 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19464 // FIXME: Preserve type source info.
19465 QualType ET = GetTypeFromParser(Ty: DynamicExceptions[ei]);
19466
19467 if (IsTopLevel) {
19468 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19469 collectUnexpandedParameterPacks(T: ET, Unexpanded);
19470 if (!Unexpanded.empty()) {
19471 DiagnoseUnexpandedParameterPacks(
19472 Loc: DynamicExceptionRanges[ei].getBegin(), UPPC: UPPC_ExceptionType,
19473 Unexpanded);
19474 continue;
19475 }
19476 }
19477
19478 // Check that the type is valid for an exception spec, and
19479 // drop it if not.
19480 if (!CheckSpecifiedExceptionType(T&: ET, Range: DynamicExceptionRanges[ei]))
19481 Exceptions.push_back(Elt: ET);
19482 }
19483 ESI.Exceptions = Exceptions;
19484 return;
19485 }
19486
19487 if (isComputedNoexcept(ESpecType: EST)) {
19488 assert((NoexceptExpr->isTypeDependent() ||
19489 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19490 Context.BoolTy) &&
19491 "Parser should have made sure that the expression is boolean");
19492 if (IsTopLevel && DiagnoseUnexpandedParameterPack(E: NoexceptExpr)) {
19493 ESI.Type = EST_BasicNoexcept;
19494 return;
19495 }
19496
19497 ESI.NoexceptExpr = NoexceptExpr;
19498 return;
19499 }
19500}
19501
19502void Sema::actOnDelayedExceptionSpecification(
19503 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19504 ArrayRef<ParsedType> DynamicExceptions,
19505 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19506 if (!D)
19507 return;
19508
19509 // Dig out the function we're referring to.
19510 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
19511 D = FTD->getTemplatedDecl();
19512
19513 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D);
19514 if (!FD)
19515 return;
19516
19517 // Check the exception specification.
19518 llvm::SmallVector<QualType, 4> Exceptions;
19519 FunctionProtoType::ExceptionSpecInfo ESI;
19520 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19521 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19522 ESI);
19523
19524 // Update the exception specification on the function type.
19525 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19526
19527 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
19528 if (MD->isStatic())
19529 checkThisInStaticMemberFunctionExceptionSpec(Method: MD);
19530
19531 if (MD->isVirtual()) {
19532 // Check overrides, which we previously had to delay.
19533 for (const CXXMethodDecl *O : MD->overridden_methods())
19534 CheckOverridingFunctionExceptionSpec(New: MD, Old: O);
19535 }
19536 }
19537}
19538
19539/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19540///
19541MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19542 SourceLocation DeclStart, Declarator &D,
19543 Expr *BitWidth,
19544 InClassInitStyle InitStyle,
19545 AccessSpecifier AS,
19546 const ParsedAttr &MSPropertyAttr) {
19547 const IdentifierInfo *II = D.getIdentifier();
19548 if (!II) {
19549 Diag(DeclStart, diag::err_anonymous_property);
19550 return nullptr;
19551 }
19552 SourceLocation Loc = D.getIdentifierLoc();
19553
19554 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19555 QualType T = TInfo->getType();
19556 if (getLangOpts().CPlusPlus) {
19557 CheckExtraCXXDefaultArguments(D);
19558
19559 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19560 UPPC: UPPC_DataMemberType)) {
19561 D.setInvalidType();
19562 T = Context.IntTy;
19563 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19564 }
19565 }
19566
19567 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19568
19569 if (D.getDeclSpec().isInlineSpecified())
19570 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19571 << getLangOpts().CPlusPlus17;
19572 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19573 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
19574 diag::err_invalid_thread)
19575 << DeclSpec::getSpecifierName(TSCS);
19576
19577 // Check to see if this name was declared as a member previously
19578 NamedDecl *PrevDecl = nullptr;
19579 LookupResult Previous(*this, II, Loc, LookupMemberName,
19580 RedeclarationKind::ForVisibleRedeclaration);
19581 LookupName(R&: Previous, S);
19582 switch (Previous.getResultKind()) {
19583 case LookupResultKind::Found:
19584 case LookupResultKind::FoundUnresolvedValue:
19585 PrevDecl = Previous.getAsSingle<NamedDecl>();
19586 break;
19587
19588 case LookupResultKind::FoundOverloaded:
19589 PrevDecl = Previous.getRepresentativeDecl();
19590 break;
19591
19592 case LookupResultKind::NotFound:
19593 case LookupResultKind::NotFoundInCurrentInstantiation:
19594 case LookupResultKind::Ambiguous:
19595 break;
19596 }
19597
19598 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19599 // Maybe we will complain about the shadowed template parameter.
19600 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
19601 // Just pretend that we didn't see the previous declaration.
19602 PrevDecl = nullptr;
19603 }
19604
19605 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19606 PrevDecl = nullptr;
19607
19608 SourceLocation TSSL = D.getBeginLoc();
19609 MSPropertyDecl *NewPD =
19610 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19611 MSPropertyAttr.getPropertyDataGetter(),
19612 MSPropertyAttr.getPropertyDataSetter());
19613 ProcessDeclAttributes(TUScope, NewPD, D);
19614 NewPD->setAccess(AS);
19615
19616 if (NewPD->isInvalidDecl())
19617 Record->setInvalidDecl();
19618
19619 if (D.getDeclSpec().isModulePrivateSpecified())
19620 NewPD->setModulePrivate();
19621
19622 if (NewPD->isInvalidDecl() && PrevDecl) {
19623 // Don't introduce NewFD into scope; there's already something
19624 // with the same name in the same scope.
19625 } else if (II) {
19626 PushOnScopeChains(NewPD, S);
19627 } else
19628 Record->addDecl(NewPD);
19629
19630 return NewPD;
19631}
19632
19633void Sema::ActOnStartFunctionDeclarationDeclarator(
19634 Declarator &Declarator, unsigned TemplateParameterDepth) {
19635 auto &Info = InventedParameterInfos.emplace_back();
19636 TemplateParameterList *ExplicitParams = nullptr;
19637 ArrayRef<TemplateParameterList *> ExplicitLists =
19638 Declarator.getTemplateParameterLists();
19639 if (!ExplicitLists.empty()) {
19640 bool IsMemberSpecialization, IsInvalid;
19641 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19642 DeclStartLoc: Declarator.getBeginLoc(), DeclLoc: Declarator.getIdentifierLoc(),
19643 SS: Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19644 ParamLists: ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, Invalid&: IsInvalid,
19645 /*SuppressDiagnostic=*/true);
19646 }
19647 // C++23 [dcl.fct]p23:
19648 // An abbreviated function template can have a template-head. The invented
19649 // template-parameters are appended to the template-parameter-list after
19650 // the explicitly declared template-parameters.
19651 //
19652 // A template-head must have one or more template-parameters (read:
19653 // 'template<>' is *not* a template-head). Only append the invented
19654 // template parameters if we matched the nested-name-specifier to a non-empty
19655 // TemplateParameterList.
19656 if (ExplicitParams && !ExplicitParams->empty()) {
19657 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19658 llvm::append_range(C&: Info.TemplateParams, R&: *ExplicitParams);
19659 Info.NumExplicitTemplateParams = ExplicitParams->size();
19660 } else {
19661 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19662 Info.NumExplicitTemplateParams = 0;
19663 }
19664}
19665
19666void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19667 auto &FSI = InventedParameterInfos.back();
19668 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19669 if (FSI.NumExplicitTemplateParams != 0) {
19670 TemplateParameterList *ExplicitParams =
19671 Declarator.getTemplateParameterLists().back();
19672 Declarator.setInventedTemplateParameterList(
19673 TemplateParameterList::Create(
19674 C: Context, TemplateLoc: ExplicitParams->getTemplateLoc(),
19675 LAngleLoc: ExplicitParams->getLAngleLoc(), Params: FSI.TemplateParams,
19676 RAngleLoc: ExplicitParams->getRAngleLoc(),
19677 RequiresClause: ExplicitParams->getRequiresClause()));
19678 } else {
19679 Declarator.setInventedTemplateParameterList(
19680 TemplateParameterList::Create(
19681 C: Context, TemplateLoc: SourceLocation(), LAngleLoc: SourceLocation(), Params: FSI.TemplateParams,
19682 RAngleLoc: SourceLocation(), /*RequiresClause=*/nullptr));
19683 }
19684 }
19685 InventedParameterInfos.pop_back();
19686}
19687

Provided by KDAB

Privacy Policy
Learn to use CMake with our Intro Training
Find out more

source code of clang/lib/Sema/SemaDeclCXX.cpp