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/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/AST/RecursiveASTVisitor.h"
27#include "clang/AST/StmtVisitor.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/AST/TypeOrdering.h"
30#include "clang/Basic/AttributeCommonInfo.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/Specifiers.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Lex/LiteralSupport.h"
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Sema/CXXFieldCollector.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/EnterExpressionEvaluationContext.h"
39#include "clang/Sema/Initialization.h"
40#include "clang/Sema/Lookup.h"
41#include "clang/Sema/Ownership.h"
42#include "clang/Sema/ParsedTemplate.h"
43#include "clang/Sema/Scope.h"
44#include "clang/Sema/ScopeInfo.h"
45#include "clang/Sema/SemaInternal.h"
46#include "clang/Sema/Template.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/STLExtras.h"
49#include "llvm/ADT/ScopeExit.h"
50#include "llvm/ADT/SmallString.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/Support/ConvertUTF.h"
53#include "llvm/Support/SaveAndRestore.h"
54#include <map>
55#include <optional>
56#include <set>
57
58using namespace clang;
59
60//===----------------------------------------------------------------------===//
61// CheckDefaultArgumentVisitor
62//===----------------------------------------------------------------------===//
63
64namespace {
65/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
66/// the default argument of a parameter to determine whether it
67/// contains any ill-formed subexpressions. For example, this will
68/// diagnose the use of local variables or parameters within the
69/// default argument expression.
70class CheckDefaultArgumentVisitor
71 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
72 Sema &S;
73 const Expr *DefaultArg;
74
75public:
76 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
77 : S(S), DefaultArg(DefaultArg) {}
78
79 bool VisitExpr(const Expr *Node);
80 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
81 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
82 bool VisitLambdaExpr(const LambdaExpr *Lambda);
83 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
84};
85
86/// VisitExpr - Visit all of the children of this expression.
87bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
88 bool IsInvalid = false;
89 for (const Stmt *SubStmt : Node->children())
90 if (SubStmt)
91 IsInvalid |= Visit(SubStmt);
92 return IsInvalid;
93}
94
95/// VisitDeclRefExpr - Visit a reference to a declaration, to
96/// determine whether this declaration can be used in the default
97/// argument expression.
98bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
99 const ValueDecl *Decl = dyn_cast<ValueDecl>(Val: DRE->getDecl());
100
101 if (!isa<VarDecl, BindingDecl>(Val: Decl))
102 return false;
103
104 if (const auto *Param = dyn_cast<ParmVarDecl>(Val: Decl)) {
105 // C++ [dcl.fct.default]p9:
106 // [...] parameters of a function shall not be used in default
107 // argument expressions, even if they are not evaluated. [...]
108 //
109 // C++17 [dcl.fct.default]p9 (by CWG 2082):
110 // [...] A parameter shall not appear as a potentially-evaluated
111 // expression in a default argument. [...]
112 //
113 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
114 return S.Diag(DRE->getBeginLoc(),
115 diag::err_param_default_argument_references_param)
116 << Param->getDeclName() << DefaultArg->getSourceRange();
117 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
118 // C++ [dcl.fct.default]p7:
119 // Local variables shall not be used in default argument
120 // expressions.
121 //
122 // C++17 [dcl.fct.default]p7 (by CWG 2082):
123 // A local variable shall not appear as a potentially-evaluated
124 // expression in a default argument.
125 //
126 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
127 // Note: A local variable cannot be odr-used (6.3) in a default
128 // argument.
129 //
130 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
131 return S.Diag(DRE->getBeginLoc(),
132 diag::err_param_default_argument_references_local)
133 << Decl << DefaultArg->getSourceRange();
134 }
135 return false;
136}
137
138/// VisitCXXThisExpr - Visit a C++ "this" expression.
139bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
140 // C++ [dcl.fct.default]p8:
141 // The keyword this shall not be used in a default argument of a
142 // member function.
143 return S.Diag(ThisE->getBeginLoc(),
144 diag::err_param_default_argument_references_this)
145 << ThisE->getSourceRange();
146}
147
148bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
149 const PseudoObjectExpr *POE) {
150 bool Invalid = false;
151 for (const Expr *E : POE->semantics()) {
152 // Look through bindings.
153 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
154 E = OVE->getSourceExpr();
155 assert(E && "pseudo-object binding without source expression?");
156 }
157
158 Invalid |= Visit(E);
159 }
160 return Invalid;
161}
162
163bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
164 // [expr.prim.lambda.capture]p9
165 // a lambda-expression appearing in a default argument cannot implicitly or
166 // explicitly capture any local entity. Such a lambda-expression can still
167 // have an init-capture if any full-expression in its initializer satisfies
168 // the constraints of an expression appearing in a default argument.
169 bool Invalid = false;
170 for (const LambdaCapture &LC : Lambda->captures()) {
171 if (!Lambda->isInitCapture(&LC))
172 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
173 // Init captures are always VarDecl.
174 auto *D = cast<VarDecl>(Val: LC.getCapturedVar());
175 Invalid |= Visit(D->getInit());
176 }
177 return Invalid;
178}
179} // namespace
180
181void
182Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
183 const CXXMethodDecl *Method) {
184 // If we have an MSAny spec already, don't bother.
185 if (!Method || ComputedEST == EST_MSAny)
186 return;
187
188 const FunctionProtoType *Proto
189 = Method->getType()->getAs<FunctionProtoType>();
190 Proto = Self->ResolveExceptionSpec(Loc: CallLoc, FPT: Proto);
191 if (!Proto)
192 return;
193
194 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
195
196 // If we have a throw-all spec at this point, ignore the function.
197 if (ComputedEST == EST_None)
198 return;
199
200 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
201 EST = EST_BasicNoexcept;
202
203 switch (EST) {
204 case EST_Unparsed:
205 case EST_Uninstantiated:
206 case EST_Unevaluated:
207 llvm_unreachable("should not see unresolved exception specs here");
208
209 // If this function can throw any exceptions, make a note of that.
210 case EST_MSAny:
211 case EST_None:
212 // FIXME: Whichever we see last of MSAny and None determines our result.
213 // We should make a consistent, order-independent choice here.
214 ClearExceptions();
215 ComputedEST = EST;
216 return;
217 case EST_NoexceptFalse:
218 ClearExceptions();
219 ComputedEST = EST_None;
220 return;
221 // FIXME: If the call to this decl is using any of its default arguments, we
222 // need to search them for potentially-throwing calls.
223 // If this function has a basic noexcept, it doesn't affect the outcome.
224 case EST_BasicNoexcept:
225 case EST_NoexceptTrue:
226 case EST_NoThrow:
227 return;
228 // If we're still at noexcept(true) and there's a throw() callee,
229 // change to that specification.
230 case EST_DynamicNone:
231 if (ComputedEST == EST_BasicNoexcept)
232 ComputedEST = EST_DynamicNone;
233 return;
234 case EST_DependentNoexcept:
235 llvm_unreachable(
236 "should not generate implicit declarations for dependent cases");
237 case EST_Dynamic:
238 break;
239 }
240 assert(EST == EST_Dynamic && "EST case not considered earlier.");
241 assert(ComputedEST != EST_None &&
242 "Shouldn't collect exceptions when throw-all is guaranteed.");
243 ComputedEST = EST_Dynamic;
244 // Record the exceptions in this function's exception specification.
245 for (const auto &E : Proto->exceptions())
246 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
247 Exceptions.push_back(E);
248}
249
250void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
251 if (!S || ComputedEST == EST_MSAny)
252 return;
253
254 // FIXME:
255 //
256 // C++0x [except.spec]p14:
257 // [An] implicit exception-specification specifies the type-id T if and
258 // only if T is allowed by the exception-specification of a function directly
259 // invoked by f's implicit definition; f shall allow all exceptions if any
260 // function it directly invokes allows all exceptions, and f shall allow no
261 // exceptions if every function it directly invokes allows no exceptions.
262 //
263 // Note in particular that if an implicit exception-specification is generated
264 // for a function containing a throw-expression, that specification can still
265 // be noexcept(true).
266 //
267 // Note also that 'directly invoked' is not defined in the standard, and there
268 // is no indication that we should only consider potentially-evaluated calls.
269 //
270 // Ultimately we should implement the intent of the standard: the exception
271 // specification should be the set of exceptions which can be thrown by the
272 // implicit definition. For now, we assume that any non-nothrow expression can
273 // throw any exception.
274
275 if (Self->canThrow(E: S))
276 ComputedEST = EST_None;
277}
278
279ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
280 SourceLocation EqualLoc) {
281 if (RequireCompleteType(Param->getLocation(), Param->getType(),
282 diag::err_typecheck_decl_incomplete_type))
283 return true;
284
285 // C++ [dcl.fct.default]p5
286 // A default argument expression is implicitly converted (clause
287 // 4) to the parameter type. The default argument expression has
288 // the same semantic constraints as the initializer expression in
289 // a declaration of a variable of the parameter type, using the
290 // copy-initialization semantics (8.5).
291 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
292 Parm: Param);
293 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Param->getLocation(),
294 EqualLoc);
295 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
296 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Arg);
297 if (Result.isInvalid())
298 return true;
299 Arg = Result.getAs<Expr>();
300
301 CheckCompletedExpr(E: Arg, CheckLoc: EqualLoc);
302 Arg = MaybeCreateExprWithCleanups(SubExpr: Arg);
303
304 return Arg;
305}
306
307void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
308 SourceLocation EqualLoc) {
309 // Add the default argument to the parameter
310 Param->setDefaultArg(Arg);
311
312 // We have already instantiated this parameter; provide each of the
313 // instantiations with the uninstantiated default argument.
314 UnparsedDefaultArgInstantiationsMap::iterator InstPos
315 = UnparsedDefaultArgInstantiations.find(Val: Param);
316 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
317 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
318 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
319
320 // We're done tracking this parameter's instantiations.
321 UnparsedDefaultArgInstantiations.erase(I: InstPos);
322 }
323}
324
325/// ActOnParamDefaultArgument - Check whether the default argument
326/// provided for a function parameter is well-formed. If so, attach it
327/// to the parameter declaration.
328void
329Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
330 Expr *DefaultArg) {
331 if (!param || !DefaultArg)
332 return;
333
334 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
335 UnparsedDefaultArgLocs.erase(Val: Param);
336
337 // Default arguments are only permitted in C++
338 if (!getLangOpts().CPlusPlus) {
339 Diag(EqualLoc, diag::err_param_default_argument)
340 << DefaultArg->getSourceRange();
341 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
342 }
343
344 // Check for unexpanded parameter packs.
345 if (DiagnoseUnexpandedParameterPack(E: DefaultArg, UPPC: UPPC_DefaultArgument))
346 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
347
348 // C++11 [dcl.fct.default]p3
349 // A default argument expression [...] shall not be specified for a
350 // parameter pack.
351 if (Param->isParameterPack()) {
352 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
353 << DefaultArg->getSourceRange();
354 // Recover by discarding the default argument.
355 Param->setDefaultArg(nullptr);
356 return;
357 }
358
359 ExprResult Result = ConvertParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
360 if (Result.isInvalid())
361 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
362
363 DefaultArg = Result.getAs<Expr>();
364
365 // Check that the default argument is well-formed
366 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
367 if (DefaultArgChecker.Visit(DefaultArg))
368 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
369
370 SetParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
371}
372
373/// ActOnParamUnparsedDefaultArgument - We've seen a default
374/// argument for a function parameter, but we can't parse it yet
375/// because we're inside a class definition. Note that this default
376/// argument will be parsed later.
377void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
378 SourceLocation EqualLoc,
379 SourceLocation ArgLoc) {
380 if (!param)
381 return;
382
383 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
384 Param->setUnparsedDefaultArg();
385 UnparsedDefaultArgLocs[Param] = ArgLoc;
386}
387
388/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
389/// the default argument for the parameter param failed.
390void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
391 Expr *DefaultArg) {
392 if (!param)
393 return;
394
395 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
396 Param->setInvalidDecl();
397 UnparsedDefaultArgLocs.erase(Val: Param);
398 ExprResult RE;
399 if (DefaultArg) {
400 RE = CreateRecoveryExpr(Begin: EqualLoc, End: DefaultArg->getEndLoc(), SubExprs: {DefaultArg},
401 T: Param->getType().getNonReferenceType());
402 } else {
403 RE = CreateRecoveryExpr(Begin: EqualLoc, End: EqualLoc, SubExprs: {},
404 T: Param->getType().getNonReferenceType());
405 }
406 Param->setDefaultArg(RE.get());
407}
408
409/// CheckExtraCXXDefaultArguments - Check for any extra default
410/// arguments in the declarator, which is not a function declaration
411/// or definition and therefore is not permitted to have default
412/// arguments. This routine should be invoked for every declarator
413/// that is not a function declaration or definition.
414void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
415 // C++ [dcl.fct.default]p3
416 // A default argument expression shall be specified only in the
417 // parameter-declaration-clause of a function declaration or in a
418 // template-parameter (14.1). It shall not be specified for a
419 // parameter pack. If it is specified in a
420 // parameter-declaration-clause, it shall not occur within a
421 // declarator or abstract-declarator of a parameter-declaration.
422 bool MightBeFunction = D.isFunctionDeclarationContext();
423 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
424 DeclaratorChunk &chunk = D.getTypeObject(i);
425 if (chunk.Kind == DeclaratorChunk::Function) {
426 if (MightBeFunction) {
427 // This is a function declaration. It can have default arguments, but
428 // keep looking in case its return type is a function type with default
429 // arguments.
430 MightBeFunction = false;
431 continue;
432 }
433 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
434 ++argIdx) {
435 ParmVarDecl *Param = cast<ParmVarDecl>(Val: chunk.Fun.Params[argIdx].Param);
436 if (Param->hasUnparsedDefaultArg()) {
437 std::unique_ptr<CachedTokens> Toks =
438 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
439 SourceRange SR;
440 if (Toks->size() > 1)
441 SR = SourceRange((*Toks)[1].getLocation(),
442 Toks->back().getLocation());
443 else
444 SR = UnparsedDefaultArgLocs[Param];
445 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
446 << SR;
447 } else if (Param->getDefaultArg()) {
448 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
449 << Param->getDefaultArg()->getSourceRange();
450 Param->setDefaultArg(nullptr);
451 }
452 }
453 } else if (chunk.Kind != DeclaratorChunk::Paren) {
454 MightBeFunction = false;
455 }
456 }
457}
458
459static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
460 return llvm::any_of(Range: FD->parameters(), P: [](ParmVarDecl *P) {
461 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
462 });
463}
464
465/// MergeCXXFunctionDecl - Merge two declarations of the same C++
466/// function, once we already know that they have the same
467/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
468/// error, false otherwise.
469bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
470 Scope *S) {
471 bool Invalid = false;
472
473 // The declaration context corresponding to the scope is the semantic
474 // parent, unless this is a local function declaration, in which case
475 // it is that surrounding function.
476 DeclContext *ScopeDC = New->isLocalExternDecl()
477 ? New->getLexicalDeclContext()
478 : New->getDeclContext();
479
480 // Find the previous declaration for the purpose of default arguments.
481 FunctionDecl *PrevForDefaultArgs = Old;
482 for (/**/; PrevForDefaultArgs;
483 // Don't bother looking back past the latest decl if this is a local
484 // extern declaration; nothing else could work.
485 PrevForDefaultArgs = New->isLocalExternDecl()
486 ? nullptr
487 : PrevForDefaultArgs->getPreviousDecl()) {
488 // Ignore hidden declarations.
489 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
490 continue;
491
492 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
493 !New->isCXXClassMember()) {
494 // Ignore default arguments of old decl if they are not in
495 // the same scope and this is not an out-of-line definition of
496 // a member function.
497 continue;
498 }
499
500 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
501 // If only one of these is a local function declaration, then they are
502 // declared in different scopes, even though isDeclInScope may think
503 // they're in the same scope. (If both are local, the scope check is
504 // sufficient, and if neither is local, then they are in the same scope.)
505 continue;
506 }
507
508 // We found the right previous declaration.
509 break;
510 }
511
512 // C++ [dcl.fct.default]p4:
513 // For non-template functions, default arguments can be added in
514 // later declarations of a function in the same
515 // scope. Declarations in different scopes have completely
516 // distinct sets of default arguments. That is, declarations in
517 // inner scopes do not acquire default arguments from
518 // declarations in outer scopes, and vice versa. In a given
519 // function declaration, all parameters subsequent to a
520 // parameter with a default argument shall have default
521 // arguments supplied in this or previous declarations. A
522 // default argument shall not be redefined by a later
523 // declaration (not even to the same value).
524 //
525 // C++ [dcl.fct.default]p6:
526 // Except for member functions of class templates, the default arguments
527 // in a member function definition that appears outside of the class
528 // definition are added to the set of default arguments provided by the
529 // member function declaration in the class definition.
530 for (unsigned p = 0, NumParams = PrevForDefaultArgs
531 ? PrevForDefaultArgs->getNumParams()
532 : 0;
533 p < NumParams; ++p) {
534 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(i: p);
535 ParmVarDecl *NewParam = New->getParamDecl(i: p);
536
537 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
538 bool NewParamHasDfl = NewParam->hasDefaultArg();
539
540 if (OldParamHasDfl && NewParamHasDfl) {
541 unsigned DiagDefaultParamID =
542 diag::err_param_default_argument_redefinition;
543
544 // MSVC accepts that default parameters be redefined for member functions
545 // of template class. The new default parameter's value is ignored.
546 Invalid = true;
547 if (getLangOpts().MicrosoftExt) {
548 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: New);
549 if (MD && MD->getParent()->getDescribedClassTemplate()) {
550 // Merge the old default argument into the new parameter.
551 NewParam->setHasInheritedDefaultArg();
552 if (OldParam->hasUninstantiatedDefaultArg())
553 NewParam->setUninstantiatedDefaultArg(
554 OldParam->getUninstantiatedDefaultArg());
555 else
556 NewParam->setDefaultArg(OldParam->getInit());
557 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
558 Invalid = false;
559 }
560 }
561
562 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
563 // hint here. Alternatively, we could walk the type-source information
564 // for NewParam to find the last source location in the type... but it
565 // isn't worth the effort right now. This is the kind of test case that
566 // is hard to get right:
567 // int f(int);
568 // void g(int (*fp)(int) = f);
569 // void g(int (*fp)(int) = &f);
570 Diag(NewParam->getLocation(), DiagDefaultParamID)
571 << NewParam->getDefaultArgRange();
572
573 // Look for the function declaration where the default argument was
574 // actually written, which may be a declaration prior to Old.
575 for (auto Older = PrevForDefaultArgs;
576 OldParam->hasInheritedDefaultArg(); /**/) {
577 Older = Older->getPreviousDecl();
578 OldParam = Older->getParamDecl(i: p);
579 }
580
581 Diag(OldParam->getLocation(), diag::note_previous_definition)
582 << OldParam->getDefaultArgRange();
583 } else if (OldParamHasDfl) {
584 // Merge the old default argument into the new parameter unless the new
585 // function is a friend declaration in a template class. In the latter
586 // case the default arguments will be inherited when the friend
587 // declaration will be instantiated.
588 if (New->getFriendObjectKind() == Decl::FOK_None ||
589 !New->getLexicalDeclContext()->isDependentContext()) {
590 // It's important to use getInit() here; getDefaultArg()
591 // strips off any top-level ExprWithCleanups.
592 NewParam->setHasInheritedDefaultArg();
593 if (OldParam->hasUnparsedDefaultArg())
594 NewParam->setUnparsedDefaultArg();
595 else if (OldParam->hasUninstantiatedDefaultArg())
596 NewParam->setUninstantiatedDefaultArg(
597 OldParam->getUninstantiatedDefaultArg());
598 else
599 NewParam->setDefaultArg(OldParam->getInit());
600 }
601 } else if (NewParamHasDfl) {
602 if (New->getDescribedFunctionTemplate()) {
603 // Paragraph 4, quoted above, only applies to non-template functions.
604 Diag(NewParam->getLocation(),
605 diag::err_param_default_argument_template_redecl)
606 << NewParam->getDefaultArgRange();
607 Diag(PrevForDefaultArgs->getLocation(),
608 diag::note_template_prev_declaration)
609 << false;
610 } else if (New->getTemplateSpecializationKind()
611 != TSK_ImplicitInstantiation &&
612 New->getTemplateSpecializationKind() != TSK_Undeclared) {
613 // C++ [temp.expr.spec]p21:
614 // Default function arguments shall not be specified in a declaration
615 // or a definition for one of the following explicit specializations:
616 // - the explicit specialization of a function template;
617 // - the explicit specialization of a member function template;
618 // - the explicit specialization of a member function of a class
619 // template where the class template specialization to which the
620 // member function specialization belongs is implicitly
621 // instantiated.
622 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
623 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
624 << New->getDeclName()
625 << NewParam->getDefaultArgRange();
626 } else if (New->getDeclContext()->isDependentContext()) {
627 // C++ [dcl.fct.default]p6 (DR217):
628 // Default arguments for a member function of a class template shall
629 // be specified on the initial declaration of the member function
630 // within the class template.
631 //
632 // Reading the tea leaves a bit in DR217 and its reference to DR205
633 // leads me to the conclusion that one cannot add default function
634 // arguments for an out-of-line definition of a member function of a
635 // dependent type.
636 int WhichKind = 2;
637 if (CXXRecordDecl *Record
638 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
639 if (Record->getDescribedClassTemplate())
640 WhichKind = 0;
641 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Record))
642 WhichKind = 1;
643 else
644 WhichKind = 2;
645 }
646
647 Diag(NewParam->getLocation(),
648 diag::err_param_default_argument_member_template_redecl)
649 << WhichKind
650 << NewParam->getDefaultArgRange();
651 }
652 }
653 }
654
655 // DR1344: If a default argument is added outside a class definition and that
656 // default argument makes the function a special member function, the program
657 // is ill-formed. This can only happen for constructors.
658 if (isa<CXXConstructorDecl>(Val: New) &&
659 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
660 CXXSpecialMember NewSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: New)),
661 OldSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: Old));
662 if (NewSM != OldSM) {
663 ParmVarDecl *NewParam = New->getParamDecl(i: New->getMinRequiredArguments());
664 assert(NewParam->hasDefaultArg());
665 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
666 << NewParam->getDefaultArgRange() << NewSM;
667 Diag(Old->getLocation(), diag::note_previous_declaration);
668 }
669 }
670
671 const FunctionDecl *Def;
672 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
673 // template has a constexpr specifier then all its declarations shall
674 // contain the constexpr specifier.
675 if (New->getConstexprKind() != Old->getConstexprKind()) {
676 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
677 << New << static_cast<int>(New->getConstexprKind())
678 << static_cast<int>(Old->getConstexprKind());
679 Diag(Old->getLocation(), diag::note_previous_declaration);
680 Invalid = true;
681 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
682 Old->isDefined(Definition&: Def) &&
683 // If a friend function is inlined but does not have 'inline'
684 // specifier, it is a definition. Do not report attribute conflict
685 // in this case, redefinition will be diagnosed later.
686 (New->isInlineSpecified() ||
687 New->getFriendObjectKind() == Decl::FOK_None)) {
688 // C++11 [dcl.fcn.spec]p4:
689 // If the definition of a function appears in a translation unit before its
690 // first declaration as inline, the program is ill-formed.
691 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
692 Diag(Def->getLocation(), diag::note_previous_definition);
693 Invalid = true;
694 }
695
696 // C++17 [temp.deduct.guide]p3:
697 // Two deduction guide declarations in the same translation unit
698 // for the same class template shall not have equivalent
699 // parameter-declaration-clauses.
700 if (isa<CXXDeductionGuideDecl>(Val: New) &&
701 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
702 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
703 Diag(Old->getLocation(), diag::note_previous_declaration);
704 }
705
706 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
707 // argument expression, that declaration shall be a definition and shall be
708 // the only declaration of the function or function template in the
709 // translation unit.
710 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
711 functionDeclHasDefaultArgument(FD: Old)) {
712 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
713 Diag(Old->getLocation(), diag::note_previous_declaration);
714 Invalid = true;
715 }
716
717 // C++11 [temp.friend]p4 (DR329):
718 // When a function is defined in a friend function declaration in a class
719 // template, the function is instantiated when the function is odr-used.
720 // The same restrictions on multiple declarations and definitions that
721 // apply to non-template function declarations and definitions also apply
722 // to these implicit definitions.
723 const FunctionDecl *OldDefinition = nullptr;
724 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
725 Old->isDefined(Definition&: OldDefinition, CheckForPendingFriendDefinition: true))
726 CheckForFunctionRedefinition(FD: New, EffectiveDefinition: OldDefinition);
727
728 return Invalid;
729}
730
731void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
732 Diag(Loc, getLangOpts().CPlusPlus26
733 ? diag::warn_cxx23_placeholder_var_definition
734 : diag::ext_placeholder_var_definition);
735}
736
737NamedDecl *
738Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
739 MultiTemplateParamsArg TemplateParamLists) {
740 assert(D.isDecompositionDeclarator());
741 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
742
743 // The syntax only allows a decomposition declarator as a simple-declaration,
744 // a for-range-declaration, or a condition in Clang, but we parse it in more
745 // cases than that.
746 if (!D.mayHaveDecompositionDeclarator()) {
747 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
748 << Decomp.getSourceRange();
749 return nullptr;
750 }
751
752 if (!TemplateParamLists.empty()) {
753 // FIXME: There's no rule against this, but there are also no rules that
754 // would actually make it usable, so we reject it for now.
755 Diag(TemplateParamLists.front()->getTemplateLoc(),
756 diag::err_decomp_decl_template);
757 return nullptr;
758 }
759
760 Diag(Decomp.getLSquareLoc(),
761 !getLangOpts().CPlusPlus17
762 ? diag::ext_decomp_decl
763 : D.getContext() == DeclaratorContext::Condition
764 ? diag::ext_decomp_decl_cond
765 : diag::warn_cxx14_compat_decomp_decl)
766 << Decomp.getSourceRange();
767
768 // The semantic context is always just the current context.
769 DeclContext *const DC = CurContext;
770
771 // C++17 [dcl.dcl]/8:
772 // The decl-specifier-seq shall contain only the type-specifier auto
773 // and cv-qualifiers.
774 // C++20 [dcl.dcl]/8:
775 // If decl-specifier-seq contains any decl-specifier other than static,
776 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
777 // C++23 [dcl.pre]/6:
778 // Each decl-specifier in the decl-specifier-seq shall be static,
779 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
780 auto &DS = D.getDeclSpec();
781 {
782 // Note: While constrained-auto needs to be checked, we do so separately so
783 // we can emit a better diagnostic.
784 SmallVector<StringRef, 8> BadSpecifiers;
785 SmallVector<SourceLocation, 8> BadSpecifierLocs;
786 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
787 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
788 if (auto SCS = DS.getStorageClassSpec()) {
789 if (SCS == DeclSpec::SCS_static) {
790 CPlusPlus20Specifiers.push_back(Elt: DeclSpec::getSpecifierName(S: SCS));
791 CPlusPlus20SpecifierLocs.push_back(Elt: DS.getStorageClassSpecLoc());
792 } else {
793 BadSpecifiers.push_back(Elt: DeclSpec::getSpecifierName(S: SCS));
794 BadSpecifierLocs.push_back(Elt: DS.getStorageClassSpecLoc());
795 }
796 }
797 if (auto TSCS = DS.getThreadStorageClassSpec()) {
798 CPlusPlus20Specifiers.push_back(Elt: DeclSpec::getSpecifierName(S: TSCS));
799 CPlusPlus20SpecifierLocs.push_back(Elt: DS.getThreadStorageClassSpecLoc());
800 }
801 if (DS.hasConstexprSpecifier()) {
802 BadSpecifiers.push_back(
803 Elt: DeclSpec::getSpecifierName(C: DS.getConstexprSpecifier()));
804 BadSpecifierLocs.push_back(Elt: DS.getConstexprSpecLoc());
805 }
806 if (DS.isInlineSpecified()) {
807 BadSpecifiers.push_back(Elt: "inline");
808 BadSpecifierLocs.push_back(Elt: DS.getInlineSpecLoc());
809 }
810
811 if (!BadSpecifiers.empty()) {
812 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
813 Err << (int)BadSpecifiers.size()
814 << llvm::join(Begin: BadSpecifiers.begin(), End: BadSpecifiers.end(), Separator: " ");
815 // Don't add FixItHints to remove the specifiers; we do still respect
816 // them when building the underlying variable.
817 for (auto Loc : BadSpecifierLocs)
818 Err << SourceRange(Loc, Loc);
819 } else if (!CPlusPlus20Specifiers.empty()) {
820 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
821 getLangOpts().CPlusPlus20
822 ? diag::warn_cxx17_compat_decomp_decl_spec
823 : diag::ext_decomp_decl_spec);
824 Warn << (int)CPlusPlus20Specifiers.size()
825 << llvm::join(Begin: CPlusPlus20Specifiers.begin(),
826 End: CPlusPlus20Specifiers.end(), Separator: " ");
827 for (auto Loc : CPlusPlus20SpecifierLocs)
828 Warn << SourceRange(Loc, Loc);
829 }
830 // We can't recover from it being declared as a typedef.
831 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
832 return nullptr;
833 }
834
835 // C++2a [dcl.struct.bind]p1:
836 // A cv that includes volatile is deprecated
837 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
838 getLangOpts().CPlusPlus20)
839 Diag(DS.getVolatileSpecLoc(),
840 diag::warn_deprecated_volatile_structured_binding);
841
842 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
843 QualType R = TInfo->getType();
844
845 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
846 UPPC: UPPC_DeclarationType))
847 D.setInvalidType();
848
849 // The syntax only allows a single ref-qualifier prior to the decomposition
850 // declarator. No other declarator chunks are permitted. Also check the type
851 // specifier here.
852 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
853 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
854 (D.getNumTypeObjects() == 1 &&
855 D.getTypeObject(i: 0).Kind != DeclaratorChunk::Reference)) {
856 Diag(Decomp.getLSquareLoc(),
857 (D.hasGroupingParens() ||
858 (D.getNumTypeObjects() &&
859 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
860 ? diag::err_decomp_decl_parens
861 : diag::err_decomp_decl_type)
862 << R;
863
864 // In most cases, there's no actual problem with an explicitly-specified
865 // type, but a function type won't work here, and ActOnVariableDeclarator
866 // shouldn't be called for such a type.
867 if (R->isFunctionType())
868 D.setInvalidType();
869 }
870
871 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
872 if (DS.isConstrainedAuto()) {
873 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
874 assert(TemplRep->Kind == TNK_Concept_template &&
875 "No other template kind should be possible for a constrained auto");
876
877 SourceRange TemplRange{TemplRep->TemplateNameLoc,
878 TemplRep->RAngleLoc.isValid()
879 ? TemplRep->RAngleLoc
880 : TemplRep->TemplateNameLoc};
881 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
882 << TemplRange << FixItHint::CreateRemoval(TemplRange);
883 }
884
885 // Build the BindingDecls.
886 SmallVector<BindingDecl*, 8> Bindings;
887
888 // Build the BindingDecls.
889 for (auto &B : D.getDecompositionDeclarator().bindings()) {
890 // Check for name conflicts.
891 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
892 IdentifierInfo *VarName = B.Name;
893 assert(VarName && "Cannot have an unnamed binding declaration");
894
895 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
896 ForVisibleRedeclaration);
897 LookupName(R&: Previous, S,
898 /*CreateBuiltins*/AllowBuiltinCreation: DC->getRedeclContext()->isTranslationUnit());
899
900 // It's not permitted to shadow a template parameter name.
901 if (Previous.isSingleResult() &&
902 Previous.getFoundDecl()->isTemplateParameter()) {
903 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
904 Previous.getFoundDecl());
905 Previous.clear();
906 }
907
908 auto *BD = BindingDecl::Create(C&: Context, DC, IdLoc: B.NameLoc, Id: VarName);
909
910 // Find the shadowed declaration before filtering for scope.
911 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
912 ? getShadowedDeclaration(D: BD, R: Previous)
913 : nullptr;
914
915 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
916 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
917 FilterLookupForScope(R&: Previous, Ctx: DC, S, ConsiderLinkage,
918 /*AllowInlineNamespace*/false);
919
920 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
921 DC->isFunctionOrMethod() && VarName->isPlaceholder();
922 if (!Previous.empty()) {
923 if (IsPlaceholder) {
924 bool sameDC = (Previous.end() - 1)
925 ->getDeclContext()
926 ->getRedeclContext()
927 ->Equals(DC->getRedeclContext());
928 if (sameDC &&
929 isDeclInScope(D: *(Previous.end() - 1), Ctx: CurContext, S, AllowInlineNamespace: false)) {
930 Previous.clear();
931 DiagPlaceholderVariableDefinition(Loc: B.NameLoc);
932 }
933 } else {
934 auto *Old = Previous.getRepresentativeDecl();
935 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
936 Diag(Old->getLocation(), diag::note_previous_definition);
937 }
938 } else if (ShadowedDecl && !D.isRedeclaration()) {
939 CheckShadow(BD, ShadowedDecl, Previous);
940 }
941 PushOnScopeChains(BD, S, true);
942 Bindings.push_back(Elt: BD);
943 ParsingInitForAutoVars.insert(BD);
944 }
945
946 // There are no prior lookup results for the variable itself, because it
947 // is unnamed.
948 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
949 Decomp.getLSquareLoc());
950 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
951 ForVisibleRedeclaration);
952
953 // Build the variable that holds the non-decomposed object.
954 bool AddToScope = true;
955 NamedDecl *New =
956 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
957 TemplateParamLists: MultiTemplateParamsArg(), AddToScope, Bindings);
958 if (AddToScope) {
959 S->AddDecl(New);
960 CurContext->addHiddenDecl(New);
961 }
962
963 if (isInOpenMPDeclareTargetContext())
964 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
965
966 return New;
967}
968
969static bool checkSimpleDecomposition(
970 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
971 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
972 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
973 if ((int64_t)Bindings.size() != NumElems) {
974 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
975 << DecompType << (unsigned)Bindings.size()
976 << (unsigned)NumElems.getLimitedValue(UINT_MAX)
977 << toString(NumElems, 10) << (NumElems < Bindings.size());
978 return true;
979 }
980
981 unsigned I = 0;
982 for (auto *B : Bindings) {
983 SourceLocation Loc = B->getLocation();
984 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
985 if (E.isInvalid())
986 return true;
987 E = GetInit(Loc, E.get(), I++);
988 if (E.isInvalid())
989 return true;
990 B->setBinding(DeclaredType: ElemType, Binding: E.get());
991 }
992
993 return false;
994}
995
996static bool checkArrayLikeDecomposition(Sema &S,
997 ArrayRef<BindingDecl *> Bindings,
998 ValueDecl *Src, QualType DecompType,
999 const llvm::APSInt &NumElems,
1000 QualType ElemType) {
1001 return checkSimpleDecomposition(
1002 S, Bindings, Src, DecompType, NumElems, ElemType,
1003 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1004 ExprResult E = S.ActOnIntegerConstant(Loc, Val: I);
1005 if (E.isInvalid())
1006 return ExprError();
1007 return S.CreateBuiltinArraySubscriptExpr(Base, LLoc: Loc, Idx: E.get(), RLoc: Loc);
1008 });
1009}
1010
1011static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1012 ValueDecl *Src, QualType DecompType,
1013 const ConstantArrayType *CAT) {
1014 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1015 llvm::APSInt(CAT->getSize()),
1016 CAT->getElementType());
1017}
1018
1019static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1020 ValueDecl *Src, QualType DecompType,
1021 const VectorType *VT) {
1022 return checkArrayLikeDecomposition(
1023 S, Bindings, Src, DecompType, NumElems: llvm::APSInt::get(X: VT->getNumElements()),
1024 ElemType: S.Context.getQualifiedType(T: VT->getElementType(),
1025 Qs: DecompType.getQualifiers()));
1026}
1027
1028static bool checkComplexDecomposition(Sema &S,
1029 ArrayRef<BindingDecl *> Bindings,
1030 ValueDecl *Src, QualType DecompType,
1031 const ComplexType *CT) {
1032 return checkSimpleDecomposition(
1033 S, Bindings, Src, DecompType, NumElems: llvm::APSInt::get(X: 2),
1034 ElemType: S.Context.getQualifiedType(T: CT->getElementType(),
1035 Qs: DecompType.getQualifiers()),
1036 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1037 return S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: I ? UO_Imag : UO_Real, InputExpr: Base);
1038 });
1039}
1040
1041static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1042 TemplateArgumentListInfo &Args,
1043 const TemplateParameterList *Params) {
1044 SmallString<128> SS;
1045 llvm::raw_svector_ostream OS(SS);
1046 bool First = true;
1047 unsigned I = 0;
1048 for (auto &Arg : Args.arguments()) {
1049 if (!First)
1050 OS << ", ";
1051 Arg.getArgument().print(Policy: PrintingPolicy, Out&: OS,
1052 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
1053 Policy: PrintingPolicy, TPL: Params, Idx: I));
1054 First = false;
1055 I++;
1056 }
1057 return std::string(OS.str());
1058}
1059
1060static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1061 SourceLocation Loc, StringRef Trait,
1062 TemplateArgumentListInfo &Args,
1063 unsigned DiagID) {
1064 auto DiagnoseMissing = [&] {
1065 if (DiagID)
1066 S.Diag(Loc, DiagID) << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(),
1067 Args, /*Params*/ nullptr);
1068 return true;
1069 };
1070
1071 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1072 NamespaceDecl *Std = S.getStdNamespace();
1073 if (!Std)
1074 return DiagnoseMissing();
1075
1076 // Look up the trait itself, within namespace std. We can diagnose various
1077 // problems with this lookup even if we've been asked to not diagnose a
1078 // missing specialization, because this can only fail if the user has been
1079 // declaring their own names in namespace std or we don't support the
1080 // standard library implementation in use.
1081 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: Trait),
1082 Loc, Sema::LookupOrdinaryName);
1083 if (!S.LookupQualifiedName(Result, Std))
1084 return DiagnoseMissing();
1085 if (Result.isAmbiguous())
1086 return true;
1087
1088 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1089 if (!TraitTD) {
1090 Result.suppressDiagnostics();
1091 NamedDecl *Found = *Result.begin();
1092 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1093 S.Diag(Found->getLocation(), diag::note_declared_at);
1094 return true;
1095 }
1096
1097 // Build the template-id.
1098 QualType TraitTy = S.CheckTemplateIdType(Template: TemplateName(TraitTD), TemplateLoc: Loc, TemplateArgs&: Args);
1099 if (TraitTy.isNull())
1100 return true;
1101 if (!S.isCompleteType(Loc, T: TraitTy)) {
1102 if (DiagID)
1103 S.RequireCompleteType(
1104 Loc, TraitTy, DiagID,
1105 printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1106 TraitTD->getTemplateParameters()));
1107 return true;
1108 }
1109
1110 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1111 assert(RD && "specialization of class template is not a class?");
1112
1113 // Look up the member of the trait type.
1114 S.LookupQualifiedName(TraitMemberLookup, RD);
1115 return TraitMemberLookup.isAmbiguous();
1116}
1117
1118static TemplateArgumentLoc
1119getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1120 uint64_t I) {
1121 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(Value: I, Type: T), T);
1122 return S.getTrivialTemplateArgumentLoc(Arg, NTTPType: T, Loc);
1123}
1124
1125static TemplateArgumentLoc
1126getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1127 return S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(T), NTTPType: QualType(), Loc);
1128}
1129
1130namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1131
1132static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1133 llvm::APSInt &Size) {
1134 EnterExpressionEvaluationContext ContextRAII(
1135 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1136
1137 DeclarationName Value = S.PP.getIdentifierInfo(Name: "value");
1138 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1139
1140 // Form template argument list for tuple_size<T>.
1141 TemplateArgumentListInfo Args(Loc, Loc);
1142 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1143
1144 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1145 // it's not tuple-like.
1146 if (lookupStdTypeTraitMember(S, TraitMemberLookup&: R, Loc, Trait: "tuple_size", Args, /*DiagID*/ 0) ||
1147 R.empty())
1148 return IsTupleLike::NotTupleLike;
1149
1150 // If we get this far, we've committed to the tuple interpretation, but
1151 // we can still fail if there actually isn't a usable ::value.
1152
1153 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1154 LookupResult &R;
1155 TemplateArgumentListInfo &Args;
1156 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1157 : R(R), Args(Args) {}
1158 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1159 SourceLocation Loc) override {
1160 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1161 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1162 /*Params*/ nullptr);
1163 }
1164 } Diagnoser(R, Args);
1165
1166 ExprResult E =
1167 S.BuildDeclarationNameExpr(SS: CXXScopeSpec(), R, /*NeedsADL*/false);
1168 if (E.isInvalid())
1169 return IsTupleLike::Error;
1170
1171 E = S.VerifyIntegerConstantExpression(E: E.get(), Result: &Size, Diagnoser);
1172 if (E.isInvalid())
1173 return IsTupleLike::Error;
1174
1175 return IsTupleLike::TupleLike;
1176}
1177
1178/// \return std::tuple_element<I, T>::type.
1179static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1180 unsigned I, QualType T) {
1181 // Form template argument list for tuple_element<I, T>.
1182 TemplateArgumentListInfo Args(Loc, Loc);
1183 Args.addArgument(
1184 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1185 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1186
1187 DeclarationName TypeDN = S.PP.getIdentifierInfo(Name: "type");
1188 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1189 if (lookupStdTypeTraitMember(
1190 S, R, Loc, "tuple_element", Args,
1191 diag::err_decomp_decl_std_tuple_element_not_specialized))
1192 return QualType();
1193
1194 auto *TD = R.getAsSingle<TypeDecl>();
1195 if (!TD) {
1196 R.suppressDiagnostics();
1197 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1198 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1199 /*Params*/ nullptr);
1200 if (!R.empty())
1201 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1202 return QualType();
1203 }
1204
1205 return S.Context.getTypeDeclType(Decl: TD);
1206}
1207
1208namespace {
1209struct InitializingBinding {
1210 Sema &S;
1211 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1212 Sema::CodeSynthesisContext Ctx;
1213 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1214 Ctx.PointOfInstantiation = BD->getLocation();
1215 Ctx.Entity = BD;
1216 S.pushCodeSynthesisContext(Ctx);
1217 }
1218 ~InitializingBinding() {
1219 S.popCodeSynthesisContext();
1220 }
1221};
1222}
1223
1224static bool checkTupleLikeDecomposition(Sema &S,
1225 ArrayRef<BindingDecl *> Bindings,
1226 VarDecl *Src, QualType DecompType,
1227 const llvm::APSInt &TupleSize) {
1228 if ((int64_t)Bindings.size() != TupleSize) {
1229 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1230 << DecompType << (unsigned)Bindings.size()
1231 << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1232 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1233 return true;
1234 }
1235
1236 if (Bindings.empty())
1237 return false;
1238
1239 DeclarationName GetDN = S.PP.getIdentifierInfo(Name: "get");
1240
1241 // [dcl.decomp]p3:
1242 // The unqualified-id get is looked up in the scope of E by class member
1243 // access lookup ...
1244 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1245 bool UseMemberGet = false;
1246 if (S.isCompleteType(Loc: Src->getLocation(), T: DecompType)) {
1247 if (auto *RD = DecompType->getAsCXXRecordDecl())
1248 S.LookupQualifiedName(MemberGet, RD);
1249 if (MemberGet.isAmbiguous())
1250 return true;
1251 // ... and if that finds at least one declaration that is a function
1252 // template whose first template parameter is a non-type parameter ...
1253 for (NamedDecl *D : MemberGet) {
1254 if (FunctionTemplateDecl *FTD =
1255 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1256 TemplateParameterList *TPL = FTD->getTemplateParameters();
1257 if (TPL->size() != 0 &&
1258 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1259 // ... the initializer is e.get<i>().
1260 UseMemberGet = true;
1261 break;
1262 }
1263 }
1264 }
1265 }
1266
1267 unsigned I = 0;
1268 for (auto *B : Bindings) {
1269 InitializingBinding InitContext(S, B);
1270 SourceLocation Loc = B->getLocation();
1271
1272 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1273 if (E.isInvalid())
1274 return true;
1275
1276 // e is an lvalue if the type of the entity is an lvalue reference and
1277 // an xvalue otherwise
1278 if (!Src->getType()->isLValueReferenceType())
1279 E = ImplicitCastExpr::Create(Context: S.Context, T: E.get()->getType(), Kind: CK_NoOp,
1280 Operand: E.get(), BasePath: nullptr, Cat: VK_XValue,
1281 FPO: FPOptionsOverride());
1282
1283 TemplateArgumentListInfo Args(Loc, Loc);
1284 Args.addArgument(
1285 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1286
1287 if (UseMemberGet) {
1288 // if [lookup of member get] finds at least one declaration, the
1289 // initializer is e.get<i-1>().
1290 E = S.BuildMemberReferenceExpr(Base: E.get(), BaseType: DecompType, OpLoc: Loc, IsArrow: false,
1291 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr,
1292 R&: MemberGet, TemplateArgs: &Args, S: nullptr);
1293 if (E.isInvalid())
1294 return true;
1295
1296 E = S.BuildCallExpr(S: nullptr, Fn: E.get(), LParenLoc: Loc, ArgExprs: std::nullopt, RParenLoc: Loc);
1297 } else {
1298 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1299 // in the associated namespaces.
1300 Expr *Get = UnresolvedLookupExpr::Create(
1301 Context: S.Context, NamingClass: nullptr, QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(),
1302 NameInfo: DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/ true, Args: &Args,
1303 Begin: UnresolvedSetIterator(), End: UnresolvedSetIterator(),
1304 /*KnownDependent=*/false);
1305
1306 Expr *Arg = E.get();
1307 E = S.BuildCallExpr(S: nullptr, Fn: Get, LParenLoc: Loc, ArgExprs: Arg, RParenLoc: Loc);
1308 }
1309 if (E.isInvalid())
1310 return true;
1311 Expr *Init = E.get();
1312
1313 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1314 QualType T = getTupleLikeElementType(S, Loc, I, T: DecompType);
1315 if (T.isNull())
1316 return true;
1317
1318 // each vi is a variable of type "reference to T" initialized with the
1319 // initializer, where the reference is an lvalue reference if the
1320 // initializer is an lvalue and an rvalue reference otherwise
1321 QualType RefType =
1322 S.BuildReferenceType(T, LValueRef: E.get()->isLValue(), Loc, Entity: B->getDeclName());
1323 if (RefType.isNull())
1324 return true;
1325 auto *RefVD = VarDecl::Create(
1326 C&: S.Context, DC: Src->getDeclContext(), StartLoc: Loc, IdLoc: Loc,
1327 Id: B->getDeclName().getAsIdentifierInfo(), T: RefType,
1328 TInfo: S.Context.getTrivialTypeSourceInfo(T, Loc), S: Src->getStorageClass());
1329 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1330 RefVD->setTSCSpec(Src->getTSCSpec());
1331 RefVD->setImplicit();
1332 if (Src->isInlineSpecified())
1333 RefVD->setInlineSpecified();
1334 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1335
1336 InitializedEntity Entity = InitializedEntity::InitializeBinding(Binding: RefVD);
1337 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc);
1338 InitializationSequence Seq(S, Entity, Kind, Init);
1339 E = Seq.Perform(S, Entity, Kind, Args: Init);
1340 if (E.isInvalid())
1341 return true;
1342 E = S.ActOnFinishFullExpr(Expr: E.get(), CC: Loc, /*DiscardedValue*/ false);
1343 if (E.isInvalid())
1344 return true;
1345 RefVD->setInit(E.get());
1346 S.CheckCompleteVariableDeclaration(VD: RefVD);
1347
1348 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1349 DeclarationNameInfo(B->getDeclName(), Loc),
1350 RefVD);
1351 if (E.isInvalid())
1352 return true;
1353
1354 B->setBinding(DeclaredType: T, Binding: E.get());
1355 I++;
1356 }
1357
1358 return false;
1359}
1360
1361/// Find the base class to decompose in a built-in decomposition of a class type.
1362/// This base class search is, unfortunately, not quite like any other that we
1363/// perform anywhere else in C++.
1364static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1365 const CXXRecordDecl *RD,
1366 CXXCastPath &BasePath) {
1367 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1368 CXXBasePath &Path) {
1369 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1370 };
1371
1372 const CXXRecordDecl *ClassWithFields = nullptr;
1373 AccessSpecifier AS = AS_public;
1374 if (RD->hasDirectFields())
1375 // [dcl.decomp]p4:
1376 // Otherwise, all of E's non-static data members shall be public direct
1377 // members of E ...
1378 ClassWithFields = RD;
1379 else {
1380 // ... or of ...
1381 CXXBasePaths Paths;
1382 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1383 if (!RD->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1384 // If no classes have fields, just decompose RD itself. (This will work
1385 // if and only if zero bindings were provided.)
1386 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1387 }
1388
1389 CXXBasePath *BestPath = nullptr;
1390 for (auto &P : Paths) {
1391 if (!BestPath)
1392 BestPath = &P;
1393 else if (!S.Context.hasSameType(T1: P.back().Base->getType(),
1394 T2: BestPath->back().Base->getType())) {
1395 // ... the same ...
1396 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1397 << false << RD << BestPath->back().Base->getType()
1398 << P.back().Base->getType();
1399 return DeclAccessPair();
1400 } else if (P.Access < BestPath->Access) {
1401 BestPath = &P;
1402 }
1403 }
1404
1405 // ... unambiguous ...
1406 QualType BaseType = BestPath->back().Base->getType();
1407 if (Paths.isAmbiguous(BaseType: S.Context.getCanonicalType(T: BaseType))) {
1408 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1409 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1410 return DeclAccessPair();
1411 }
1412
1413 // ... [accessible, implied by other rules] base class of E.
1414 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1415 *BestPath, diag::err_decomp_decl_inaccessible_base);
1416 AS = BestPath->Access;
1417
1418 ClassWithFields = BaseType->getAsCXXRecordDecl();
1419 S.BuildBasePathArray(Paths, BasePath);
1420 }
1421
1422 // The above search did not check whether the selected class itself has base
1423 // classes with fields, so check that now.
1424 CXXBasePaths Paths;
1425 if (ClassWithFields->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1426 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1427 << (ClassWithFields == RD) << RD << ClassWithFields
1428 << Paths.front().back().Base->getType();
1429 return DeclAccessPair();
1430 }
1431
1432 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1433}
1434
1435static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1436 ValueDecl *Src, QualType DecompType,
1437 const CXXRecordDecl *OrigRD) {
1438 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1439 diag::err_incomplete_type))
1440 return true;
1441
1442 CXXCastPath BasePath;
1443 DeclAccessPair BasePair =
1444 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1445 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1446 if (!RD)
1447 return true;
1448 QualType BaseType = S.Context.getQualifiedType(T: S.Context.getRecordType(RD),
1449 Qs: DecompType.getQualifiers());
1450
1451 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1452 unsigned NumFields = llvm::count_if(
1453 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1454 assert(Bindings.size() != NumFields);
1455 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1456 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1457 << (NumFields < Bindings.size());
1458 return true;
1459 };
1460
1461 // all of E's non-static data members shall be [...] well-formed
1462 // when named as e.name in the context of the structured binding,
1463 // E shall not have an anonymous union member, ...
1464 unsigned I = 0;
1465 for (auto *FD : RD->fields()) {
1466 if (FD->isUnnamedBitfield())
1467 continue;
1468
1469 // All the non-static data members are required to be nameable, so they
1470 // must all have names.
1471 if (!FD->getDeclName()) {
1472 if (RD->isLambda()) {
1473 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1474 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1475 return true;
1476 }
1477
1478 if (FD->isAnonymousStructOrUnion()) {
1479 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1480 << DecompType << FD->getType()->isUnionType();
1481 S.Diag(FD->getLocation(), diag::note_declared_at);
1482 return true;
1483 }
1484
1485 // FIXME: Are there any other ways we could have an anonymous member?
1486 }
1487
1488 // We have a real field to bind.
1489 if (I >= Bindings.size())
1490 return DiagnoseBadNumberOfBindings();
1491 auto *B = Bindings[I++];
1492 SourceLocation Loc = B->getLocation();
1493
1494 // The field must be accessible in the context of the structured binding.
1495 // We already checked that the base class is accessible.
1496 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1497 // const_cast here.
1498 S.CheckStructuredBindingMemberAccess(
1499 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1500 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1501 BasePair.getAccess(), FD->getAccess())));
1502
1503 // Initialize the binding to Src.FD.
1504 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1505 if (E.isInvalid())
1506 return true;
1507 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1508 VK_LValue, &BasePath);
1509 if (E.isInvalid())
1510 return true;
1511 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1512 CXXScopeSpec(), FD,
1513 DeclAccessPair::make(FD, FD->getAccess()),
1514 DeclarationNameInfo(FD->getDeclName(), Loc));
1515 if (E.isInvalid())
1516 return true;
1517
1518 // If the type of the member is T, the referenced type is cv T, where cv is
1519 // the cv-qualification of the decomposition expression.
1520 //
1521 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1522 // 'const' to the type of the field.
1523 Qualifiers Q = DecompType.getQualifiers();
1524 if (FD->isMutable())
1525 Q.removeConst();
1526 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1527 }
1528
1529 if (I != Bindings.size())
1530 return DiagnoseBadNumberOfBindings();
1531
1532 return false;
1533}
1534
1535void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1536 QualType DecompType = DD->getType();
1537
1538 // If the type of the decomposition is dependent, then so is the type of
1539 // each binding.
1540 if (DecompType->isDependentType()) {
1541 for (auto *B : DD->bindings())
1542 B->setType(Context.DependentTy);
1543 return;
1544 }
1545
1546 DecompType = DecompType.getNonReferenceType();
1547 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1548
1549 // C++1z [dcl.decomp]/2:
1550 // If E is an array type [...]
1551 // As an extension, we also support decomposition of built-in complex and
1552 // vector types.
1553 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1554 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1555 DD->setInvalidDecl();
1556 return;
1557 }
1558 if (auto *VT = DecompType->getAs<VectorType>()) {
1559 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1560 DD->setInvalidDecl();
1561 return;
1562 }
1563 if (auto *CT = DecompType->getAs<ComplexType>()) {
1564 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1565 DD->setInvalidDecl();
1566 return;
1567 }
1568
1569 // C++1z [dcl.decomp]/3:
1570 // if the expression std::tuple_size<E>::value is a well-formed integral
1571 // constant expression, [...]
1572 llvm::APSInt TupleSize(32);
1573 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1574 case IsTupleLike::Error:
1575 DD->setInvalidDecl();
1576 return;
1577
1578 case IsTupleLike::TupleLike:
1579 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1580 DD->setInvalidDecl();
1581 return;
1582
1583 case IsTupleLike::NotTupleLike:
1584 break;
1585 }
1586
1587 // C++1z [dcl.dcl]/8:
1588 // [E shall be of array or non-union class type]
1589 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1590 if (!RD || RD->isUnion()) {
1591 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1592 << DD << !RD << DecompType;
1593 DD->setInvalidDecl();
1594 return;
1595 }
1596
1597 // C++1z [dcl.decomp]/4:
1598 // all of E's non-static data members shall be [...] direct members of
1599 // E or of the same unambiguous public base class of E, ...
1600 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1601 DD->setInvalidDecl();
1602}
1603
1604/// Merge the exception specifications of two variable declarations.
1605///
1606/// This is called when there's a redeclaration of a VarDecl. The function
1607/// checks if the redeclaration might have an exception specification and
1608/// validates compatibility and merges the specs if necessary.
1609void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1610 // Shortcut if exceptions are disabled.
1611 if (!getLangOpts().CXXExceptions)
1612 return;
1613
1614 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1615 "Should only be called if types are otherwise the same.");
1616
1617 QualType NewType = New->getType();
1618 QualType OldType = Old->getType();
1619
1620 // We're only interested in pointers and references to functions, as well
1621 // as pointers to member functions.
1622 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1623 NewType = R->getPointeeType();
1624 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1625 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1626 NewType = P->getPointeeType();
1627 OldType = OldType->castAs<PointerType>()->getPointeeType();
1628 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1629 NewType = M->getPointeeType();
1630 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1631 }
1632
1633 if (!NewType->isFunctionProtoType())
1634 return;
1635
1636 // There's lots of special cases for functions. For function pointers, system
1637 // libraries are hopefully not as broken so that we don't need these
1638 // workarounds.
1639 if (CheckEquivalentExceptionSpec(
1640 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1641 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1642 New->setInvalidDecl();
1643 }
1644}
1645
1646/// CheckCXXDefaultArguments - Verify that the default arguments for a
1647/// function declaration are well-formed according to C++
1648/// [dcl.fct.default].
1649void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1650 unsigned NumParams = FD->getNumParams();
1651 unsigned ParamIdx = 0;
1652
1653 // This checking doesn't make sense for explicit specializations; their
1654 // default arguments are determined by the declaration we're specializing,
1655 // not by FD.
1656 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1657 return;
1658 if (auto *FTD = FD->getDescribedFunctionTemplate())
1659 if (FTD->isMemberSpecialization())
1660 return;
1661
1662 // Find first parameter with a default argument
1663 for (; ParamIdx < NumParams; ++ParamIdx) {
1664 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1665 if (Param->hasDefaultArg())
1666 break;
1667 }
1668
1669 // C++20 [dcl.fct.default]p4:
1670 // In a given function declaration, each parameter subsequent to a parameter
1671 // with a default argument shall have a default argument supplied in this or
1672 // a previous declaration, unless the parameter was expanded from a
1673 // parameter pack, or shall be a function parameter pack.
1674 for (; ParamIdx < NumParams; ++ParamIdx) {
1675 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1676 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1677 !(CurrentInstantiationScope &&
1678 CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1679 if (Param->isInvalidDecl())
1680 /* We already complained about this parameter. */;
1681 else if (Param->getIdentifier())
1682 Diag(Param->getLocation(),
1683 diag::err_param_default_argument_missing_name)
1684 << Param->getIdentifier();
1685 else
1686 Diag(Param->getLocation(),
1687 diag::err_param_default_argument_missing);
1688 }
1689 }
1690}
1691
1692/// Check that the given type is a literal type. Issue a diagnostic if not,
1693/// if Kind is Diagnose.
1694/// \return \c true if a problem has been found (and optionally diagnosed).
1695template <typename... Ts>
1696static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1697 SourceLocation Loc, QualType T, unsigned DiagID,
1698 Ts &&...DiagArgs) {
1699 if (T->isDependentType())
1700 return false;
1701
1702 switch (Kind) {
1703 case Sema::CheckConstexprKind::Diagnose:
1704 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1705 std::forward<Ts>(DiagArgs)...);
1706
1707 case Sema::CheckConstexprKind::CheckValid:
1708 return !T->isLiteralType(Ctx: SemaRef.Context);
1709 }
1710
1711 llvm_unreachable("unknown CheckConstexprKind");
1712}
1713
1714/// Determine whether a destructor cannot be constexpr due to
1715static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1716 const CXXDestructorDecl *DD,
1717 Sema::CheckConstexprKind Kind) {
1718 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1719 const CXXRecordDecl *RD =
1720 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1721 if (!RD || RD->hasConstexprDestructor())
1722 return true;
1723
1724 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1725 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1726 << static_cast<int>(DD->getConstexprKind()) << !FD
1727 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1728 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1729 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1730 }
1731 return false;
1732 };
1733
1734 const CXXRecordDecl *RD = DD->getParent();
1735 for (const CXXBaseSpecifier &B : RD->bases())
1736 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1737 return false;
1738 for (const FieldDecl *FD : RD->fields())
1739 if (!Check(FD->getLocation(), FD->getType(), FD))
1740 return false;
1741 return true;
1742}
1743
1744/// Check whether a function's parameter types are all literal types. If so,
1745/// return true. If not, produce a suitable diagnostic and return false.
1746static bool CheckConstexprParameterTypes(Sema &SemaRef,
1747 const FunctionDecl *FD,
1748 Sema::CheckConstexprKind Kind) {
1749 unsigned ArgIndex = 0;
1750 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1751 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1752 e = FT->param_type_end();
1753 i != e; ++i, ++ArgIndex) {
1754 const ParmVarDecl *PD = FD->getParamDecl(i: ArgIndex);
1755 assert(PD && "null in a parameter list");
1756 SourceLocation ParamLoc = PD->getLocation();
1757 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1758 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1759 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1760 FD->isConsteval()))
1761 return false;
1762 }
1763 return true;
1764}
1765
1766/// Check whether a function's return type is a literal type. If so, return
1767/// true. If not, produce a suitable diagnostic and return false.
1768static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1769 Sema::CheckConstexprKind Kind) {
1770 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1771 diag::err_constexpr_non_literal_return,
1772 FD->isConsteval()))
1773 return false;
1774 return true;
1775}
1776
1777/// Get diagnostic %select index for tag kind for
1778/// record diagnostic message.
1779/// WARNING: Indexes apply to particular diagnostics only!
1780///
1781/// \returns diagnostic %select index.
1782static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1783 switch (Tag) {
1784 case TagTypeKind::Struct:
1785 return 0;
1786 case TagTypeKind::Interface:
1787 return 1;
1788 case TagTypeKind::Class:
1789 return 2;
1790 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1791 }
1792}
1793
1794static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1795 Stmt *Body,
1796 Sema::CheckConstexprKind Kind);
1797
1798// Check whether a function declaration satisfies the requirements of a
1799// constexpr function definition or a constexpr constructor definition. If so,
1800// return true. If not, produce appropriate diagnostics (unless asked not to by
1801// Kind) and return false.
1802//
1803// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1804bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1805 CheckConstexprKind Kind) {
1806 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
1807 if (MD && MD->isInstance()) {
1808 // C++11 [dcl.constexpr]p4:
1809 // The definition of a constexpr constructor shall satisfy the following
1810 // constraints:
1811 // - the class shall not have any virtual base classes;
1812 //
1813 // FIXME: This only applies to constructors and destructors, not arbitrary
1814 // member functions.
1815 const CXXRecordDecl *RD = MD->getParent();
1816 if (RD->getNumVBases()) {
1817 if (Kind == CheckConstexprKind::CheckValid)
1818 return false;
1819
1820 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1821 << isa<CXXConstructorDecl>(NewFD)
1822 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1823 for (const auto &I : RD->vbases())
1824 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1825 << I.getSourceRange();
1826 return false;
1827 }
1828 }
1829
1830 if (!isa<CXXConstructorDecl>(Val: NewFD)) {
1831 // C++11 [dcl.constexpr]p3:
1832 // The definition of a constexpr function shall satisfy the following
1833 // constraints:
1834 // - it shall not be virtual; (removed in C++20)
1835 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD);
1836 if (Method && Method->isVirtual()) {
1837 if (getLangOpts().CPlusPlus20) {
1838 if (Kind == CheckConstexprKind::Diagnose)
1839 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1840 } else {
1841 if (Kind == CheckConstexprKind::CheckValid)
1842 return false;
1843
1844 Method = Method->getCanonicalDecl();
1845 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1846
1847 // If it's not obvious why this function is virtual, find an overridden
1848 // function which uses the 'virtual' keyword.
1849 const CXXMethodDecl *WrittenVirtual = Method;
1850 while (!WrittenVirtual->isVirtualAsWritten())
1851 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1852 if (WrittenVirtual != Method)
1853 Diag(WrittenVirtual->getLocation(),
1854 diag::note_overridden_virtual_function);
1855 return false;
1856 }
1857 }
1858
1859 // - its return type shall be a literal type;
1860 if (!CheckConstexprReturnType(SemaRef&: *this, FD: NewFD, Kind))
1861 return false;
1862 }
1863
1864 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
1865 // A destructor can be constexpr only if the defaulted destructor could be;
1866 // we don't need to check the members and bases if we already know they all
1867 // have constexpr destructors.
1868 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1869 if (Kind == CheckConstexprKind::CheckValid)
1870 return false;
1871 if (!CheckConstexprDestructorSubobjects(SemaRef&: *this, DD: Dtor, Kind))
1872 return false;
1873 }
1874 }
1875
1876 // - each of its parameter types shall be a literal type;
1877 if (!CheckConstexprParameterTypes(SemaRef&: *this, FD: NewFD, Kind))
1878 return false;
1879
1880 Stmt *Body = NewFD->getBody();
1881 assert(Body &&
1882 "CheckConstexprFunctionDefinition called on function with no body");
1883 return CheckConstexprFunctionBody(SemaRef&: *this, Dcl: NewFD, Body, Kind);
1884}
1885
1886/// Check the given declaration statement is legal within a constexpr function
1887/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1888///
1889/// \return true if the body is OK (maybe only as an extension), false if we
1890/// have diagnosed a problem.
1891static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1892 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1893 Sema::CheckConstexprKind Kind) {
1894 // C++11 [dcl.constexpr]p3 and p4:
1895 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1896 // contain only
1897 for (const auto *DclIt : DS->decls()) {
1898 switch (DclIt->getKind()) {
1899 case Decl::StaticAssert:
1900 case Decl::Using:
1901 case Decl::UsingShadow:
1902 case Decl::UsingDirective:
1903 case Decl::UnresolvedUsingTypename:
1904 case Decl::UnresolvedUsingValue:
1905 case Decl::UsingEnum:
1906 // - static_assert-declarations
1907 // - using-declarations,
1908 // - using-directives,
1909 // - using-enum-declaration
1910 continue;
1911
1912 case Decl::Typedef:
1913 case Decl::TypeAlias: {
1914 // - typedef declarations and alias-declarations that do not define
1915 // classes or enumerations,
1916 const auto *TN = cast<TypedefNameDecl>(Val: DclIt);
1917 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1918 // Don't allow variably-modified types in constexpr functions.
1919 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1920 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1921 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1922 << TL.getSourceRange() << TL.getType()
1923 << isa<CXXConstructorDecl>(Dcl);
1924 }
1925 return false;
1926 }
1927 continue;
1928 }
1929
1930 case Decl::Enum:
1931 case Decl::CXXRecord:
1932 // C++1y allows types to be defined, not just declared.
1933 if (cast<TagDecl>(Val: DclIt)->isThisDeclarationADefinition()) {
1934 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1935 SemaRef.Diag(DS->getBeginLoc(),
1936 SemaRef.getLangOpts().CPlusPlus14
1937 ? diag::warn_cxx11_compat_constexpr_type_definition
1938 : diag::ext_constexpr_type_definition)
1939 << isa<CXXConstructorDecl>(Dcl);
1940 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1941 return false;
1942 }
1943 }
1944 continue;
1945
1946 case Decl::EnumConstant:
1947 case Decl::IndirectField:
1948 case Decl::ParmVar:
1949 // These can only appear with other declarations which are banned in
1950 // C++11 and permitted in C++1y, so ignore them.
1951 continue;
1952
1953 case Decl::Var:
1954 case Decl::Decomposition: {
1955 // C++1y [dcl.constexpr]p3 allows anything except:
1956 // a definition of a variable of non-literal type or of static or
1957 // thread storage duration or [before C++2a] for which no
1958 // initialization is performed.
1959 const auto *VD = cast<VarDecl>(Val: DclIt);
1960 if (VD->isThisDeclarationADefinition()) {
1961 if (VD->isStaticLocal()) {
1962 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1963 SemaRef.Diag(VD->getLocation(),
1964 SemaRef.getLangOpts().CPlusPlus23
1965 ? diag::warn_cxx20_compat_constexpr_var
1966 : diag::ext_constexpr_static_var)
1967 << isa<CXXConstructorDecl>(Dcl)
1968 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1969 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1970 return false;
1971 }
1972 }
1973 if (SemaRef.LangOpts.CPlusPlus23) {
1974 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1975 diag::warn_cxx20_compat_constexpr_var,
1976 isa<CXXConstructorDecl>(Dcl),
1977 /*variable of non-literal type*/ 2);
1978 } else if (CheckLiteralType(
1979 SemaRef, Kind, VD->getLocation(), VD->getType(),
1980 diag::err_constexpr_local_var_non_literal_type,
1981 isa<CXXConstructorDecl>(Dcl))) {
1982 return false;
1983 }
1984 if (!VD->getType()->isDependentType() &&
1985 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1986 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1987 SemaRef.Diag(
1988 VD->getLocation(),
1989 SemaRef.getLangOpts().CPlusPlus20
1990 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1991 : diag::ext_constexpr_local_var_no_init)
1992 << isa<CXXConstructorDecl>(Dcl);
1993 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1994 return false;
1995 }
1996 continue;
1997 }
1998 }
1999 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2000 SemaRef.Diag(VD->getLocation(),
2001 SemaRef.getLangOpts().CPlusPlus14
2002 ? diag::warn_cxx11_compat_constexpr_local_var
2003 : diag::ext_constexpr_local_var)
2004 << isa<CXXConstructorDecl>(Dcl);
2005 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2006 return false;
2007 }
2008 continue;
2009 }
2010
2011 case Decl::NamespaceAlias:
2012 case Decl::Function:
2013 // These are disallowed in C++11 and permitted in C++1y. Allow them
2014 // everywhere as an extension.
2015 if (!Cxx1yLoc.isValid())
2016 Cxx1yLoc = DS->getBeginLoc();
2017 continue;
2018
2019 default:
2020 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2021 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2022 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2023 }
2024 return false;
2025 }
2026 }
2027
2028 return true;
2029}
2030
2031/// Check that the given field is initialized within a constexpr constructor.
2032///
2033/// \param Dcl The constexpr constructor being checked.
2034/// \param Field The field being checked. This may be a member of an anonymous
2035/// struct or union nested within the class being checked.
2036/// \param Inits All declarations, including anonymous struct/union members and
2037/// indirect members, for which any initialization was provided.
2038/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2039/// multiple notes for different members to the same error.
2040/// \param Kind Whether we're diagnosing a constructor as written or determining
2041/// whether the formal requirements are satisfied.
2042/// \return \c false if we're checking for validity and the constructor does
2043/// not satisfy the requirements on a constexpr constructor.
2044static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2045 const FunctionDecl *Dcl,
2046 FieldDecl *Field,
2047 llvm::SmallSet<Decl*, 16> &Inits,
2048 bool &Diagnosed,
2049 Sema::CheckConstexprKind Kind) {
2050 // In C++20 onwards, there's nothing to check for validity.
2051 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2052 SemaRef.getLangOpts().CPlusPlus20)
2053 return true;
2054
2055 if (Field->isInvalidDecl())
2056 return true;
2057
2058 if (Field->isUnnamedBitfield())
2059 return true;
2060
2061 // Anonymous unions with no variant members and empty anonymous structs do not
2062 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2063 // indirect fields don't need initializing.
2064 if (Field->isAnonymousStructOrUnion() &&
2065 (Field->getType()->isUnionType()
2066 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2067 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2068 return true;
2069
2070 if (!Inits.count(Field)) {
2071 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2072 if (!Diagnosed) {
2073 SemaRef.Diag(Dcl->getLocation(),
2074 SemaRef.getLangOpts().CPlusPlus20
2075 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2076 : diag::ext_constexpr_ctor_missing_init);
2077 Diagnosed = true;
2078 }
2079 SemaRef.Diag(Field->getLocation(),
2080 diag::note_constexpr_ctor_missing_init);
2081 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2082 return false;
2083 }
2084 } else if (Field->isAnonymousStructOrUnion()) {
2085 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2086 for (auto *I : RD->fields())
2087 // If an anonymous union contains an anonymous struct of which any member
2088 // is initialized, all members must be initialized.
2089 if (!RD->isUnion() || Inits.count(I))
2090 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2091 Kind))
2092 return false;
2093 }
2094 return true;
2095}
2096
2097/// Check the provided statement is allowed in a constexpr function
2098/// definition.
2099static bool
2100CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2101 SmallVectorImpl<SourceLocation> &ReturnStmts,
2102 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2103 SourceLocation &Cxx2bLoc,
2104 Sema::CheckConstexprKind Kind) {
2105 // - its function-body shall be [...] a compound-statement that contains only
2106 switch (S->getStmtClass()) {
2107 case Stmt::NullStmtClass:
2108 // - null statements,
2109 return true;
2110
2111 case Stmt::DeclStmtClass:
2112 // - static_assert-declarations
2113 // - using-declarations,
2114 // - using-directives,
2115 // - typedef declarations and alias-declarations that do not define
2116 // classes or enumerations,
2117 if (!CheckConstexprDeclStmt(SemaRef, Dcl, DS: cast<DeclStmt>(Val: S), Cxx1yLoc, Kind))
2118 return false;
2119 return true;
2120
2121 case Stmt::ReturnStmtClass:
2122 // - and exactly one return statement;
2123 if (isa<CXXConstructorDecl>(Val: Dcl)) {
2124 // C++1y allows return statements in constexpr constructors.
2125 if (!Cxx1yLoc.isValid())
2126 Cxx1yLoc = S->getBeginLoc();
2127 return true;
2128 }
2129
2130 ReturnStmts.push_back(Elt: S->getBeginLoc());
2131 return true;
2132
2133 case Stmt::AttributedStmtClass:
2134 // Attributes on a statement don't affect its formal kind and hence don't
2135 // affect its validity in a constexpr function.
2136 return CheckConstexprFunctionStmt(
2137 SemaRef, Dcl, S: cast<AttributedStmt>(Val: S)->getSubStmt(), ReturnStmts,
2138 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2139
2140 case Stmt::CompoundStmtClass: {
2141 // C++1y allows compound-statements.
2142 if (!Cxx1yLoc.isValid())
2143 Cxx1yLoc = S->getBeginLoc();
2144
2145 CompoundStmt *CompStmt = cast<CompoundStmt>(Val: S);
2146 for (auto *BodyIt : CompStmt->body()) {
2147 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts,
2148 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2149 return false;
2150 }
2151 return true;
2152 }
2153
2154 case Stmt::IfStmtClass: {
2155 // C++1y allows if-statements.
2156 if (!Cxx1yLoc.isValid())
2157 Cxx1yLoc = S->getBeginLoc();
2158
2159 IfStmt *If = cast<IfStmt>(Val: S);
2160 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getThen(), ReturnStmts,
2161 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2162 return false;
2163 if (If->getElse() &&
2164 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getElse(), ReturnStmts,
2165 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2166 return false;
2167 return true;
2168 }
2169
2170 case Stmt::WhileStmtClass:
2171 case Stmt::DoStmtClass:
2172 case Stmt::ForStmtClass:
2173 case Stmt::CXXForRangeStmtClass:
2174 case Stmt::ContinueStmtClass:
2175 // C++1y allows all of these. We don't allow them as extensions in C++11,
2176 // because they don't make sense without variable mutation.
2177 if (!SemaRef.getLangOpts().CPlusPlus14)
2178 break;
2179 if (!Cxx1yLoc.isValid())
2180 Cxx1yLoc = S->getBeginLoc();
2181 for (Stmt *SubStmt : S->children()) {
2182 if (SubStmt &&
2183 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2184 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2185 return false;
2186 }
2187 return true;
2188
2189 case Stmt::SwitchStmtClass:
2190 case Stmt::CaseStmtClass:
2191 case Stmt::DefaultStmtClass:
2192 case Stmt::BreakStmtClass:
2193 // C++1y allows switch-statements, and since they don't need variable
2194 // mutation, we can reasonably allow them in C++11 as an extension.
2195 if (!Cxx1yLoc.isValid())
2196 Cxx1yLoc = S->getBeginLoc();
2197 for (Stmt *SubStmt : S->children()) {
2198 if (SubStmt &&
2199 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2200 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2201 return false;
2202 }
2203 return true;
2204
2205 case Stmt::LabelStmtClass:
2206 case Stmt::GotoStmtClass:
2207 if (Cxx2bLoc.isInvalid())
2208 Cxx2bLoc = S->getBeginLoc();
2209 for (Stmt *SubStmt : S->children()) {
2210 if (SubStmt &&
2211 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2212 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2213 return false;
2214 }
2215 return true;
2216
2217 case Stmt::GCCAsmStmtClass:
2218 case Stmt::MSAsmStmtClass:
2219 // C++2a allows inline assembly statements.
2220 case Stmt::CXXTryStmtClass:
2221 if (Cxx2aLoc.isInvalid())
2222 Cxx2aLoc = S->getBeginLoc();
2223 for (Stmt *SubStmt : S->children()) {
2224 if (SubStmt &&
2225 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2226 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2227 return false;
2228 }
2229 return true;
2230
2231 case Stmt::CXXCatchStmtClass:
2232 // Do not bother checking the language mode (already covered by the
2233 // try block check).
2234 if (!CheckConstexprFunctionStmt(
2235 SemaRef, Dcl, S: cast<CXXCatchStmt>(Val: S)->getHandlerBlock(), ReturnStmts,
2236 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2237 return false;
2238 return true;
2239
2240 default:
2241 if (!isa<Expr>(Val: S))
2242 break;
2243
2244 // C++1y allows expression-statements.
2245 if (!Cxx1yLoc.isValid())
2246 Cxx1yLoc = S->getBeginLoc();
2247 return true;
2248 }
2249
2250 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2251 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2252 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2253 }
2254 return false;
2255}
2256
2257/// Check the body for the given constexpr function declaration only contains
2258/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2259///
2260/// \return true if the body is OK, false if we have found or diagnosed a
2261/// problem.
2262static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2263 Stmt *Body,
2264 Sema::CheckConstexprKind Kind) {
2265 SmallVector<SourceLocation, 4> ReturnStmts;
2266
2267 if (isa<CXXTryStmt>(Val: Body)) {
2268 // C++11 [dcl.constexpr]p3:
2269 // The definition of a constexpr function shall satisfy the following
2270 // constraints: [...]
2271 // - its function-body shall be = delete, = default, or a
2272 // compound-statement
2273 //
2274 // C++11 [dcl.constexpr]p4:
2275 // In the definition of a constexpr constructor, [...]
2276 // - its function-body shall not be a function-try-block;
2277 //
2278 // This restriction is lifted in C++2a, as long as inner statements also
2279 // apply the general constexpr rules.
2280 switch (Kind) {
2281 case Sema::CheckConstexprKind::CheckValid:
2282 if (!SemaRef.getLangOpts().CPlusPlus20)
2283 return false;
2284 break;
2285
2286 case Sema::CheckConstexprKind::Diagnose:
2287 SemaRef.Diag(Body->getBeginLoc(),
2288 !SemaRef.getLangOpts().CPlusPlus20
2289 ? diag::ext_constexpr_function_try_block_cxx20
2290 : diag::warn_cxx17_compat_constexpr_function_try_block)
2291 << isa<CXXConstructorDecl>(Dcl);
2292 break;
2293 }
2294 }
2295
2296 // - its function-body shall be [...] a compound-statement that contains only
2297 // [... list of cases ...]
2298 //
2299 // Note that walking the children here is enough to properly check for
2300 // CompoundStmt and CXXTryStmt body.
2301 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2302 for (Stmt *SubStmt : Body->children()) {
2303 if (SubStmt &&
2304 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2305 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2306 return false;
2307 }
2308
2309 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2310 // If this is only valid as an extension, report that we don't satisfy the
2311 // constraints of the current language.
2312 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2313 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2314 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2315 return false;
2316 } else if (Cxx2bLoc.isValid()) {
2317 SemaRef.Diag(Cxx2bLoc,
2318 SemaRef.getLangOpts().CPlusPlus23
2319 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2320 : diag::ext_constexpr_body_invalid_stmt_cxx23)
2321 << isa<CXXConstructorDecl>(Dcl);
2322 } else if (Cxx2aLoc.isValid()) {
2323 SemaRef.Diag(Cxx2aLoc,
2324 SemaRef.getLangOpts().CPlusPlus20
2325 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2326 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2327 << isa<CXXConstructorDecl>(Dcl);
2328 } else if (Cxx1yLoc.isValid()) {
2329 SemaRef.Diag(Cxx1yLoc,
2330 SemaRef.getLangOpts().CPlusPlus14
2331 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2332 : diag::ext_constexpr_body_invalid_stmt)
2333 << isa<CXXConstructorDecl>(Dcl);
2334 }
2335
2336 if (const CXXConstructorDecl *Constructor
2337 = dyn_cast<CXXConstructorDecl>(Val: Dcl)) {
2338 const CXXRecordDecl *RD = Constructor->getParent();
2339 // DR1359:
2340 // - every non-variant non-static data member and base class sub-object
2341 // shall be initialized;
2342 // DR1460:
2343 // - if the class is a union having variant members, exactly one of them
2344 // shall be initialized;
2345 if (RD->isUnion()) {
2346 if (Constructor->getNumCtorInitializers() == 0 &&
2347 RD->hasVariantMembers()) {
2348 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2349 SemaRef.Diag(
2350 Dcl->getLocation(),
2351 SemaRef.getLangOpts().CPlusPlus20
2352 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2353 : diag::ext_constexpr_union_ctor_no_init);
2354 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2355 return false;
2356 }
2357 }
2358 } else if (!Constructor->isDependentContext() &&
2359 !Constructor->isDelegatingConstructor()) {
2360 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2361
2362 // Skip detailed checking if we have enough initializers, and we would
2363 // allow at most one initializer per member.
2364 bool AnyAnonStructUnionMembers = false;
2365 unsigned Fields = 0;
2366 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2367 E = RD->field_end(); I != E; ++I, ++Fields) {
2368 if (I->isAnonymousStructOrUnion()) {
2369 AnyAnonStructUnionMembers = true;
2370 break;
2371 }
2372 }
2373 // DR1460:
2374 // - if the class is a union-like class, but is not a union, for each of
2375 // its anonymous union members having variant members, exactly one of
2376 // them shall be initialized;
2377 if (AnyAnonStructUnionMembers ||
2378 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2379 // Check initialization of non-static data members. Base classes are
2380 // always initialized so do not need to be checked. Dependent bases
2381 // might not have initializers in the member initializer list.
2382 llvm::SmallSet<Decl*, 16> Inits;
2383 for (const auto *I: Constructor->inits()) {
2384 if (FieldDecl *FD = I->getMember())
2385 Inits.insert(FD);
2386 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2387 Inits.insert(I: ID->chain_begin(), E: ID->chain_end());
2388 }
2389
2390 bool Diagnosed = false;
2391 for (auto *I : RD->fields())
2392 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2393 Kind))
2394 return false;
2395 }
2396 }
2397 } else {
2398 if (ReturnStmts.empty()) {
2399 // C++1y doesn't require constexpr functions to contain a 'return'
2400 // statement. We still do, unless the return type might be void, because
2401 // otherwise if there's no return statement, the function cannot
2402 // be used in a core constant expression.
2403 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2404 (Dcl->getReturnType()->isVoidType() ||
2405 Dcl->getReturnType()->isDependentType());
2406 switch (Kind) {
2407 case Sema::CheckConstexprKind::Diagnose:
2408 SemaRef.Diag(Dcl->getLocation(),
2409 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2410 : diag::err_constexpr_body_no_return)
2411 << Dcl->isConsteval();
2412 if (!OK)
2413 return false;
2414 break;
2415
2416 case Sema::CheckConstexprKind::CheckValid:
2417 // The formal requirements don't include this rule in C++14, even
2418 // though the "must be able to produce a constant expression" rules
2419 // still imply it in some cases.
2420 if (!SemaRef.getLangOpts().CPlusPlus14)
2421 return false;
2422 break;
2423 }
2424 } else if (ReturnStmts.size() > 1) {
2425 switch (Kind) {
2426 case Sema::CheckConstexprKind::Diagnose:
2427 SemaRef.Diag(
2428 ReturnStmts.back(),
2429 SemaRef.getLangOpts().CPlusPlus14
2430 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2431 : diag::ext_constexpr_body_multiple_return);
2432 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2433 SemaRef.Diag(ReturnStmts[I],
2434 diag::note_constexpr_body_previous_return);
2435 break;
2436
2437 case Sema::CheckConstexprKind::CheckValid:
2438 if (!SemaRef.getLangOpts().CPlusPlus14)
2439 return false;
2440 break;
2441 }
2442 }
2443 }
2444
2445 // C++11 [dcl.constexpr]p5:
2446 // if no function argument values exist such that the function invocation
2447 // substitution would produce a constant expression, the program is
2448 // ill-formed; no diagnostic required.
2449 // C++11 [dcl.constexpr]p3:
2450 // - every constructor call and implicit conversion used in initializing the
2451 // return value shall be one of those allowed in a constant expression.
2452 // C++11 [dcl.constexpr]p4:
2453 // - every constructor involved in initializing non-static data members and
2454 // base class sub-objects shall be a constexpr constructor.
2455 //
2456 // Note that this rule is distinct from the "requirements for a constexpr
2457 // function", so is not checked in CheckValid mode.
2458 SmallVector<PartialDiagnosticAt, 8> Diags;
2459 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2460 !Expr::isPotentialConstantExpr(FD: Dcl, Diags)) {
2461 SemaRef.Diag(Dcl->getLocation(),
2462 diag::ext_constexpr_function_never_constant_expr)
2463 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2464 << Dcl->getNameInfo().getSourceRange();
2465 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2466 SemaRef.Diag(Loc: Diags[I].first, PD: Diags[I].second);
2467 // Don't return false here: we allow this for compatibility in
2468 // system headers.
2469 }
2470
2471 return true;
2472}
2473
2474bool Sema::CheckImmediateEscalatingFunctionDefinition(
2475 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2476 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2477 return true;
2478 FD->setBodyContainsImmediateEscalatingExpressions(
2479 FSI->FoundImmediateEscalatingExpression);
2480 if (FSI->FoundImmediateEscalatingExpression) {
2481 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2482 if (it != UndefinedButUsed.end()) {
2483 Diag(it->second, diag::err_immediate_function_used_before_definition)
2484 << it->first;
2485 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2486 if (FD->isImmediateFunction() && !FD->isConsteval())
2487 DiagnoseImmediateEscalatingReason(FD);
2488 return false;
2489 }
2490 }
2491 return true;
2492}
2493
2494void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2495 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2496 "expected an immediate function");
2497 assert(FD->hasBody() && "expected the function to have a body");
2498 struct ImmediateEscalatingExpressionsVisitor
2499 : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2500
2501 using Base = RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor>;
2502 Sema &SemaRef;
2503
2504 const FunctionDecl *ImmediateFn;
2505 bool ImmediateFnIsConstructor;
2506 CXXConstructorDecl *CurrentConstructor = nullptr;
2507 CXXCtorInitializer *CurrentInit = nullptr;
2508
2509 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2510 : SemaRef(SemaRef), ImmediateFn(FD),
2511 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(Val: FD)) {}
2512
2513 bool shouldVisitImplicitCode() const { return true; }
2514 bool shouldVisitLambdaBody() const { return false; }
2515
2516 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2517 SourceLocation Loc = E->getBeginLoc();
2518 SourceRange Range = E->getSourceRange();
2519 if (CurrentConstructor && CurrentInit) {
2520 Loc = CurrentConstructor->getLocation();
2521 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2522 : SourceRange();
2523 }
2524
2525 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2526
2527 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2528 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2529 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2530 << (InitializedField != nullptr)
2531 << (CurrentInit && !CurrentInit->isWritten())
2532 << InitializedField << Range;
2533 }
2534 bool TraverseCallExpr(CallExpr *E) {
2535 if (const auto *DR =
2536 dyn_cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit());
2537 DR && DR->isImmediateEscalating()) {
2538 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2539 return false;
2540 }
2541
2542 for (Expr *A : E->arguments())
2543 if (!getDerived().TraverseStmt(A))
2544 return false;
2545
2546 return true;
2547 }
2548
2549 bool VisitDeclRefExpr(DeclRefExpr *E) {
2550 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(Val: E->getDecl());
2551 ReferencedFn && E->isImmediateEscalating()) {
2552 Diag(E, ReferencedFn, /*IsCall=*/false);
2553 return false;
2554 }
2555
2556 return true;
2557 }
2558
2559 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2560 CXXConstructorDecl *D = E->getConstructor();
2561 if (E->isImmediateEscalating()) {
2562 Diag(E, D, /*IsCall=*/true);
2563 return false;
2564 }
2565 return true;
2566 }
2567
2568 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2569 llvm::SaveAndRestore RAII(CurrentInit, Init);
2570 return Base::TraverseConstructorInitializer(Init);
2571 }
2572
2573 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2574 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2575 return Base::TraverseCXXConstructorDecl(Ctr);
2576 }
2577
2578 bool TraverseType(QualType T) { return true; }
2579 bool VisitBlockExpr(BlockExpr *T) { return true; }
2580
2581 } Visitor(*this, FD);
2582 Visitor.TraverseDecl(FD);
2583}
2584
2585/// Get the class that is directly named by the current context. This is the
2586/// class for which an unqualified-id in this scope could name a constructor
2587/// or destructor.
2588///
2589/// If the scope specifier denotes a class, this will be that class.
2590/// If the scope specifier is empty, this will be the class whose
2591/// member-specification we are currently within. Otherwise, there
2592/// is no such class.
2593CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2594 assert(getLangOpts().CPlusPlus && "No class names in C!");
2595
2596 if (SS && SS->isInvalid())
2597 return nullptr;
2598
2599 if (SS && SS->isNotEmpty()) {
2600 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2601 return dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2602 }
2603
2604 return dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2605}
2606
2607/// isCurrentClassName - Determine whether the identifier II is the
2608/// name of the class type currently being defined. In the case of
2609/// nested classes, this will only return true if II is the name of
2610/// the innermost class.
2611bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2612 const CXXScopeSpec *SS) {
2613 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2614 return CurDecl && &II == CurDecl->getIdentifier();
2615}
2616
2617/// Determine whether the identifier II is a typo for the name of
2618/// the class type currently being defined. If so, update it to the identifier
2619/// that should have been used.
2620bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2621 assert(getLangOpts().CPlusPlus && "No class names in C!");
2622
2623 if (!getLangOpts().SpellChecking)
2624 return false;
2625
2626 CXXRecordDecl *CurDecl;
2627 if (SS && SS->isSet() && !SS->isInvalid()) {
2628 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2629 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2630 } else
2631 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2632
2633 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2634 3 * II->getName().edit_distance(Other: CurDecl->getIdentifier()->getName())
2635 < II->getLength()) {
2636 II = CurDecl->getIdentifier();
2637 return true;
2638 }
2639
2640 return false;
2641}
2642
2643/// Determine whether the given class is a base class of the given
2644/// class, including looking at dependent bases.
2645static bool findCircularInheritance(const CXXRecordDecl *Class,
2646 const CXXRecordDecl *Current) {
2647 SmallVector<const CXXRecordDecl*, 8> Queue;
2648
2649 Class = Class->getCanonicalDecl();
2650 while (true) {
2651 for (const auto &I : Current->bases()) {
2652 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2653 if (!Base)
2654 continue;
2655
2656 Base = Base->getDefinition();
2657 if (!Base)
2658 continue;
2659
2660 if (Base->getCanonicalDecl() == Class)
2661 return true;
2662
2663 Queue.push_back(Elt: Base);
2664 }
2665
2666 if (Queue.empty())
2667 return false;
2668
2669 Current = Queue.pop_back_val();
2670 }
2671
2672 return false;
2673}
2674
2675/// Check the validity of a C++ base class specifier.
2676///
2677/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2678/// and returns NULL otherwise.
2679CXXBaseSpecifier *
2680Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2681 SourceRange SpecifierRange,
2682 bool Virtual, AccessSpecifier Access,
2683 TypeSourceInfo *TInfo,
2684 SourceLocation EllipsisLoc) {
2685 // In HLSL, unspecified class access is public rather than private.
2686 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2687 Access == AS_none)
2688 Access = AS_public;
2689
2690 QualType BaseType = TInfo->getType();
2691 if (BaseType->containsErrors()) {
2692 // Already emitted a diagnostic when parsing the error type.
2693 return nullptr;
2694 }
2695 // C++ [class.union]p1:
2696 // A union shall not have base classes.
2697 if (Class->isUnion()) {
2698 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2699 << SpecifierRange;
2700 return nullptr;
2701 }
2702
2703 if (EllipsisLoc.isValid() &&
2704 !TInfo->getType()->containsUnexpandedParameterPack()) {
2705 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2706 << TInfo->getTypeLoc().getSourceRange();
2707 EllipsisLoc = SourceLocation();
2708 }
2709
2710 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2711
2712 if (BaseType->isDependentType()) {
2713 // Make sure that we don't have circular inheritance among our dependent
2714 // bases. For non-dependent bases, the check for completeness below handles
2715 // this.
2716 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2717 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2718 ((BaseDecl = BaseDecl->getDefinition()) &&
2719 findCircularInheritance(Class, Current: BaseDecl))) {
2720 Diag(BaseLoc, diag::err_circular_inheritance)
2721 << BaseType << Context.getTypeDeclType(Class);
2722
2723 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2724 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2725 << BaseType;
2726
2727 return nullptr;
2728 }
2729 }
2730
2731 // Make sure that we don't make an ill-formed AST where the type of the
2732 // Class is non-dependent and its attached base class specifier is an
2733 // dependent type, which violates invariants in many clang code paths (e.g.
2734 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2735 // explicitly mark the Class decl invalid. The diagnostic was already
2736 // emitted.
2737 if (!Class->getTypeForDecl()->isDependentType())
2738 Class->setInvalidDecl();
2739 return new (Context) CXXBaseSpecifier(
2740 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2741 Access, TInfo, EllipsisLoc);
2742 }
2743
2744 // Base specifiers must be record types.
2745 if (!BaseType->isRecordType()) {
2746 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2747 return nullptr;
2748 }
2749
2750 // C++ [class.union]p1:
2751 // A union shall not be used as a base class.
2752 if (BaseType->isUnionType()) {
2753 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2754 return nullptr;
2755 }
2756
2757 // For the MS ABI, propagate DLL attributes to base class templates.
2758 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2759 Context.getTargetInfo().getTriple().isPS()) {
2760 if (Attr *ClassAttr = getDLLAttr(Class)) {
2761 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2762 Val: BaseType->getAsCXXRecordDecl())) {
2763 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplateSpec: BaseTemplate,
2764 BaseLoc);
2765 }
2766 }
2767 }
2768
2769 // C++ [class.derived]p2:
2770 // The class-name in a base-specifier shall not be an incompletely
2771 // defined class.
2772 if (RequireCompleteType(BaseLoc, BaseType,
2773 diag::err_incomplete_base_class, SpecifierRange)) {
2774 Class->setInvalidDecl();
2775 return nullptr;
2776 }
2777
2778 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2779 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2780 assert(BaseDecl && "Record type has no declaration");
2781 BaseDecl = BaseDecl->getDefinition();
2782 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2783 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(Val: BaseDecl);
2784 assert(CXXBaseDecl && "Base type is not a C++ type");
2785
2786 // Microsoft docs say:
2787 // "If a base-class has a code_seg attribute, derived classes must have the
2788 // same attribute."
2789 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2790 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2791 if ((DerivedCSA || BaseCSA) &&
2792 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2793 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2794 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2795 << CXXBaseDecl;
2796 return nullptr;
2797 }
2798
2799 // A class which contains a flexible array member is not suitable for use as a
2800 // base class:
2801 // - If the layout determines that a base comes before another base,
2802 // the flexible array member would index into the subsequent base.
2803 // - If the layout determines that base comes before the derived class,
2804 // the flexible array member would index into the derived class.
2805 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2806 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2807 << CXXBaseDecl->getDeclName();
2808 return nullptr;
2809 }
2810
2811 // C++ [class]p3:
2812 // If a class is marked final and it appears as a base-type-specifier in
2813 // base-clause, the program is ill-formed.
2814 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2815 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2816 << CXXBaseDecl->getDeclName()
2817 << FA->isSpelledAsSealed();
2818 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2819 << CXXBaseDecl->getDeclName() << FA->getRange();
2820 return nullptr;
2821 }
2822
2823 if (BaseDecl->isInvalidDecl())
2824 Class->setInvalidDecl();
2825
2826 // Create the base specifier.
2827 return new (Context) CXXBaseSpecifier(
2828 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2829 Access, TInfo, EllipsisLoc);
2830}
2831
2832/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2833/// one entry in the base class list of a class specifier, for
2834/// example:
2835/// class foo : public bar, virtual private baz {
2836/// 'public bar' and 'virtual private baz' are each base-specifiers.
2837BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2838 const ParsedAttributesView &Attributes,
2839 bool Virtual, AccessSpecifier Access,
2840 ParsedType basetype, SourceLocation BaseLoc,
2841 SourceLocation EllipsisLoc) {
2842 if (!classdecl)
2843 return true;
2844
2845 AdjustDeclIfTemplate(Decl&: classdecl);
2846 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: classdecl);
2847 if (!Class)
2848 return true;
2849
2850 // We haven't yet attached the base specifiers.
2851 Class->setIsParsingBaseSpecifiers();
2852
2853 // We do not support any C++11 attributes on base-specifiers yet.
2854 // Diagnose any attributes we see.
2855 for (const ParsedAttr &AL : Attributes) {
2856 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2857 continue;
2858 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2859 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2860 << AL << AL.getRange();
2861 else
2862 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2863 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2864 }
2865
2866 TypeSourceInfo *TInfo = nullptr;
2867 GetTypeFromParser(Ty: basetype, TInfo: &TInfo);
2868
2869 if (EllipsisLoc.isInvalid() &&
2870 DiagnoseUnexpandedParameterPack(Loc: SpecifierRange.getBegin(), T: TInfo,
2871 UPPC: UPPC_BaseType))
2872 return true;
2873
2874 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2875 Virtual, Access, TInfo,
2876 EllipsisLoc))
2877 return BaseSpec;
2878 else
2879 Class->setInvalidDecl();
2880
2881 return true;
2882}
2883
2884/// Use small set to collect indirect bases. As this is only used
2885/// locally, there's no need to abstract the small size parameter.
2886typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2887
2888/// Recursively add the bases of Type. Don't add Type itself.
2889static void
2890NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2891 const QualType &Type)
2892{
2893 // Even though the incoming type is a base, it might not be
2894 // a class -- it could be a template parm, for instance.
2895 if (auto Rec = Type->getAs<RecordType>()) {
2896 auto Decl = Rec->getAsCXXRecordDecl();
2897
2898 // Iterate over its bases.
2899 for (const auto &BaseSpec : Decl->bases()) {
2900 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2901 .getUnqualifiedType();
2902 if (Set.insert(Base).second)
2903 // If we've not already seen it, recurse.
2904 NoteIndirectBases(Context, Set, Base);
2905 }
2906 }
2907}
2908
2909/// Performs the actual work of attaching the given base class
2910/// specifiers to a C++ class.
2911bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2912 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2913 if (Bases.empty())
2914 return false;
2915
2916 // Used to keep track of which base types we have already seen, so
2917 // that we can properly diagnose redundant direct base types. Note
2918 // that the key is always the unqualified canonical type of the base
2919 // class.
2920 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2921
2922 // Used to track indirect bases so we can see if a direct base is
2923 // ambiguous.
2924 IndirectBaseSet IndirectBaseTypes;
2925
2926 // Copy non-redundant base specifiers into permanent storage.
2927 unsigned NumGoodBases = 0;
2928 bool Invalid = false;
2929 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2930 QualType NewBaseType
2931 = Context.getCanonicalType(T: Bases[idx]->getType());
2932 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2933
2934 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2935 if (KnownBase) {
2936 // C++ [class.mi]p3:
2937 // A class shall not be specified as a direct base class of a
2938 // derived class more than once.
2939 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2940 << KnownBase->getType() << Bases[idx]->getSourceRange();
2941
2942 // Delete the duplicate base class specifier; we're going to
2943 // overwrite its pointer later.
2944 Context.Deallocate(Ptr: Bases[idx]);
2945
2946 Invalid = true;
2947 } else {
2948 // Okay, add this new base class.
2949 KnownBase = Bases[idx];
2950 Bases[NumGoodBases++] = Bases[idx];
2951
2952 if (NewBaseType->isDependentType())
2953 continue;
2954 // Note this base's direct & indirect bases, if there could be ambiguity.
2955 if (Bases.size() > 1)
2956 NoteIndirectBases(Context, Set&: IndirectBaseTypes, Type: NewBaseType);
2957
2958 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2959 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: Record->getDecl());
2960 if (Class->isInterface() &&
2961 (!RD->isInterfaceLike() ||
2962 KnownBase->getAccessSpecifier() != AS_public)) {
2963 // The Microsoft extension __interface does not permit bases that
2964 // are not themselves public interfaces.
2965 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2966 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2967 << RD->getSourceRange();
2968 Invalid = true;
2969 }
2970 if (RD->hasAttr<WeakAttr>())
2971 Class->addAttr(WeakAttr::CreateImplicit(Context));
2972 }
2973 }
2974 }
2975
2976 // Attach the remaining base class specifiers to the derived class.
2977 Class->setBases(Bases: Bases.data(), NumBases: NumGoodBases);
2978
2979 // Check that the only base classes that are duplicate are virtual.
2980 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2981 // Check whether this direct base is inaccessible due to ambiguity.
2982 QualType BaseType = Bases[idx]->getType();
2983
2984 // Skip all dependent types in templates being used as base specifiers.
2985 // Checks below assume that the base specifier is a CXXRecord.
2986 if (BaseType->isDependentType())
2987 continue;
2988
2989 CanQualType CanonicalBase = Context.getCanonicalType(T: BaseType)
2990 .getUnqualifiedType();
2991
2992 if (IndirectBaseTypes.count(Ptr: CanonicalBase)) {
2993 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2994 /*DetectVirtual=*/true);
2995 bool found
2996 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2997 assert(found);
2998 (void)found;
2999
3000 if (Paths.isAmbiguous(BaseType: CanonicalBase))
3001 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3002 << BaseType << getAmbiguousPathsDisplayString(Paths)
3003 << Bases[idx]->getSourceRange();
3004 else
3005 assert(Bases[idx]->isVirtual());
3006 }
3007
3008 // Delete the base class specifier, since its data has been copied
3009 // into the CXXRecordDecl.
3010 Context.Deallocate(Ptr: Bases[idx]);
3011 }
3012
3013 return Invalid;
3014}
3015
3016/// ActOnBaseSpecifiers - Attach the given base specifiers to the
3017/// class, after checking whether there are any duplicate base
3018/// classes.
3019void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3020 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3021 if (!ClassDecl || Bases.empty())
3022 return;
3023
3024 AdjustDeclIfTemplate(Decl&: ClassDecl);
3025 AttachBaseSpecifiers(Class: cast<CXXRecordDecl>(Val: ClassDecl), Bases);
3026}
3027
3028/// Determine whether the type \p Derived is a C++ class that is
3029/// derived from the type \p Base.
3030bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3031 if (!getLangOpts().CPlusPlus)
3032 return false;
3033
3034 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3035 if (!DerivedRD)
3036 return false;
3037
3038 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3039 if (!BaseRD)
3040 return false;
3041
3042 // If either the base or the derived type is invalid, don't try to
3043 // check whether one is derived from the other.
3044 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
3045 return false;
3046
3047 // FIXME: In a modules build, do we need the entire path to be visible for us
3048 // to be able to use the inheritance relationship?
3049 if (!isCompleteType(Loc, T: Derived) && !DerivedRD->isBeingDefined())
3050 return false;
3051
3052 return DerivedRD->isDerivedFrom(Base: BaseRD);
3053}
3054
3055/// Determine whether the type \p Derived is a C++ class that is
3056/// derived from the type \p Base.
3057bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3058 CXXBasePaths &Paths) {
3059 if (!getLangOpts().CPlusPlus)
3060 return false;
3061
3062 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3063 if (!DerivedRD)
3064 return false;
3065
3066 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3067 if (!BaseRD)
3068 return false;
3069
3070 if (!isCompleteType(Loc, T: Derived) && !DerivedRD->isBeingDefined())
3071 return false;
3072
3073 return DerivedRD->isDerivedFrom(Base: BaseRD, Paths);
3074}
3075
3076static void BuildBasePathArray(const CXXBasePath &Path,
3077 CXXCastPath &BasePathArray) {
3078 // We first go backward and check if we have a virtual base.
3079 // FIXME: It would be better if CXXBasePath had the base specifier for
3080 // the nearest virtual base.
3081 unsigned Start = 0;
3082 for (unsigned I = Path.size(); I != 0; --I) {
3083 if (Path[I - 1].Base->isVirtual()) {
3084 Start = I - 1;
3085 break;
3086 }
3087 }
3088
3089 // Now add all bases.
3090 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3091 BasePathArray.push_back(Elt: const_cast<CXXBaseSpecifier*>(Path[I].Base));
3092}
3093
3094
3095void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3096 CXXCastPath &BasePathArray) {
3097 assert(BasePathArray.empty() && "Base path array must be empty!");
3098 assert(Paths.isRecordingPaths() && "Must record paths!");
3099 return ::BuildBasePathArray(Path: Paths.front(), BasePathArray);
3100}
3101/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
3102/// conversion (where Derived and Base are class types) is
3103/// well-formed, meaning that the conversion is unambiguous (and
3104/// that all of the base classes are accessible). Returns true
3105/// and emits a diagnostic if the code is ill-formed, returns false
3106/// otherwise. Loc is the location where this routine should point to
3107/// if there is an error, and Range is the source range to highlight
3108/// if there is an error.
3109///
3110/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
3111/// diagnostic for the respective type of error will be suppressed, but the
3112/// check for ill-formed code will still be performed.
3113bool
3114Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3115 unsigned InaccessibleBaseID,
3116 unsigned AmbiguousBaseConvID,
3117 SourceLocation Loc, SourceRange Range,
3118 DeclarationName Name,
3119 CXXCastPath *BasePath,
3120 bool IgnoreAccess) {
3121 // First, determine whether the path from Derived to Base is
3122 // ambiguous. This is slightly more expensive than checking whether
3123 // the Derived to Base conversion exists, because here we need to
3124 // explore multiple paths to determine if there is an ambiguity.
3125 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3126 /*DetectVirtual=*/false);
3127 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3128 if (!DerivationOkay)
3129 return true;
3130
3131 const CXXBasePath *Path = nullptr;
3132 if (!Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: Base).getUnqualifiedType()))
3133 Path = &Paths.front();
3134
3135 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3136 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3137 // user to access such bases.
3138 if (!Path && getLangOpts().MSVCCompat) {
3139 for (const CXXBasePath &PossiblePath : Paths) {
3140 if (PossiblePath.size() == 1) {
3141 Path = &PossiblePath;
3142 if (AmbiguousBaseConvID)
3143 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3144 << Base << Derived << Range;
3145 break;
3146 }
3147 }
3148 }
3149
3150 if (Path) {
3151 if (!IgnoreAccess) {
3152 // Check that the base class can be accessed.
3153 switch (
3154 CheckBaseClassAccess(AccessLoc: Loc, Base, Derived, Path: *Path, DiagID: InaccessibleBaseID)) {
3155 case AR_inaccessible:
3156 return true;
3157 case AR_accessible:
3158 case AR_dependent:
3159 case AR_delayed:
3160 break;
3161 }
3162 }
3163
3164 // Build a base path if necessary.
3165 if (BasePath)
3166 ::BuildBasePathArray(Path: *Path, BasePathArray&: *BasePath);
3167 return false;
3168 }
3169
3170 if (AmbiguousBaseConvID) {
3171 // We know that the derived-to-base conversion is ambiguous, and
3172 // we're going to produce a diagnostic. Perform the derived-to-base
3173 // search just one more time to compute all of the possible paths so
3174 // that we can print them out. This is more expensive than any of
3175 // the previous derived-to-base checks we've done, but at this point
3176 // performance isn't as much of an issue.
3177 Paths.clear();
3178 Paths.setRecordingPaths(true);
3179 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3180 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3181 (void)StillOkay;
3182
3183 // Build up a textual representation of the ambiguous paths, e.g.,
3184 // D -> B -> A, that will be used to illustrate the ambiguous
3185 // conversions in the diagnostic. We only print one of the paths
3186 // to each base class subobject.
3187 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3188
3189 Diag(Loc, DiagID: AmbiguousBaseConvID)
3190 << Derived << Base << PathDisplayStr << Range << Name;
3191 }
3192 return true;
3193}
3194
3195bool
3196Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3197 SourceLocation Loc, SourceRange Range,
3198 CXXCastPath *BasePath,
3199 bool IgnoreAccess) {
3200 return CheckDerivedToBaseConversion(
3201 Derived, Base, diag::err_upcast_to_inaccessible_base,
3202 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3203 BasePath, IgnoreAccess);
3204}
3205
3206
3207/// Builds a string representing ambiguous paths from a
3208/// specific derived class to different subobjects of the same base
3209/// class.
3210///
3211/// This function builds a string that can be used in error messages
3212/// to show the different paths that one can take through the
3213/// inheritance hierarchy to go from the derived class to different
3214/// subobjects of a base class. The result looks something like this:
3215/// @code
3216/// struct D -> struct B -> struct A
3217/// struct D -> struct C -> struct A
3218/// @endcode
3219std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3220 std::string PathDisplayStr;
3221 std::set<unsigned> DisplayedPaths;
3222 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3223 Path != Paths.end(); ++Path) {
3224 if (DisplayedPaths.insert(x: Path->back().SubobjectNumber).second) {
3225 // We haven't displayed a path to this particular base
3226 // class subobject yet.
3227 PathDisplayStr += "\n ";
3228 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3229 for (CXXBasePath::const_iterator Element = Path->begin();
3230 Element != Path->end(); ++Element)
3231 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3232 }
3233 }
3234
3235 return PathDisplayStr;
3236}
3237
3238//===----------------------------------------------------------------------===//
3239// C++ class member Handling
3240//===----------------------------------------------------------------------===//
3241
3242/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3243bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3244 SourceLocation ColonLoc,
3245 const ParsedAttributesView &Attrs) {
3246 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3247 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(C&: Context, AS: Access, DC: CurContext,
3248 ASLoc, ColonLoc);
3249 CurContext->addHiddenDecl(ASDecl);
3250 return ProcessAccessDeclAttributeList(ASDecl, AttrList: Attrs);
3251}
3252
3253/// CheckOverrideControl - Check C++11 override control semantics.
3254void Sema::CheckOverrideControl(NamedDecl *D) {
3255 if (D->isInvalidDecl())
3256 return;
3257
3258 // We only care about "override" and "final" declarations.
3259 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3260 return;
3261
3262 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3263
3264 // We can't check dependent instance methods.
3265 if (MD && MD->isInstance() &&
3266 (MD->getParent()->hasAnyDependentBases() ||
3267 MD->getType()->isDependentType()))
3268 return;
3269
3270 if (MD && !MD->isVirtual()) {
3271 // If we have a non-virtual method, check if it hides a virtual method.
3272 // (In that case, it's most likely the method has the wrong type.)
3273 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3274 FindHiddenVirtualMethods(MD, OverloadedMethods);
3275
3276 if (!OverloadedMethods.empty()) {
3277 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3278 Diag(OA->getLocation(),
3279 diag::override_keyword_hides_virtual_member_function)
3280 << "override" << (OverloadedMethods.size() > 1);
3281 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3282 Diag(FA->getLocation(),
3283 diag::override_keyword_hides_virtual_member_function)
3284 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3285 << (OverloadedMethods.size() > 1);
3286 }
3287 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3288 MD->setInvalidDecl();
3289 return;
3290 }
3291 // Fall through into the general case diagnostic.
3292 // FIXME: We might want to attempt typo correction here.
3293 }
3294
3295 if (!MD || !MD->isVirtual()) {
3296 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3297 Diag(OA->getLocation(),
3298 diag::override_keyword_only_allowed_on_virtual_member_functions)
3299 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3300 D->dropAttr<OverrideAttr>();
3301 }
3302 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3303 Diag(FA->getLocation(),
3304 diag::override_keyword_only_allowed_on_virtual_member_functions)
3305 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3306 << FixItHint::CreateRemoval(FA->getLocation());
3307 D->dropAttr<FinalAttr>();
3308 }
3309 return;
3310 }
3311
3312 // C++11 [class.virtual]p5:
3313 // If a function is marked with the virt-specifier override and
3314 // does not override a member function of a base class, the program is
3315 // ill-formed.
3316 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3317 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3318 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3319 << MD->getDeclName();
3320}
3321
3322void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3323 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3324 return;
3325 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3326 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3327 return;
3328
3329 SourceLocation Loc = MD->getLocation();
3330 SourceLocation SpellingLoc = Loc;
3331 if (getSourceManager().isMacroArgExpansion(Loc))
3332 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3333 SpellingLoc = getSourceManager().getSpellingLoc(Loc: SpellingLoc);
3334 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(Loc: SpellingLoc))
3335 return;
3336
3337 if (MD->size_overridden_methods() > 0) {
3338 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3339 unsigned DiagID =
3340 Inconsistent && !Diags.isIgnored(DiagID: DiagInconsistent, Loc: MD->getLocation())
3341 ? DiagInconsistent
3342 : DiagSuggest;
3343 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3344 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3345 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3346 };
3347 if (isa<CXXDestructorDecl>(MD))
3348 EmitDiag(
3349 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3350 diag::warn_suggest_destructor_marked_not_override_overriding);
3351 else
3352 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3353 diag::warn_suggest_function_marked_not_override_overriding);
3354 }
3355}
3356
3357/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3358/// function overrides a virtual member function marked 'final', according to
3359/// C++11 [class.virtual]p4.
3360bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3361 const CXXMethodDecl *Old) {
3362 FinalAttr *FA = Old->getAttr<FinalAttr>();
3363 if (!FA)
3364 return false;
3365
3366 Diag(New->getLocation(), diag::err_final_function_overridden)
3367 << New->getDeclName()
3368 << FA->isSpelledAsSealed();
3369 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3370 return true;
3371}
3372
3373static bool InitializationHasSideEffects(const FieldDecl &FD) {
3374 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3375 // FIXME: Destruction of ObjC lifetime types has side-effects.
3376 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3377 return !RD->isCompleteDefinition() ||
3378 !RD->hasTrivialDefaultConstructor() ||
3379 !RD->hasTrivialDestructor();
3380 return false;
3381}
3382
3383// Check if there is a field shadowing.
3384void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3385 DeclarationName FieldName,
3386 const CXXRecordDecl *RD,
3387 bool DeclIsField) {
3388 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3389 return;
3390
3391 // To record a shadowed field in a base
3392 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3393 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3394 CXXBasePath &Path) {
3395 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3396 // Record an ambiguous path directly
3397 if (Bases.find(x: Base) != Bases.end())
3398 return true;
3399 for (const auto Field : Base->lookup(FieldName)) {
3400 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3401 Field->getAccess() != AS_private) {
3402 assert(Field->getAccess() != AS_none);
3403 assert(Bases.find(Base) == Bases.end());
3404 Bases[Base] = Field;
3405 return true;
3406 }
3407 }
3408 return false;
3409 };
3410
3411 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3412 /*DetectVirtual=*/true);
3413 if (!RD->lookupInBases(BaseMatches: FieldShadowed, Paths))
3414 return;
3415
3416 for (const auto &P : Paths) {
3417 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3418 auto It = Bases.find(x: Base);
3419 // Skip duplicated bases
3420 if (It == Bases.end())
3421 continue;
3422 auto BaseField = It->second;
3423 assert(BaseField->getAccess() != AS_private);
3424 if (AS_none !=
3425 CXXRecordDecl::MergeAccess(PathAccess: P.Access, DeclAccess: BaseField->getAccess())) {
3426 Diag(Loc, diag::warn_shadow_field)
3427 << FieldName << RD << Base << DeclIsField;
3428 Diag(BaseField->getLocation(), diag::note_shadow_field);
3429 Bases.erase(position: It);
3430 }
3431 }
3432}
3433
3434/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3435/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3436/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3437/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3438/// present (but parsing it has been deferred).
3439NamedDecl *
3440Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3441 MultiTemplateParamsArg TemplateParameterLists,
3442 Expr *BW, const VirtSpecifiers &VS,
3443 InClassInitStyle InitStyle) {
3444 const DeclSpec &DS = D.getDeclSpec();
3445 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3446 DeclarationName Name = NameInfo.getName();
3447 SourceLocation Loc = NameInfo.getLoc();
3448
3449 // For anonymous bitfields, the location should point to the type.
3450 if (Loc.isInvalid())
3451 Loc = D.getBeginLoc();
3452
3453 Expr *BitWidth = static_cast<Expr*>(BW);
3454
3455 assert(isa<CXXRecordDecl>(CurContext));
3456 assert(!DS.isFriendSpecified());
3457
3458 bool isFunc = D.isDeclarationOfFunction();
3459 const ParsedAttr *MSPropertyAttr =
3460 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3461
3462 if (cast<CXXRecordDecl>(Val: CurContext)->isInterface()) {
3463 // The Microsoft extension __interface only permits public member functions
3464 // and prohibits constructors, destructors, operators, non-public member
3465 // functions, static methods and data members.
3466 unsigned InvalidDecl;
3467 bool ShowDeclName = true;
3468 if (!isFunc &&
3469 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3470 InvalidDecl = 0;
3471 else if (!isFunc)
3472 InvalidDecl = 1;
3473 else if (AS != AS_public)
3474 InvalidDecl = 2;
3475 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3476 InvalidDecl = 3;
3477 else switch (Name.getNameKind()) {
3478 case DeclarationName::CXXConstructorName:
3479 InvalidDecl = 4;
3480 ShowDeclName = false;
3481 break;
3482
3483 case DeclarationName::CXXDestructorName:
3484 InvalidDecl = 5;
3485 ShowDeclName = false;
3486 break;
3487
3488 case DeclarationName::CXXOperatorName:
3489 case DeclarationName::CXXConversionFunctionName:
3490 InvalidDecl = 6;
3491 break;
3492
3493 default:
3494 InvalidDecl = 0;
3495 break;
3496 }
3497
3498 if (InvalidDecl) {
3499 if (ShowDeclName)
3500 Diag(Loc, diag::err_invalid_member_in_interface)
3501 << (InvalidDecl-1) << Name;
3502 else
3503 Diag(Loc, diag::err_invalid_member_in_interface)
3504 << (InvalidDecl-1) << "";
3505 return nullptr;
3506 }
3507 }
3508
3509 // C++ 9.2p6: A member shall not be declared to have automatic storage
3510 // duration (auto, register) or with the extern storage-class-specifier.
3511 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3512 // data members and cannot be applied to names declared const or static,
3513 // and cannot be applied to reference members.
3514 switch (DS.getStorageClassSpec()) {
3515 case DeclSpec::SCS_unspecified:
3516 case DeclSpec::SCS_typedef:
3517 case DeclSpec::SCS_static:
3518 break;
3519 case DeclSpec::SCS_mutable:
3520 if (isFunc) {
3521 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3522
3523 // FIXME: It would be nicer if the keyword was ignored only for this
3524 // declarator. Otherwise we could get follow-up errors.
3525 D.getMutableDeclSpec().ClearStorageClassSpecs();
3526 }
3527 break;
3528 default:
3529 Diag(DS.getStorageClassSpecLoc(),
3530 diag::err_storageclass_invalid_for_member);
3531 D.getMutableDeclSpec().ClearStorageClassSpecs();
3532 break;
3533 }
3534
3535 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3536 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3537 !isFunc);
3538
3539 if (DS.hasConstexprSpecifier() && isInstField) {
3540 SemaDiagnosticBuilder B =
3541 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3542 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3543 if (InitStyle == ICIS_NoInit) {
3544 B << 0 << 0;
3545 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3546 B << FixItHint::CreateRemoval(RemoveRange: ConstexprLoc);
3547 else {
3548 B << FixItHint::CreateReplacement(RemoveRange: ConstexprLoc, Code: "const");
3549 D.getMutableDeclSpec().ClearConstexprSpec();
3550 const char *PrevSpec;
3551 unsigned DiagID;
3552 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3553 T: DeclSpec::TQ_const, Loc: ConstexprLoc, PrevSpec, DiagID, Lang: getLangOpts());
3554 (void)Failed;
3555 assert(!Failed && "Making a constexpr member const shouldn't fail");
3556 }
3557 } else {
3558 B << 1;
3559 const char *PrevSpec;
3560 unsigned DiagID;
3561 if (D.getMutableDeclSpec().SetStorageClassSpec(
3562 S&: *this, SC: DeclSpec::SCS_static, Loc: ConstexprLoc, PrevSpec, DiagID,
3563 Policy: Context.getPrintingPolicy())) {
3564 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3565 "This is the only DeclSpec that should fail to be applied");
3566 B << 1;
3567 } else {
3568 B << 0 << FixItHint::CreateInsertion(InsertionLoc: ConstexprLoc, Code: "static ");
3569 isInstField = false;
3570 }
3571 }
3572 }
3573
3574 NamedDecl *Member;
3575 if (isInstField) {
3576 CXXScopeSpec &SS = D.getCXXScopeSpec();
3577
3578 // Data members must have identifiers for names.
3579 if (!Name.isIdentifier()) {
3580 Diag(Loc, diag::err_bad_variable_name)
3581 << Name;
3582 return nullptr;
3583 }
3584
3585 IdentifierInfo *II = Name.getAsIdentifierInfo();
3586
3587 // Member field could not be with "template" keyword.
3588 // So TemplateParameterLists should be empty in this case.
3589 if (TemplateParameterLists.size()) {
3590 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3591 if (TemplateParams->size()) {
3592 // There is no such thing as a member field template.
3593 Diag(D.getIdentifierLoc(), diag::err_template_member)
3594 << II
3595 << SourceRange(TemplateParams->getTemplateLoc(),
3596 TemplateParams->getRAngleLoc());
3597 } else {
3598 // There is an extraneous 'template<>' for this member.
3599 Diag(TemplateParams->getTemplateLoc(),
3600 diag::err_template_member_noparams)
3601 << II
3602 << SourceRange(TemplateParams->getTemplateLoc(),
3603 TemplateParams->getRAngleLoc());
3604 }
3605 return nullptr;
3606 }
3607
3608 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3609 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3610 << II
3611 << SourceRange(D.getName().TemplateId->LAngleLoc,
3612 D.getName().TemplateId->RAngleLoc)
3613 << D.getName().TemplateId->LAngleLoc;
3614 D.SetIdentifier(Id: II, IdLoc: Loc);
3615 }
3616
3617 if (SS.isSet() && !SS.isInvalid()) {
3618 // The user provided a superfluous scope specifier inside a class
3619 // definition:
3620 //
3621 // class X {
3622 // int X::member;
3623 // };
3624 if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) {
3625 TemplateIdAnnotation *TemplateId =
3626 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3627 ? D.getName().TemplateId
3628 : nullptr;
3629 diagnoseQualifiedDeclaration(SS, DC, Name, Loc: D.getIdentifierLoc(),
3630 TemplateId,
3631 /*IsMemberSpecialization=*/false);
3632 } else {
3633 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3634 << Name << SS.getRange();
3635 }
3636 SS.clear();
3637 }
3638
3639 if (MSPropertyAttr) {
3640 Member = HandleMSProperty(S, cast<CXXRecordDecl>(Val: CurContext), Loc, D,
3641 BitWidth, InitStyle, AS, *MSPropertyAttr);
3642 if (!Member)
3643 return nullptr;
3644 isInstField = false;
3645 } else {
3646 Member = HandleField(S, cast<CXXRecordDecl>(Val: CurContext), Loc, D,
3647 BitWidth, InitStyle, AS);
3648 if (!Member)
3649 return nullptr;
3650 }
3651
3652 CheckShadowInheritedFields(Loc, FieldName: Name, RD: cast<CXXRecordDecl>(Val: CurContext));
3653 } else {
3654 Member = HandleDeclarator(S, D, TemplateParameterLists);
3655 if (!Member)
3656 return nullptr;
3657
3658 // Non-instance-fields can't have a bitfield.
3659 if (BitWidth) {
3660 if (Member->isInvalidDecl()) {
3661 // don't emit another diagnostic.
3662 } else if (isa<VarDecl>(Val: Member) || isa<VarTemplateDecl>(Val: Member)) {
3663 // C++ 9.6p3: A bit-field shall not be a static member.
3664 // "static member 'A' cannot be a bit-field"
3665 Diag(Loc, diag::err_static_not_bitfield)
3666 << Name << BitWidth->getSourceRange();
3667 } else if (isa<TypedefDecl>(Val: Member)) {
3668 // "typedef member 'x' cannot be a bit-field"
3669 Diag(Loc, diag::err_typedef_not_bitfield)
3670 << Name << BitWidth->getSourceRange();
3671 } else {
3672 // A function typedef ("typedef int f(); f a;").
3673 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3674 Diag(Loc, diag::err_not_integral_type_bitfield)
3675 << Name << cast<ValueDecl>(Member)->getType()
3676 << BitWidth->getSourceRange();
3677 }
3678
3679 BitWidth = nullptr;
3680 Member->setInvalidDecl();
3681 }
3682
3683 NamedDecl *NonTemplateMember = Member;
3684 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Member))
3685 NonTemplateMember = FunTmpl->getTemplatedDecl();
3686 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Val: Member))
3687 NonTemplateMember = VarTmpl->getTemplatedDecl();
3688
3689 Member->setAccess(AS);
3690
3691 // If we have declared a member function template or static data member
3692 // template, set the access of the templated declaration as well.
3693 if (NonTemplateMember != Member)
3694 NonTemplateMember->setAccess(AS);
3695
3696 // C++ [temp.deduct.guide]p3:
3697 // A deduction guide [...] for a member class template [shall be
3698 // declared] with the same access [as the template].
3699 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: NonTemplateMember)) {
3700 auto *TD = DG->getDeducedTemplate();
3701 // Access specifiers are only meaningful if both the template and the
3702 // deduction guide are from the same scope.
3703 if (AS != TD->getAccess() &&
3704 TD->getDeclContext()->getRedeclContext()->Equals(
3705 DG->getDeclContext()->getRedeclContext())) {
3706 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3707 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3708 << TD->getAccess();
3709 const AccessSpecDecl *LastAccessSpec = nullptr;
3710 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3711 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3712 LastAccessSpec = AccessSpec;
3713 }
3714 assert(LastAccessSpec && "differing access with no access specifier");
3715 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3716 << AS;
3717 }
3718 }
3719 }
3720
3721 if (VS.isOverrideSpecified())
3722 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3723 if (VS.isFinalSpecified())
3724 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3725 VS.isFinalSpelledSealed()
3726 ? FinalAttr::Keyword_sealed
3727 : FinalAttr::Keyword_final));
3728
3729 if (VS.getLastLocation().isValid()) {
3730 // Update the end location of a method that has a virt-specifiers.
3731 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Member))
3732 MD->setRangeEnd(VS.getLastLocation());
3733 }
3734
3735 CheckOverrideControl(D: Member);
3736
3737 assert((Name || isInstField) && "No identifier for non-field ?");
3738
3739 if (isInstField) {
3740 FieldDecl *FD = cast<FieldDecl>(Val: Member);
3741 FieldCollector->Add(D: FD);
3742
3743 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3744 // Remember all explicit private FieldDecls that have a name, no side
3745 // effects and are not part of a dependent type declaration.
3746
3747 auto DeclHasUnusedAttr = [](const QualType &T) {
3748 if (const TagDecl *TD = T->getAsTagDecl())
3749 return TD->hasAttr<UnusedAttr>();
3750 if (const TypedefType *TDT = T->getAs<TypedefType>())
3751 return TDT->getDecl()->hasAttr<UnusedAttr>();
3752 return false;
3753 };
3754
3755 if (!FD->isImplicit() && FD->getDeclName() &&
3756 FD->getAccess() == AS_private &&
3757 !FD->hasAttr<UnusedAttr>() &&
3758 !FD->getParent()->isDependentContext() &&
3759 !DeclHasUnusedAttr(FD->getType()) &&
3760 !InitializationHasSideEffects(*FD))
3761 UnusedPrivateFields.insert(FD);
3762 }
3763 }
3764
3765 return Member;
3766}
3767
3768namespace {
3769 class UninitializedFieldVisitor
3770 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3771 Sema &S;
3772 // List of Decls to generate a warning on. Also remove Decls that become
3773 // initialized.
3774 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3775 // List of base classes of the record. Classes are removed after their
3776 // initializers.
3777 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3778 // Vector of decls to be removed from the Decl set prior to visiting the
3779 // nodes. These Decls may have been initialized in the prior initializer.
3780 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3781 // If non-null, add a note to the warning pointing back to the constructor.
3782 const CXXConstructorDecl *Constructor;
3783 // Variables to hold state when processing an initializer list. When
3784 // InitList is true, special case initialization of FieldDecls matching
3785 // InitListFieldDecl.
3786 bool InitList;
3787 FieldDecl *InitListFieldDecl;
3788 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3789
3790 public:
3791 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3792 UninitializedFieldVisitor(Sema &S,
3793 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3794 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3795 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3796 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3797
3798 // Returns true if the use of ME is not an uninitialized use.
3799 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3800 bool CheckReferenceOnly) {
3801 llvm::SmallVector<FieldDecl*, 4> Fields;
3802 bool ReferenceField = false;
3803 while (ME) {
3804 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
3805 if (!FD)
3806 return false;
3807 Fields.push_back(Elt: FD);
3808 if (FD->getType()->isReferenceType())
3809 ReferenceField = true;
3810 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParenImpCasts());
3811 }
3812
3813 // Binding a reference to an uninitialized field is not an
3814 // uninitialized use.
3815 if (CheckReferenceOnly && !ReferenceField)
3816 return true;
3817
3818 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3819 // Discard the first field since it is the field decl that is being
3820 // initialized.
3821 for (const FieldDecl *FD : llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Fields)))
3822 UsedFieldIndex.push_back(Elt: FD->getFieldIndex());
3823
3824 for (auto UsedIter = UsedFieldIndex.begin(),
3825 UsedEnd = UsedFieldIndex.end(),
3826 OrigIter = InitFieldIndex.begin(),
3827 OrigEnd = InitFieldIndex.end();
3828 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3829 if (*UsedIter < *OrigIter)
3830 return true;
3831 if (*UsedIter > *OrigIter)
3832 break;
3833 }
3834
3835 return false;
3836 }
3837
3838 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3839 bool AddressOf) {
3840 if (isa<EnumConstantDecl>(Val: ME->getMemberDecl()))
3841 return;
3842
3843 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3844 // or union.
3845 MemberExpr *FieldME = ME;
3846
3847 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3848
3849 Expr *Base = ME;
3850 while (MemberExpr *SubME =
3851 dyn_cast<MemberExpr>(Val: Base->IgnoreParenImpCasts())) {
3852
3853 if (isa<VarDecl>(Val: SubME->getMemberDecl()))
3854 return;
3855
3856 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: SubME->getMemberDecl()))
3857 if (!FD->isAnonymousStructOrUnion())
3858 FieldME = SubME;
3859
3860 if (!FieldME->getType().isPODType(S.Context))
3861 AllPODFields = false;
3862
3863 Base = SubME->getBase();
3864 }
3865
3866 if (!isa<CXXThisExpr>(Val: Base->IgnoreParenImpCasts())) {
3867 Visit(Base);
3868 return;
3869 }
3870
3871 if (AddressOf && AllPODFields)
3872 return;
3873
3874 ValueDecl* FoundVD = FieldME->getMemberDecl();
3875
3876 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Val: Base)) {
3877 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3878 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3879 }
3880
3881 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3882 QualType T = BaseCast->getType();
3883 if (T->isPointerType() &&
3884 BaseClasses.count(Ptr: T->getPointeeType())) {
3885 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3886 << T->getPointeeType() << FoundVD;
3887 }
3888 }
3889 }
3890
3891 if (!Decls.count(Ptr: FoundVD))
3892 return;
3893
3894 const bool IsReference = FoundVD->getType()->isReferenceType();
3895
3896 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3897 // Special checking for initializer lists.
3898 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3899 return;
3900 }
3901 } else {
3902 // Prevent double warnings on use of unbounded references.
3903 if (CheckReferenceOnly && !IsReference)
3904 return;
3905 }
3906
3907 unsigned diag = IsReference
3908 ? diag::warn_reference_field_is_uninit
3909 : diag::warn_field_is_uninit;
3910 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag) << FoundVD;
3911 if (Constructor)
3912 S.Diag(Constructor->getLocation(),
3913 diag::note_uninit_in_this_constructor)
3914 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3915
3916 }
3917
3918 void HandleValue(Expr *E, bool AddressOf) {
3919 E = E->IgnoreParens();
3920
3921 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
3922 HandleMemberExpr(ME, CheckReferenceOnly: false /*CheckReferenceOnly*/,
3923 AddressOf /*AddressOf*/);
3924 return;
3925 }
3926
3927 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
3928 Visit(CO->getCond());
3929 HandleValue(E: CO->getTrueExpr(), AddressOf);
3930 HandleValue(E: CO->getFalseExpr(), AddressOf);
3931 return;
3932 }
3933
3934 if (BinaryConditionalOperator *BCO =
3935 dyn_cast<BinaryConditionalOperator>(Val: E)) {
3936 Visit(BCO->getCond());
3937 HandleValue(E: BCO->getFalseExpr(), AddressOf);
3938 return;
3939 }
3940
3941 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
3942 HandleValue(E: OVE->getSourceExpr(), AddressOf);
3943 return;
3944 }
3945
3946 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
3947 switch (BO->getOpcode()) {
3948 default:
3949 break;
3950 case(BO_PtrMemD):
3951 case(BO_PtrMemI):
3952 HandleValue(E: BO->getLHS(), AddressOf);
3953 Visit(BO->getRHS());
3954 return;
3955 case(BO_Comma):
3956 Visit(BO->getLHS());
3957 HandleValue(E: BO->getRHS(), AddressOf);
3958 return;
3959 }
3960 }
3961
3962 Visit(E);
3963 }
3964
3965 void CheckInitListExpr(InitListExpr *ILE) {
3966 InitFieldIndex.push_back(Elt: 0);
3967 for (auto *Child : ILE->children()) {
3968 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Val: Child)) {
3969 CheckInitListExpr(ILE: SubList);
3970 } else {
3971 Visit(S: Child);
3972 }
3973 ++InitFieldIndex.back();
3974 }
3975 InitFieldIndex.pop_back();
3976 }
3977
3978 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3979 FieldDecl *Field, const Type *BaseClass) {
3980 // Remove Decls that may have been initialized in the previous
3981 // initializer.
3982 for (ValueDecl* VD : DeclsToRemove)
3983 Decls.erase(Ptr: VD);
3984 DeclsToRemove.clear();
3985
3986 Constructor = FieldConstructor;
3987 InitListExpr *ILE = dyn_cast<InitListExpr>(Val: E);
3988
3989 if (ILE && Field) {
3990 InitList = true;
3991 InitListFieldDecl = Field;
3992 InitFieldIndex.clear();
3993 CheckInitListExpr(ILE);
3994 } else {
3995 InitList = false;
3996 Visit(E);
3997 }
3998
3999 if (Field)
4000 Decls.erase(Field);
4001 if (BaseClass)
4002 BaseClasses.erase(Ptr: BaseClass->getCanonicalTypeInternal());
4003 }
4004
4005 void VisitMemberExpr(MemberExpr *ME) {
4006 // All uses of unbounded reference fields will warn.
4007 HandleMemberExpr(ME, CheckReferenceOnly: true /*CheckReferenceOnly*/, AddressOf: false /*AddressOf*/);
4008 }
4009
4010 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4011 if (E->getCastKind() == CK_LValueToRValue) {
4012 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4013 return;
4014 }
4015
4016 Inherited::VisitImplicitCastExpr(E);
4017 }
4018
4019 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4020 if (E->getConstructor()->isCopyConstructor()) {
4021 Expr *ArgExpr = E->getArg(Arg: 0);
4022 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
4023 if (ILE->getNumInits() == 1)
4024 ArgExpr = ILE->getInit(Init: 0);
4025 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
4026 if (ICE->getCastKind() == CK_NoOp)
4027 ArgExpr = ICE->getSubExpr();
4028 HandleValue(E: ArgExpr, AddressOf: false /*AddressOf*/);
4029 return;
4030 }
4031 Inherited::VisitCXXConstructExpr(E);
4032 }
4033
4034 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4035 Expr *Callee = E->getCallee();
4036 if (isa<MemberExpr>(Val: Callee)) {
4037 HandleValue(E: Callee, AddressOf: false /*AddressOf*/);
4038 for (auto *Arg : E->arguments())
4039 Visit(Arg);
4040 return;
4041 }
4042
4043 Inherited::VisitCXXMemberCallExpr(E);
4044 }
4045
4046 void VisitCallExpr(CallExpr *E) {
4047 // Treat std::move as a use.
4048 if (E->isCallToStdMove()) {
4049 HandleValue(E: E->getArg(Arg: 0), /*AddressOf=*/false);
4050 return;
4051 }
4052
4053 Inherited::VisitCallExpr(CE: E);
4054 }
4055
4056 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4057 Expr *Callee = E->getCallee();
4058
4059 if (isa<UnresolvedLookupExpr>(Callee))
4060 return Inherited::VisitCXXOperatorCallExpr(E);
4061
4062 Visit(Callee);
4063 for (auto *Arg : E->arguments())
4064 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4065 }
4066
4067 void VisitBinaryOperator(BinaryOperator *E) {
4068 // If a field assignment is detected, remove the field from the
4069 // uninitiailized field set.
4070 if (E->getOpcode() == BO_Assign)
4071 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getLHS()))
4072 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()))
4073 if (!FD->getType()->isReferenceType())
4074 DeclsToRemove.push_back(FD);
4075
4076 if (E->isCompoundAssignmentOp()) {
4077 HandleValue(E: E->getLHS(), AddressOf: false /*AddressOf*/);
4078 Visit(E->getRHS());
4079 return;
4080 }
4081
4082 Inherited::VisitBinaryOperator(E);
4083 }
4084
4085 void VisitUnaryOperator(UnaryOperator *E) {
4086 if (E->isIncrementDecrementOp()) {
4087 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4088 return;
4089 }
4090 if (E->getOpcode() == UO_AddrOf) {
4091 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getSubExpr())) {
4092 HandleValue(E: ME->getBase(), AddressOf: true /*AddressOf*/);
4093 return;
4094 }
4095 }
4096
4097 Inherited::VisitUnaryOperator(E);
4098 }
4099 };
4100
4101 // Diagnose value-uses of fields to initialize themselves, e.g.
4102 // foo(foo)
4103 // where foo is not also a parameter to the constructor.
4104 // Also diagnose across field uninitialized use such as
4105 // x(y), y(x)
4106 // TODO: implement -Wuninitialized and fold this into that framework.
4107 static void DiagnoseUninitializedFields(
4108 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4109
4110 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4111 Constructor->getLocation())) {
4112 return;
4113 }
4114
4115 if (Constructor->isInvalidDecl())
4116 return;
4117
4118 const CXXRecordDecl *RD = Constructor->getParent();
4119
4120 if (RD->isDependentContext())
4121 return;
4122
4123 // Holds fields that are uninitialized.
4124 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4125
4126 // At the beginning, all fields are uninitialized.
4127 for (auto *I : RD->decls()) {
4128 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4129 UninitializedFields.insert(FD);
4130 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4131 UninitializedFields.insert(IFD->getAnonField());
4132 }
4133 }
4134
4135 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4136 for (const auto &I : RD->bases())
4137 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4138
4139 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4140 return;
4141
4142 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4143 UninitializedFields,
4144 UninitializedBaseClasses);
4145
4146 for (const auto *FieldInit : Constructor->inits()) {
4147 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4148 break;
4149
4150 Expr *InitExpr = FieldInit->getInit();
4151 if (!InitExpr)
4152 continue;
4153
4154 if (CXXDefaultInitExpr *Default =
4155 dyn_cast<CXXDefaultInitExpr>(Val: InitExpr)) {
4156 InitExpr = Default->getExpr();
4157 if (!InitExpr)
4158 continue;
4159 // In class initializers will point to the constructor.
4160 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: Constructor,
4161 Field: FieldInit->getAnyMember(),
4162 BaseClass: FieldInit->getBaseClass());
4163 } else {
4164 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: nullptr,
4165 Field: FieldInit->getAnyMember(),
4166 BaseClass: FieldInit->getBaseClass());
4167 }
4168 }
4169 }
4170} // namespace
4171
4172/// Enter a new C++ default initializer scope. After calling this, the
4173/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4174/// parsing or instantiating the initializer failed.
4175void Sema::ActOnStartCXXInClassMemberInitializer() {
4176 // Create a synthetic function scope to represent the call to the constructor
4177 // that notionally surrounds a use of this initializer.
4178 PushFunctionScope();
4179}
4180
4181void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4182 if (!D.isFunctionDeclarator())
4183 return;
4184 auto &FTI = D.getFunctionTypeInfo();
4185 if (!FTI.Params)
4186 return;
4187 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4188 FTI.NumParams)) {
4189 auto *ParamDecl = cast<NamedDecl>(Val: Param.Param);
4190 if (ParamDecl->getDeclName())
4191 PushOnScopeChains(D: ParamDecl, S, /*AddToContext=*/false);
4192 }
4193}
4194
4195ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4196 return ActOnRequiresClause(ConstraintExpr);
4197}
4198
4199ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4200 if (ConstraintExpr.isInvalid())
4201 return ExprError();
4202
4203 ConstraintExpr = CorrectDelayedTyposInExpr(ER: ConstraintExpr);
4204 if (ConstraintExpr.isInvalid())
4205 return ExprError();
4206
4207 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr.get(),
4208 UPPC: UPPC_RequiresClause))
4209 return ExprError();
4210
4211 return ConstraintExpr;
4212}
4213
4214ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4215 Expr *InitExpr,
4216 SourceLocation InitLoc) {
4217 InitializedEntity Entity =
4218 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: FD);
4219 InitializationKind Kind =
4220 FD->getInClassInitStyle() == ICIS_ListInit
4221 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4222 InitExpr->getBeginLoc(),
4223 InitExpr->getEndLoc())
4224 : InitializationKind::CreateCopy(InitLoc: InitExpr->getBeginLoc(), EqualLoc: InitLoc);
4225 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4226 return Seq.Perform(S&: *this, Entity, Kind, Args: InitExpr);
4227}
4228
4229/// This is invoked after parsing an in-class initializer for a
4230/// non-static C++ class member, and after instantiating an in-class initializer
4231/// in a class template. Such actions are deferred until the class is complete.
4232void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4233 SourceLocation InitLoc,
4234 Expr *InitExpr) {
4235 // Pop the notional constructor scope we created earlier.
4236 PopFunctionScopeInfo(WP: nullptr, D);
4237
4238 FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
4239 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4240 "must set init style when field is created");
4241
4242 if (!InitExpr) {
4243 D->setInvalidDecl();
4244 if (FD)
4245 FD->removeInClassInitializer();
4246 return;
4247 }
4248
4249 if (DiagnoseUnexpandedParameterPack(E: InitExpr, UPPC: UPPC_Initializer)) {
4250 FD->setInvalidDecl();
4251 FD->removeInClassInitializer();
4252 return;
4253 }
4254
4255 ExprResult Init = CorrectDelayedTyposInExpr(E: InitExpr, /*InitDecl=*/nullptr,
4256 /*RecoverUncorrectedTypos=*/true);
4257 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4258 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4259 Init = ConvertMemberDefaultInitExpression(FD, InitExpr: Init.get(), InitLoc);
4260 // C++11 [class.base.init]p7:
4261 // The initialization of each base and member constitutes a
4262 // full-expression.
4263 if (!Init.isInvalid())
4264 Init = ActOnFinishFullExpr(Expr: Init.get(), /*DiscarededValue=*/DiscardedValue: false);
4265 if (Init.isInvalid()) {
4266 FD->setInvalidDecl();
4267 return;
4268 }
4269 }
4270
4271 FD->setInClassInitializer(Init.get());
4272}
4273
4274/// Find the direct and/or virtual base specifiers that
4275/// correspond to the given base type, for use in base initialization
4276/// within a constructor.
4277static bool FindBaseInitializer(Sema &SemaRef,
4278 CXXRecordDecl *ClassDecl,
4279 QualType BaseType,
4280 const CXXBaseSpecifier *&DirectBaseSpec,
4281 const CXXBaseSpecifier *&VirtualBaseSpec) {
4282 // First, check for a direct base class.
4283 DirectBaseSpec = nullptr;
4284 for (const auto &Base : ClassDecl->bases()) {
4285 if (SemaRef.Context.hasSameUnqualifiedType(T1: BaseType, T2: Base.getType())) {
4286 // We found a direct base of this type. That's what we're
4287 // initializing.
4288 DirectBaseSpec = &Base;
4289 break;
4290 }
4291 }
4292
4293 // Check for a virtual base class.
4294 // FIXME: We might be able to short-circuit this if we know in advance that
4295 // there are no virtual bases.
4296 VirtualBaseSpec = nullptr;
4297 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4298 // We haven't found a base yet; search the class hierarchy for a
4299 // virtual base class.
4300 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4301 /*DetectVirtual=*/false);
4302 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4303 SemaRef.Context.getTypeDeclType(ClassDecl),
4304 BaseType, Paths)) {
4305 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4306 Path != Paths.end(); ++Path) {
4307 if (Path->back().Base->isVirtual()) {
4308 VirtualBaseSpec = Path->back().Base;
4309 break;
4310 }
4311 }
4312 }
4313 }
4314
4315 return DirectBaseSpec || VirtualBaseSpec;
4316}
4317
4318/// Handle a C++ member initializer using braced-init-list syntax.
4319MemInitResult
4320Sema::ActOnMemInitializer(Decl *ConstructorD,
4321 Scope *S,
4322 CXXScopeSpec &SS,
4323 IdentifierInfo *MemberOrBase,
4324 ParsedType TemplateTypeTy,
4325 const DeclSpec &DS,
4326 SourceLocation IdLoc,
4327 Expr *InitList,
4328 SourceLocation EllipsisLoc) {
4329 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4330 DS, IdLoc, Init: InitList,
4331 EllipsisLoc);
4332}
4333
4334/// Handle a C++ member initializer using parentheses syntax.
4335MemInitResult
4336Sema::ActOnMemInitializer(Decl *ConstructorD,
4337 Scope *S,
4338 CXXScopeSpec &SS,
4339 IdentifierInfo *MemberOrBase,
4340 ParsedType TemplateTypeTy,
4341 const DeclSpec &DS,
4342 SourceLocation IdLoc,
4343 SourceLocation LParenLoc,
4344 ArrayRef<Expr *> Args,
4345 SourceLocation RParenLoc,
4346 SourceLocation EllipsisLoc) {
4347 Expr *List = ParenListExpr::Create(Ctx: Context, LParenLoc, Exprs: Args, RParenLoc);
4348 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4349 DS, IdLoc, Init: List, EllipsisLoc);
4350}
4351
4352namespace {
4353
4354// Callback to only accept typo corrections that can be a valid C++ member
4355// initializer: either a non-static field member or a base class.
4356class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4357public:
4358 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4359 : ClassDecl(ClassDecl) {}
4360
4361 bool ValidateCandidate(const TypoCorrection &candidate) override {
4362 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4363 if (FieldDecl *Member = dyn_cast<FieldDecl>(Val: ND))
4364 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4365 return isa<TypeDecl>(Val: ND);
4366 }
4367 return false;
4368 }
4369
4370 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4371 return std::make_unique<MemInitializerValidatorCCC>(args&: *this);
4372 }
4373
4374private:
4375 CXXRecordDecl *ClassDecl;
4376};
4377
4378}
4379
4380bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4381 RecordDecl *ClassDecl,
4382 const IdentifierInfo *Name) {
4383 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4384 DeclContextLookupResult::iterator Found =
4385 llvm::find_if(Range&: Result, P: [this](const NamedDecl *Elem) {
4386 return isa<FieldDecl, IndirectFieldDecl>(Val: Elem) &&
4387 Elem->isPlaceholderVar(LangOpts: getLangOpts());
4388 });
4389 // We did not find a placeholder variable
4390 if (Found == Result.end())
4391 return false;
4392 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4393 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4394 const NamedDecl *ND = *It;
4395 if (ND->getDeclContext() != ND->getDeclContext())
4396 break;
4397 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4398 ND->isPlaceholderVar(getLangOpts()))
4399 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4400 }
4401 return true;
4402}
4403
4404ValueDecl *
4405Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4406 const IdentifierInfo *MemberOrBase) {
4407 ValueDecl *ND = nullptr;
4408 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4409 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4410 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4411 if (ND) {
4412 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4413 return nullptr;
4414 break;
4415 }
4416 if (!IsPlaceholder)
4417 return cast<ValueDecl>(D);
4418 ND = cast<ValueDecl>(D);
4419 }
4420 }
4421 return ND;
4422}
4423
4424ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4425 CXXScopeSpec &SS,
4426 ParsedType TemplateTypeTy,
4427 IdentifierInfo *MemberOrBase) {
4428 if (SS.getScopeRep() || TemplateTypeTy)
4429 return nullptr;
4430 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4431}
4432
4433/// Handle a C++ member initializer.
4434MemInitResult
4435Sema::BuildMemInitializer(Decl *ConstructorD,
4436 Scope *S,
4437 CXXScopeSpec &SS,
4438 IdentifierInfo *MemberOrBase,
4439 ParsedType TemplateTypeTy,
4440 const DeclSpec &DS,
4441 SourceLocation IdLoc,
4442 Expr *Init,
4443 SourceLocation EllipsisLoc) {
4444 ExprResult Res = CorrectDelayedTyposInExpr(E: Init, /*InitDecl=*/nullptr,
4445 /*RecoverUncorrectedTypos=*/true);
4446 if (!Res.isUsable())
4447 return true;
4448 Init = Res.get();
4449
4450 if (!ConstructorD)
4451 return true;
4452
4453 AdjustDeclIfTemplate(Decl&: ConstructorD);
4454
4455 CXXConstructorDecl *Constructor
4456 = dyn_cast<CXXConstructorDecl>(Val: ConstructorD);
4457 if (!Constructor) {
4458 // The user wrote a constructor initializer on a function that is
4459 // not a C++ constructor. Ignore the error for now, because we may
4460 // have more member initializers coming; we'll diagnose it just
4461 // once in ActOnMemInitializers.
4462 return true;
4463 }
4464
4465 CXXRecordDecl *ClassDecl = Constructor->getParent();
4466
4467 // C++ [class.base.init]p2:
4468 // Names in a mem-initializer-id are looked up in the scope of the
4469 // constructor's class and, if not found in that scope, are looked
4470 // up in the scope containing the constructor's definition.
4471 // [Note: if the constructor's class contains a member with the
4472 // same name as a direct or virtual base class of the class, a
4473 // mem-initializer-id naming the member or base class and composed
4474 // of a single identifier refers to the class member. A
4475 // mem-initializer-id for the hidden base class may be specified
4476 // using a qualified name. ]
4477
4478 // Look for a member, first.
4479 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4480 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4481 if (EllipsisLoc.isValid())
4482 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4483 << MemberOrBase
4484 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4485
4486 return BuildMemberInitializer(Member, Init, IdLoc);
4487 }
4488 // It didn't name a member, so see if it names a class.
4489 QualType BaseType;
4490 TypeSourceInfo *TInfo = nullptr;
4491
4492 if (TemplateTypeTy) {
4493 BaseType = GetTypeFromParser(Ty: TemplateTypeTy, TInfo: &TInfo);
4494 if (BaseType.isNull())
4495 return true;
4496 } else if (DS.getTypeSpecType() == TST_decltype) {
4497 BaseType = BuildDecltypeType(E: DS.getRepAsExpr());
4498 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4499 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4500 return true;
4501 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4502 BaseType =
4503 BuildPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(),
4504 Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc());
4505 } else {
4506 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4507 LookupParsedName(R, S, SS: &SS);
4508
4509 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4510 if (!TyD) {
4511 if (R.isAmbiguous()) return true;
4512
4513 // We don't want access-control diagnostics here.
4514 R.suppressDiagnostics();
4515
4516 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4517 bool NotUnknownSpecialization = false;
4518 DeclContext *DC = computeDeclContext(SS, EnteringContext: false);
4519 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Val: DC))
4520 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4521
4522 if (!NotUnknownSpecialization) {
4523 // When the scope specifier can refer to a member of an unknown
4524 // specialization, we take it as a type name.
4525 BaseType = CheckTypenameType(
4526 Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(),
4527 QualifierLoc: SS.getWithLocInContext(Context), II: *MemberOrBase, IILoc: IdLoc);
4528 if (BaseType.isNull())
4529 return true;
4530
4531 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4532 DependentNameTypeLoc TL =
4533 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4534 if (!TL.isNull()) {
4535 TL.setNameLoc(IdLoc);
4536 TL.setElaboratedKeywordLoc(SourceLocation());
4537 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4538 }
4539
4540 R.clear();
4541 R.setLookupName(MemberOrBase);
4542 }
4543 }
4544
4545 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4546 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4547 auto *TempSpec = cast<TemplateSpecializationType>(
4548 Val: UnqualifiedBase->getInjectedClassNameSpecialization());
4549 TemplateName TN = TempSpec->getTemplateName();
4550 for (auto const &Base : ClassDecl->bases()) {
4551 auto BaseTemplate =
4552 Base.getType()->getAs<TemplateSpecializationType>();
4553 if (BaseTemplate && Context.hasSameTemplateName(
4554 BaseTemplate->getTemplateName(), TN)) {
4555 Diag(IdLoc, diag::ext_unqualified_base_class)
4556 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4557 BaseType = Base.getType();
4558 break;
4559 }
4560 }
4561 }
4562 }
4563
4564 // If no results were found, try to correct typos.
4565 TypoCorrection Corr;
4566 MemInitializerValidatorCCC CCC(ClassDecl);
4567 if (R.empty() && BaseType.isNull() &&
4568 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4569 CCC, CTK_ErrorRecovery, ClassDecl))) {
4570 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4571 // We have found a non-static data member with a similar
4572 // name to what was typed; complain and initialize that
4573 // member.
4574 diagnoseTypo(Corr,
4575 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4576 << MemberOrBase << true);
4577 return BuildMemberInitializer(Member, Init, IdLoc);
4578 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4579 const CXXBaseSpecifier *DirectBaseSpec;
4580 const CXXBaseSpecifier *VirtualBaseSpec;
4581 if (FindBaseInitializer(SemaRef&: *this, ClassDecl,
4582 BaseType: Context.getTypeDeclType(Decl: Type),
4583 DirectBaseSpec, VirtualBaseSpec)) {
4584 // We have found a direct or virtual base class with a
4585 // similar name to what was typed; complain and initialize
4586 // that base class.
4587 diagnoseTypo(Corr,
4588 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4589 << MemberOrBase << false,
4590 PDiag() /*Suppress note, we provide our own.*/);
4591
4592 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4593 : VirtualBaseSpec;
4594 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4595 << BaseSpec->getType() << BaseSpec->getSourceRange();
4596
4597 TyD = Type;
4598 }
4599 }
4600 }
4601
4602 if (!TyD && BaseType.isNull()) {
4603 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4604 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4605 return true;
4606 }
4607 }
4608
4609 if (BaseType.isNull()) {
4610 BaseType = getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS,
4611 T: Context.getTypeDeclType(Decl: TyD));
4612 MarkAnyDeclReferenced(Loc: TyD->getLocation(), D: TyD, /*OdrUse=*/MightBeOdrUse: false);
4613 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4614 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4615 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4616 TL.setElaboratedKeywordLoc(SourceLocation());
4617 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4618 }
4619 }
4620
4621 if (!TInfo)
4622 TInfo = Context.getTrivialTypeSourceInfo(T: BaseType, Loc: IdLoc);
4623
4624 return BuildBaseInitializer(BaseType, BaseTInfo: TInfo, Init, ClassDecl, EllipsisLoc);
4625}
4626
4627MemInitResult
4628Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4629 SourceLocation IdLoc) {
4630 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Val: Member);
4631 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Val: Member);
4632 assert((DirectMember || IndirectMember) &&
4633 "Member must be a FieldDecl or IndirectFieldDecl");
4634
4635 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4636 return true;
4637
4638 if (Member->isInvalidDecl())
4639 return true;
4640
4641 MultiExprArg Args;
4642 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4643 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4644 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
4645 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4646 } else {
4647 // Template instantiation doesn't reconstruct ParenListExprs for us.
4648 Args = Init;
4649 }
4650
4651 SourceRange InitRange = Init->getSourceRange();
4652
4653 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4654 // Can't check initialization for a member of dependent type or when
4655 // any of the arguments are type-dependent expressions.
4656 DiscardCleanupsInEvaluationContext();
4657 } else {
4658 bool InitList = false;
4659 if (isa<InitListExpr>(Val: Init)) {
4660 InitList = true;
4661 Args = Init;
4662 }
4663
4664 // Initialize the member.
4665 InitializedEntity MemberEntity =
4666 DirectMember ? InitializedEntity::InitializeMember(Member: DirectMember, Parent: nullptr)
4667 : InitializedEntity::InitializeMember(Member: IndirectMember,
4668 Parent: nullptr);
4669 InitializationKind Kind =
4670 InitList ? InitializationKind::CreateDirectList(
4671 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4672 : InitializationKind::CreateDirect(InitLoc: IdLoc, LParenLoc: InitRange.getBegin(),
4673 RParenLoc: InitRange.getEnd());
4674
4675 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4676 ExprResult MemberInit = InitSeq.Perform(S&: *this, Entity: MemberEntity, Kind, Args,
4677 ResultType: nullptr);
4678 if (!MemberInit.isInvalid()) {
4679 // C++11 [class.base.init]p7:
4680 // The initialization of each base and member constitutes a
4681 // full-expression.
4682 MemberInit = ActOnFinishFullExpr(Expr: MemberInit.get(), CC: InitRange.getBegin(),
4683 /*DiscardedValue*/ false);
4684 }
4685
4686 if (MemberInit.isInvalid()) {
4687 // Args were sensible expressions but we couldn't initialize the member
4688 // from them. Preserve them in a RecoveryExpr instead.
4689 Init = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4690 T: Member->getType())
4691 .get();
4692 if (!Init)
4693 return true;
4694 } else {
4695 Init = MemberInit.get();
4696 }
4697 }
4698
4699 if (DirectMember) {
4700 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4701 InitRange.getBegin(), Init,
4702 InitRange.getEnd());
4703 } else {
4704 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4705 InitRange.getBegin(), Init,
4706 InitRange.getEnd());
4707 }
4708}
4709
4710MemInitResult
4711Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4712 CXXRecordDecl *ClassDecl) {
4713 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4714 if (!LangOpts.CPlusPlus11)
4715 return Diag(NameLoc, diag::err_delegating_ctor)
4716 << TInfo->getTypeLoc().getSourceRange();
4717 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4718
4719 bool InitList = true;
4720 MultiExprArg Args = Init;
4721 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4722 InitList = false;
4723 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4724 }
4725
4726 SourceRange InitRange = Init->getSourceRange();
4727 // Initialize the object.
4728 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4729 Type: QualType(ClassDecl->getTypeForDecl(), 0));
4730 InitializationKind Kind =
4731 InitList ? InitializationKind::CreateDirectList(
4732 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4733 : InitializationKind::CreateDirect(InitLoc: NameLoc, LParenLoc: InitRange.getBegin(),
4734 RParenLoc: InitRange.getEnd());
4735 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4736 ExprResult DelegationInit = InitSeq.Perform(S&: *this, Entity: DelegationEntity, Kind,
4737 Args, ResultType: nullptr);
4738 if (!DelegationInit.isInvalid()) {
4739 assert((DelegationInit.get()->containsErrors() ||
4740 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4741 "Delegating constructor with no target?");
4742
4743 // C++11 [class.base.init]p7:
4744 // The initialization of each base and member constitutes a
4745 // full-expression.
4746 DelegationInit = ActOnFinishFullExpr(
4747 Expr: DelegationInit.get(), CC: InitRange.getBegin(), /*DiscardedValue*/ false);
4748 }
4749
4750 if (DelegationInit.isInvalid()) {
4751 DelegationInit =
4752 CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4753 T: QualType(ClassDecl->getTypeForDecl(), 0));
4754 if (DelegationInit.isInvalid())
4755 return true;
4756 } else {
4757 // If we are in a dependent context, template instantiation will
4758 // perform this type-checking again. Just save the arguments that we
4759 // received in a ParenListExpr.
4760 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4761 // of the information that we have about the base
4762 // initializer. However, deconstructing the ASTs is a dicey process,
4763 // and this approach is far more likely to get the corner cases right.
4764 if (CurContext->isDependentContext())
4765 DelegationInit = Init;
4766 }
4767
4768 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4769 DelegationInit.getAs<Expr>(),
4770 InitRange.getEnd());
4771}
4772
4773MemInitResult
4774Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4775 Expr *Init, CXXRecordDecl *ClassDecl,
4776 SourceLocation EllipsisLoc) {
4777 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4778
4779 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4780 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4781 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4782
4783 // C++ [class.base.init]p2:
4784 // [...] Unless the mem-initializer-id names a nonstatic data
4785 // member of the constructor's class or a direct or virtual base
4786 // of that class, the mem-initializer is ill-formed. A
4787 // mem-initializer-list can initialize a base class using any
4788 // name that denotes that base class type.
4789
4790 // We can store the initializers in "as-written" form and delay analysis until
4791 // instantiation if the constructor is dependent. But not for dependent
4792 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4793 bool Dependent = CurContext->isDependentContext() &&
4794 (BaseType->isDependentType() || Init->isTypeDependent());
4795
4796 SourceRange InitRange = Init->getSourceRange();
4797 if (EllipsisLoc.isValid()) {
4798 // This is a pack expansion.
4799 if (!BaseType->containsUnexpandedParameterPack()) {
4800 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4801 << SourceRange(BaseLoc, InitRange.getEnd());
4802
4803 EllipsisLoc = SourceLocation();
4804 }
4805 } else {
4806 // Check for any unexpanded parameter packs.
4807 if (DiagnoseUnexpandedParameterPack(Loc: BaseLoc, T: BaseTInfo, UPPC: UPPC_Initializer))
4808 return true;
4809
4810 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4811 return true;
4812 }
4813
4814 // Check for direct and virtual base classes.
4815 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4816 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4817 if (!Dependent) {
4818 if (Context.hasSameUnqualifiedType(T1: QualType(ClassDecl->getTypeForDecl(),0),
4819 T2: BaseType))
4820 return BuildDelegatingInitializer(TInfo: BaseTInfo, Init, ClassDecl);
4821
4822 FindBaseInitializer(SemaRef&: *this, ClassDecl, BaseType, DirectBaseSpec,
4823 VirtualBaseSpec);
4824
4825 // C++ [base.class.init]p2:
4826 // Unless the mem-initializer-id names a nonstatic data member of the
4827 // constructor's class or a direct or virtual base of that class, the
4828 // mem-initializer is ill-formed.
4829 if (!DirectBaseSpec && !VirtualBaseSpec) {
4830 // If the class has any dependent bases, then it's possible that
4831 // one of those types will resolve to the same type as
4832 // BaseType. Therefore, just treat this as a dependent base
4833 // class initialization. FIXME: Should we try to check the
4834 // initialization anyway? It seems odd.
4835 if (ClassDecl->hasAnyDependentBases())
4836 Dependent = true;
4837 else
4838 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4839 << BaseType << Context.getTypeDeclType(ClassDecl)
4840 << BaseTInfo->getTypeLoc().getSourceRange();
4841 }
4842 }
4843
4844 if (Dependent) {
4845 DiscardCleanupsInEvaluationContext();
4846
4847 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4848 /*IsVirtual=*/false,
4849 InitRange.getBegin(), Init,
4850 InitRange.getEnd(), EllipsisLoc);
4851 }
4852
4853 // C++ [base.class.init]p2:
4854 // If a mem-initializer-id is ambiguous because it designates both
4855 // a direct non-virtual base class and an inherited virtual base
4856 // class, the mem-initializer is ill-formed.
4857 if (DirectBaseSpec && VirtualBaseSpec)
4858 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4859 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4860
4861 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4862 if (!BaseSpec)
4863 BaseSpec = VirtualBaseSpec;
4864
4865 // Initialize the base.
4866 bool InitList = true;
4867 MultiExprArg Args = Init;
4868 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4869 InitList = false;
4870 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4871 }
4872
4873 InitializedEntity BaseEntity =
4874 InitializedEntity::InitializeBase(Context, Base: BaseSpec, IsInheritedVirtualBase: VirtualBaseSpec);
4875 InitializationKind Kind =
4876 InitList ? InitializationKind::CreateDirectList(InitLoc: BaseLoc)
4877 : InitializationKind::CreateDirect(InitLoc: BaseLoc, LParenLoc: InitRange.getBegin(),
4878 RParenLoc: InitRange.getEnd());
4879 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4880 ExprResult BaseInit = InitSeq.Perform(S&: *this, Entity: BaseEntity, Kind, Args, ResultType: nullptr);
4881 if (!BaseInit.isInvalid()) {
4882 // C++11 [class.base.init]p7:
4883 // The initialization of each base and member constitutes a
4884 // full-expression.
4885 BaseInit = ActOnFinishFullExpr(Expr: BaseInit.get(), CC: InitRange.getBegin(),
4886 /*DiscardedValue*/ false);
4887 }
4888
4889 if (BaseInit.isInvalid()) {
4890 BaseInit = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(),
4891 SubExprs: Args, T: BaseType);
4892 if (BaseInit.isInvalid())
4893 return true;
4894 } else {
4895 // If we are in a dependent context, template instantiation will
4896 // perform this type-checking again. Just save the arguments that we
4897 // received in a ParenListExpr.
4898 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4899 // of the information that we have about the base
4900 // initializer. However, deconstructing the ASTs is a dicey process,
4901 // and this approach is far more likely to get the corner cases right.
4902 if (CurContext->isDependentContext())
4903 BaseInit = Init;
4904 }
4905
4906 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4907 BaseSpec->isVirtual(),
4908 InitRange.getBegin(),
4909 BaseInit.getAs<Expr>(),
4910 InitRange.getEnd(), EllipsisLoc);
4911}
4912
4913// Create a static_cast\<T&&>(expr).
4914static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4915 QualType TargetType =
4916 SemaRef.BuildReferenceType(T: E->getType(), /*SpelledAsLValue*/ LValueRef: false,
4917 Loc: SourceLocation(), Entity: DeclarationName());
4918 SourceLocation ExprLoc = E->getBeginLoc();
4919 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4920 T: TargetType, Loc: ExprLoc);
4921
4922 return SemaRef.BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
4923 AngleBrackets: SourceRange(ExprLoc, ExprLoc),
4924 Parens: E->getSourceRange()).get();
4925}
4926
4927/// ImplicitInitializerKind - How an implicit base or member initializer should
4928/// initialize its base or member.
4929enum ImplicitInitializerKind {
4930 IIK_Default,
4931 IIK_Copy,
4932 IIK_Move,
4933 IIK_Inherit
4934};
4935
4936static bool
4937BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4938 ImplicitInitializerKind ImplicitInitKind,
4939 CXXBaseSpecifier *BaseSpec,
4940 bool IsInheritedVirtualBase,
4941 CXXCtorInitializer *&CXXBaseInit) {
4942 InitializedEntity InitEntity
4943 = InitializedEntity::InitializeBase(Context&: SemaRef.Context, Base: BaseSpec,
4944 IsInheritedVirtualBase);
4945
4946 ExprResult BaseInit;
4947
4948 switch (ImplicitInitKind) {
4949 case IIK_Inherit:
4950 case IIK_Default: {
4951 InitializationKind InitKind
4952 = InitializationKind::CreateDefault(InitLoc: Constructor->getLocation());
4953 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4954 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: std::nullopt);
4955 break;
4956 }
4957
4958 case IIK_Move:
4959 case IIK_Copy: {
4960 bool Moving = ImplicitInitKind == IIK_Move;
4961 ParmVarDecl *Param = Constructor->getParamDecl(0);
4962 QualType ParamType = Param->getType().getNonReferenceType();
4963
4964 Expr *CopyCtorArg =
4965 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4966 SourceLocation(), Param, false,
4967 Constructor->getLocation(), ParamType,
4968 VK_LValue, nullptr);
4969
4970 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: CopyCtorArg));
4971
4972 // Cast to the base class to avoid ambiguities.
4973 QualType ArgTy =
4974 SemaRef.Context.getQualifiedType(T: BaseSpec->getType().getUnqualifiedType(),
4975 Qs: ParamType.getQualifiers());
4976
4977 if (Moving) {
4978 CopyCtorArg = CastForMoving(SemaRef, E: CopyCtorArg);
4979 }
4980
4981 CXXCastPath BasePath;
4982 BasePath.push_back(Elt: BaseSpec);
4983 CopyCtorArg = SemaRef.ImpCastExprToType(E: CopyCtorArg, Type: ArgTy,
4984 CK: CK_UncheckedDerivedToBase,
4985 VK: Moving ? VK_XValue : VK_LValue,
4986 BasePath: &BasePath).get();
4987
4988 InitializationKind InitKind
4989 = InitializationKind::CreateDirect(InitLoc: Constructor->getLocation(),
4990 LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
4991 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4992 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: CopyCtorArg);
4993 break;
4994 }
4995 }
4996
4997 BaseInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: BaseInit);
4998 if (BaseInit.isInvalid())
4999 return true;
5000
5001 CXXBaseInit =
5002 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5003 SemaRef.Context.getTrivialTypeSourceInfo(T: BaseSpec->getType(),
5004 Loc: SourceLocation()),
5005 BaseSpec->isVirtual(),
5006 SourceLocation(),
5007 BaseInit.getAs<Expr>(),
5008 SourceLocation(),
5009 SourceLocation());
5010
5011 return false;
5012}
5013
5014static bool RefersToRValueRef(Expr *MemRef) {
5015 ValueDecl *Referenced = cast<MemberExpr>(Val: MemRef)->getMemberDecl();
5016 return Referenced->getType()->isRValueReferenceType();
5017}
5018
5019static bool
5020BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
5021 ImplicitInitializerKind ImplicitInitKind,
5022 FieldDecl *Field, IndirectFieldDecl *Indirect,
5023 CXXCtorInitializer *&CXXMemberInit) {
5024 if (Field->isInvalidDecl())
5025 return true;
5026
5027 SourceLocation Loc = Constructor->getLocation();
5028
5029 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5030 bool Moving = ImplicitInitKind == IIK_Move;
5031 ParmVarDecl *Param = Constructor->getParamDecl(0);
5032 QualType ParamType = Param->getType().getNonReferenceType();
5033
5034 // Suppress copying zero-width bitfields.
5035 if (Field->isZeroLengthBitField(Ctx: SemaRef.Context))
5036 return false;
5037
5038 Expr *MemberExprBase =
5039 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
5040 SourceLocation(), Param, false,
5041 Loc, ParamType, VK_LValue, nullptr);
5042
5043 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: MemberExprBase));
5044
5045 if (Moving) {
5046 MemberExprBase = CastForMoving(SemaRef, E: MemberExprBase);
5047 }
5048
5049 // Build a reference to this field within the parameter.
5050 CXXScopeSpec SS;
5051 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5052 Sema::LookupMemberName);
5053 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Val: Indirect)
5054 : cast<ValueDecl>(Val: Field), AS_public);
5055 MemberLookup.resolveKind();
5056 ExprResult CtorArg
5057 = SemaRef.BuildMemberReferenceExpr(Base: MemberExprBase,
5058 BaseType: ParamType, OpLoc: Loc,
5059 /*IsArrow=*/false,
5060 SS,
5061 /*TemplateKWLoc=*/SourceLocation(),
5062 /*FirstQualifierInScope=*/nullptr,
5063 R&: MemberLookup,
5064 /*TemplateArgs=*/nullptr,
5065 /*S*/nullptr);
5066 if (CtorArg.isInvalid())
5067 return true;
5068
5069 // C++11 [class.copy]p15:
5070 // - if a member m has rvalue reference type T&&, it is direct-initialized
5071 // with static_cast<T&&>(x.m);
5072 if (RefersToRValueRef(MemRef: CtorArg.get())) {
5073 CtorArg = CastForMoving(SemaRef, E: CtorArg.get());
5074 }
5075
5076 InitializedEntity Entity =
5077 Indirect ? InitializedEntity::InitializeMember(Member: Indirect, Parent: nullptr,
5078 /*Implicit*/ true)
5079 : InitializedEntity::InitializeMember(Member: Field, Parent: nullptr,
5080 /*Implicit*/ true);
5081
5082 // Direct-initialize to use the copy constructor.
5083 InitializationKind InitKind =
5084 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5085
5086 Expr *CtorArgE = CtorArg.getAs<Expr>();
5087 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5088 ExprResult MemberInit =
5089 InitSeq.Perform(S&: SemaRef, Entity, Kind: InitKind, Args: MultiExprArg(&CtorArgE, 1));
5090 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5091 if (MemberInit.isInvalid())
5092 return true;
5093
5094 if (Indirect)
5095 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5096 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5097 else
5098 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5099 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5100 return false;
5101 }
5102
5103 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5104 "Unhandled implicit init kind!");
5105
5106 QualType FieldBaseElementType =
5107 SemaRef.Context.getBaseElementType(Field->getType());
5108
5109 if (FieldBaseElementType->isRecordType()) {
5110 InitializedEntity InitEntity =
5111 Indirect ? InitializedEntity::InitializeMember(Member: Indirect, Parent: nullptr,
5112 /*Implicit*/ true)
5113 : InitializedEntity::InitializeMember(Member: Field, Parent: nullptr,
5114 /*Implicit*/ true);
5115 InitializationKind InitKind =
5116 InitializationKind::CreateDefault(InitLoc: Loc);
5117
5118 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
5119 ExprResult MemberInit =
5120 InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: std::nullopt);
5121
5122 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5123 if (MemberInit.isInvalid())
5124 return true;
5125
5126 if (Indirect)
5127 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5128 Indirect, Loc,
5129 Loc,
5130 MemberInit.get(),
5131 Loc);
5132 else
5133 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5134 Field, Loc, Loc,
5135 MemberInit.get(),
5136 Loc);
5137 return false;
5138 }
5139
5140 if (!Field->getParent()->isUnion()) {
5141 if (FieldBaseElementType->isReferenceType()) {
5142 SemaRef.Diag(Constructor->getLocation(),
5143 diag::err_uninitialized_member_in_ctor)
5144 << (int)Constructor->isImplicit()
5145 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5146 << 0 << Field->getDeclName();
5147 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5148 return true;
5149 }
5150
5151 if (FieldBaseElementType.isConstQualified()) {
5152 SemaRef.Diag(Constructor->getLocation(),
5153 diag::err_uninitialized_member_in_ctor)
5154 << (int)Constructor->isImplicit()
5155 << SemaRef.Context.getTagDeclType(Constructor->getParent())
5156 << 1 << Field->getDeclName();
5157 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5158 return true;
5159 }
5160 }
5161
5162 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5163 // ARC and Weak:
5164 // Default-initialize Objective-C pointers to NULL.
5165 CXXMemberInit
5166 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5167 Loc, Loc,
5168 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5169 Loc);
5170 return false;
5171 }
5172
5173 // Nothing to initialize.
5174 CXXMemberInit = nullptr;
5175 return false;
5176}
5177
5178namespace {
5179struct BaseAndFieldInfo {
5180 Sema &S;
5181 CXXConstructorDecl *Ctor;
5182 bool AnyErrorsInInits;
5183 ImplicitInitializerKind IIK;
5184 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5185 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5186 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5187
5188 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5189 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5190 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5191 if (Ctor->getInheritedConstructor())
5192 IIK = IIK_Inherit;
5193 else if (Generated && Ctor->isCopyConstructor())
5194 IIK = IIK_Copy;
5195 else if (Generated && Ctor->isMoveConstructor())
5196 IIK = IIK_Move;
5197 else
5198 IIK = IIK_Default;
5199 }
5200
5201 bool isImplicitCopyOrMove() const {
5202 switch (IIK) {
5203 case IIK_Copy:
5204 case IIK_Move:
5205 return true;
5206
5207 case IIK_Default:
5208 case IIK_Inherit:
5209 return false;
5210 }
5211
5212 llvm_unreachable("Invalid ImplicitInitializerKind!");
5213 }
5214
5215 bool addFieldInitializer(CXXCtorInitializer *Init) {
5216 AllToInit.push_back(Elt: Init);
5217
5218 // Check whether this initializer makes the field "used".
5219 if (Init->getInit()->HasSideEffects(Ctx: S.Context))
5220 S.UnusedPrivateFields.remove(Init->getAnyMember());
5221
5222 return false;
5223 }
5224
5225 bool isInactiveUnionMember(FieldDecl *Field) {
5226 RecordDecl *Record = Field->getParent();
5227 if (!Record->isUnion())
5228 return false;
5229
5230 if (FieldDecl *Active =
5231 ActiveUnionMember.lookup(Val: Record->getCanonicalDecl()))
5232 return Active != Field->getCanonicalDecl();
5233
5234 // In an implicit copy or move constructor, ignore any in-class initializer.
5235 if (isImplicitCopyOrMove())
5236 return true;
5237
5238 // If there's no explicit initialization, the field is active only if it
5239 // has an in-class initializer...
5240 if (Field->hasInClassInitializer())
5241 return false;
5242 // ... or it's an anonymous struct or union whose class has an in-class
5243 // initializer.
5244 if (!Field->isAnonymousStructOrUnion())
5245 return true;
5246 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5247 return !FieldRD->hasInClassInitializer();
5248 }
5249
5250 /// Determine whether the given field is, or is within, a union member
5251 /// that is inactive (because there was an initializer given for a different
5252 /// member of the union, or because the union was not initialized at all).
5253 bool isWithinInactiveUnionMember(FieldDecl *Field,
5254 IndirectFieldDecl *Indirect) {
5255 if (!Indirect)
5256 return isInactiveUnionMember(Field);
5257
5258 for (auto *C : Indirect->chain()) {
5259 FieldDecl *Field = dyn_cast<FieldDecl>(Val: C);
5260 if (Field && isInactiveUnionMember(Field))
5261 return true;
5262 }
5263 return false;
5264 }
5265};
5266}
5267
5268/// Determine whether the given type is an incomplete or zero-lenfgth
5269/// array type.
5270static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5271 if (T->isIncompleteArrayType())
5272 return true;
5273
5274 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5275 if (!ArrayT->getSize())
5276 return true;
5277
5278 T = ArrayT->getElementType();
5279 }
5280
5281 return false;
5282}
5283
5284static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5285 FieldDecl *Field,
5286 IndirectFieldDecl *Indirect = nullptr) {
5287 if (Field->isInvalidDecl())
5288 return false;
5289
5290 // Overwhelmingly common case: we have a direct initializer for this field.
5291 if (CXXCtorInitializer *Init =
5292 Info.AllBaseFields.lookup(Val: Field->getCanonicalDecl()))
5293 return Info.addFieldInitializer(Init);
5294
5295 // C++11 [class.base.init]p8:
5296 // if the entity is a non-static data member that has a
5297 // brace-or-equal-initializer and either
5298 // -- the constructor's class is a union and no other variant member of that
5299 // union is designated by a mem-initializer-id or
5300 // -- the constructor's class is not a union, and, if the entity is a member
5301 // of an anonymous union, no other member of that union is designated by
5302 // a mem-initializer-id,
5303 // the entity is initialized as specified in [dcl.init].
5304 //
5305 // We also apply the same rules to handle anonymous structs within anonymous
5306 // unions.
5307 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5308 return false;
5309
5310 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5311 ExprResult DIE =
5312 SemaRef.BuildCXXDefaultInitExpr(Loc: Info.Ctor->getLocation(), Field);
5313 if (DIE.isInvalid())
5314 return true;
5315
5316 auto Entity = InitializedEntity::InitializeMember(Member: Field, Parent: nullptr, Implicit: true);
5317 SemaRef.checkInitializerLifetime(Entity, Init: DIE.get());
5318
5319 CXXCtorInitializer *Init;
5320 if (Indirect)
5321 Init = new (SemaRef.Context)
5322 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5323 SourceLocation(), DIE.get(), SourceLocation());
5324 else
5325 Init = new (SemaRef.Context)
5326 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5327 SourceLocation(), DIE.get(), SourceLocation());
5328 return Info.addFieldInitializer(Init);
5329 }
5330
5331 // Don't initialize incomplete or zero-length arrays.
5332 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5333 return false;
5334
5335 // Don't try to build an implicit initializer if there were semantic
5336 // errors in any of the initializers (and therefore we might be
5337 // missing some that the user actually wrote).
5338 if (Info.AnyErrorsInInits)
5339 return false;
5340
5341 CXXCtorInitializer *Init = nullptr;
5342 if (BuildImplicitMemberInitializer(SemaRef&: Info.S, Constructor: Info.Ctor, ImplicitInitKind: Info.IIK, Field,
5343 Indirect, CXXMemberInit&: Init))
5344 return true;
5345
5346 if (!Init)
5347 return false;
5348
5349 return Info.addFieldInitializer(Init);
5350}
5351
5352bool
5353Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5354 CXXCtorInitializer *Initializer) {
5355 assert(Initializer->isDelegatingInitializer());
5356 Constructor->setNumCtorInitializers(1);
5357 CXXCtorInitializer **initializer =
5358 new (Context) CXXCtorInitializer*[1];
5359 memcpy(dest: initializer, src: &Initializer, n: sizeof (CXXCtorInitializer*));
5360 Constructor->setCtorInitializers(initializer);
5361
5362 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: Constructor->getParent())) {
5363 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5364 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5365 }
5366
5367 DelegatingCtorDecls.push_back(LocalValue: Constructor);
5368
5369 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5370
5371 return false;
5372}
5373
5374bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5375 ArrayRef<CXXCtorInitializer *> Initializers) {
5376 if (Constructor->isDependentContext()) {
5377 // Just store the initializers as written, they will be checked during
5378 // instantiation.
5379 if (!Initializers.empty()) {
5380 Constructor->setNumCtorInitializers(Initializers.size());
5381 CXXCtorInitializer **baseOrMemberInitializers =
5382 new (Context) CXXCtorInitializer*[Initializers.size()];
5383 memcpy(dest: baseOrMemberInitializers, src: Initializers.data(),
5384 n: Initializers.size() * sizeof(CXXCtorInitializer*));
5385 Constructor->setCtorInitializers(baseOrMemberInitializers);
5386 }
5387
5388 // Let template instantiation know whether we had errors.
5389 if (AnyErrors)
5390 Constructor->setInvalidDecl();
5391
5392 return false;
5393 }
5394
5395 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5396
5397 // We need to build the initializer AST according to order of construction
5398 // and not what user specified in the Initializers list.
5399 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5400 if (!ClassDecl)
5401 return true;
5402
5403 bool HadError = false;
5404
5405 for (unsigned i = 0; i < Initializers.size(); i++) {
5406 CXXCtorInitializer *Member = Initializers[i];
5407
5408 if (Member->isBaseInitializer())
5409 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5410 else {
5411 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5412
5413 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5414 for (auto *C : F->chain()) {
5415 FieldDecl *FD = dyn_cast<FieldDecl>(Val: C);
5416 if (FD && FD->getParent()->isUnion())
5417 Info.ActiveUnionMember.insert(std::make_pair(
5418 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5419 }
5420 } else if (FieldDecl *FD = Member->getMember()) {
5421 if (FD->getParent()->isUnion())
5422 Info.ActiveUnionMember.insert(std::make_pair(
5423 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5424 }
5425 }
5426 }
5427
5428 // Keep track of the direct virtual bases.
5429 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5430 for (auto &I : ClassDecl->bases()) {
5431 if (I.isVirtual())
5432 DirectVBases.insert(&I);
5433 }
5434
5435 // Push virtual bases before others.
5436 for (auto &VBase : ClassDecl->vbases()) {
5437 if (CXXCtorInitializer *Value
5438 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5439 // [class.base.init]p7, per DR257:
5440 // A mem-initializer where the mem-initializer-id names a virtual base
5441 // class is ignored during execution of a constructor of any class that
5442 // is not the most derived class.
5443 if (ClassDecl->isAbstract()) {
5444 // FIXME: Provide a fixit to remove the base specifier. This requires
5445 // tracking the location of the associated comma for a base specifier.
5446 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5447 << VBase.getType() << ClassDecl;
5448 DiagnoseAbstractType(ClassDecl);
5449 }
5450
5451 Info.AllToInit.push_back(Value);
5452 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5453 // [class.base.init]p8, per DR257:
5454 // If a given [...] base class is not named by a mem-initializer-id
5455 // [...] and the entity is not a virtual base class of an abstract
5456 // class, then [...] the entity is default-initialized.
5457 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5458 CXXCtorInitializer *CXXBaseInit;
5459 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5460 &VBase, IsInheritedVirtualBase,
5461 CXXBaseInit)) {
5462 HadError = true;
5463 continue;
5464 }
5465
5466 Info.AllToInit.push_back(CXXBaseInit);
5467 }
5468 }
5469
5470 // Non-virtual bases.
5471 for (auto &Base : ClassDecl->bases()) {
5472 // Virtuals are in the virtual base list and already constructed.
5473 if (Base.isVirtual())
5474 continue;
5475
5476 if (CXXCtorInitializer *Value
5477 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5478 Info.AllToInit.push_back(Value);
5479 } else if (!AnyErrors) {
5480 CXXCtorInitializer *CXXBaseInit;
5481 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5482 &Base, /*IsInheritedVirtualBase=*/false,
5483 CXXBaseInit)) {
5484 HadError = true;
5485 continue;
5486 }
5487
5488 Info.AllToInit.push_back(CXXBaseInit);
5489 }
5490 }
5491
5492 // Fields.
5493 for (auto *Mem : ClassDecl->decls()) {
5494 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5495 // C++ [class.bit]p2:
5496 // A declaration for a bit-field that omits the identifier declares an
5497 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5498 // initialized.
5499 if (F->isUnnamedBitfield())
5500 continue;
5501
5502 // If we're not generating the implicit copy/move constructor, then we'll
5503 // handle anonymous struct/union fields based on their individual
5504 // indirect fields.
5505 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5506 continue;
5507
5508 if (CollectFieldInitializer(*this, Info, F))
5509 HadError = true;
5510 continue;
5511 }
5512
5513 // Beyond this point, we only consider default initialization.
5514 if (Info.isImplicitCopyOrMove())
5515 continue;
5516
5517 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5518 if (F->getType()->isIncompleteArrayType()) {
5519 assert(ClassDecl->hasFlexibleArrayMember() &&
5520 "Incomplete array type is not valid");
5521 continue;
5522 }
5523
5524 // Initialize each field of an anonymous struct individually.
5525 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5526 HadError = true;
5527
5528 continue;
5529 }
5530 }
5531
5532 unsigned NumInitializers = Info.AllToInit.size();
5533 if (NumInitializers > 0) {
5534 Constructor->setNumCtorInitializers(NumInitializers);
5535 CXXCtorInitializer **baseOrMemberInitializers =
5536 new (Context) CXXCtorInitializer*[NumInitializers];
5537 memcpy(dest: baseOrMemberInitializers, src: Info.AllToInit.data(),
5538 n: NumInitializers * sizeof(CXXCtorInitializer*));
5539 Constructor->setCtorInitializers(baseOrMemberInitializers);
5540
5541 // Constructors implicitly reference the base and member
5542 // destructors.
5543 MarkBaseAndMemberDestructorsReferenced(Loc: Constructor->getLocation(),
5544 Record: Constructor->getParent());
5545 }
5546
5547 return HadError;
5548}
5549
5550static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5551 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5552 const RecordDecl *RD = RT->getDecl();
5553 if (RD->isAnonymousStructOrUnion()) {
5554 for (auto *Field : RD->fields())
5555 PopulateKeysForFields(Field, IdealInits);
5556 return;
5557 }
5558 }
5559 IdealInits.push_back(Elt: Field->getCanonicalDecl());
5560}
5561
5562static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5563 return Context.getCanonicalType(T: BaseType).getTypePtr();
5564}
5565
5566static const void *GetKeyForMember(ASTContext &Context,
5567 CXXCtorInitializer *Member) {
5568 if (!Member->isAnyMemberInitializer())
5569 return GetKeyForBase(Context, BaseType: QualType(Member->getBaseClass(), 0));
5570
5571 return Member->getAnyMember()->getCanonicalDecl();
5572}
5573
5574static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5575 const CXXCtorInitializer *Previous,
5576 const CXXCtorInitializer *Current) {
5577 if (Previous->isAnyMemberInitializer())
5578 Diag << 0 << Previous->getAnyMember();
5579 else
5580 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5581
5582 if (Current->isAnyMemberInitializer())
5583 Diag << 0 << Current->getAnyMember();
5584 else
5585 Diag << 1 << Current->getTypeSourceInfo()->getType();
5586}
5587
5588static void DiagnoseBaseOrMemInitializerOrder(
5589 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5590 ArrayRef<CXXCtorInitializer *> Inits) {
5591 if (Constructor->getDeclContext()->isDependentContext())
5592 return;
5593
5594 // Don't check initializers order unless the warning is enabled at the
5595 // location of at least one initializer.
5596 bool ShouldCheckOrder = false;
5597 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5598 CXXCtorInitializer *Init = Inits[InitIndex];
5599 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5600 Init->getSourceLocation())) {
5601 ShouldCheckOrder = true;
5602 break;
5603 }
5604 }
5605 if (!ShouldCheckOrder)
5606 return;
5607
5608 // Build the list of bases and members in the order that they'll
5609 // actually be initialized. The explicit initializers should be in
5610 // this same order but may be missing things.
5611 SmallVector<const void*, 32> IdealInitKeys;
5612
5613 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5614
5615 // 1. Virtual bases.
5616 for (const auto &VBase : ClassDecl->vbases())
5617 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5618
5619 // 2. Non-virtual bases.
5620 for (const auto &Base : ClassDecl->bases()) {
5621 if (Base.isVirtual())
5622 continue;
5623 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5624 }
5625
5626 // 3. Direct fields.
5627 for (auto *Field : ClassDecl->fields()) {
5628 if (Field->isUnnamedBitfield())
5629 continue;
5630
5631 PopulateKeysForFields(Field, IdealInitKeys);
5632 }
5633
5634 unsigned NumIdealInits = IdealInitKeys.size();
5635 unsigned IdealIndex = 0;
5636
5637 // Track initializers that are in an incorrect order for either a warning or
5638 // note if multiple ones occur.
5639 SmallVector<unsigned> WarnIndexes;
5640 // Correlates the index of an initializer in the init-list to the index of
5641 // the field/base in the class.
5642 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5643
5644 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5645 const void *InitKey = GetKeyForMember(Context&: SemaRef.Context, Member: Inits[InitIndex]);
5646
5647 // Scan forward to try to find this initializer in the idealized
5648 // initializers list.
5649 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5650 if (InitKey == IdealInitKeys[IdealIndex])
5651 break;
5652
5653 // If we didn't find this initializer, it must be because we
5654 // scanned past it on a previous iteration. That can only
5655 // happen if we're out of order; emit a warning.
5656 if (IdealIndex == NumIdealInits && InitIndex) {
5657 WarnIndexes.push_back(Elt: InitIndex);
5658
5659 // Move back to the initializer's location in the ideal list.
5660 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5661 if (InitKey == IdealInitKeys[IdealIndex])
5662 break;
5663
5664 assert(IdealIndex < NumIdealInits &&
5665 "initializer not found in initializer list");
5666 }
5667 CorrelatedInitOrder.emplace_back(Args&: IdealIndex, Args&: InitIndex);
5668 }
5669
5670 if (WarnIndexes.empty())
5671 return;
5672
5673 // Sort based on the ideal order, first in the pair.
5674 llvm::sort(C&: CorrelatedInitOrder, Comp: llvm::less_first());
5675
5676 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5677 // emit the diagnostic before we can try adding notes.
5678 {
5679 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5680 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5681 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5682 : diag::warn_some_initializers_out_of_order);
5683
5684 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5685 if (CorrelatedInitOrder[I].second == I)
5686 continue;
5687 // Ideally we would be using InsertFromRange here, but clang doesn't
5688 // appear to handle InsertFromRange correctly when the source range is
5689 // modified by another fix-it.
5690 D << FixItHint::CreateReplacement(
5691 RemoveRange: Inits[I]->getSourceRange(),
5692 Code: Lexer::getSourceText(
5693 Range: CharSourceRange::getTokenRange(
5694 R: Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5695 SM: SemaRef.getSourceManager(), LangOpts: SemaRef.getLangOpts()));
5696 }
5697
5698 // If there is only 1 item out of order, the warning expects the name and
5699 // type of each being added to it.
5700 if (WarnIndexes.size() == 1) {
5701 AddInitializerToDiag(Diag: D, Previous: Inits[WarnIndexes.front() - 1],
5702 Current: Inits[WarnIndexes.front()]);
5703 return;
5704 }
5705 }
5706 // More than 1 item to warn, create notes letting the user know which ones
5707 // are bad.
5708 for (unsigned WarnIndex : WarnIndexes) {
5709 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5710 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5711 diag::note_initializer_out_of_order);
5712 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5713 D << PrevInit->getSourceRange();
5714 }
5715}
5716
5717namespace {
5718bool CheckRedundantInit(Sema &S,
5719 CXXCtorInitializer *Init,
5720 CXXCtorInitializer *&PrevInit) {
5721 if (!PrevInit) {
5722 PrevInit = Init;
5723 return false;
5724 }
5725
5726 if (FieldDecl *Field = Init->getAnyMember())
5727 S.Diag(Init->getSourceLocation(),
5728 diag::err_multiple_mem_initialization)
5729 << Field->getDeclName()
5730 << Init->getSourceRange();
5731 else {
5732 const Type *BaseClass = Init->getBaseClass();
5733 assert(BaseClass && "neither field nor base");
5734 S.Diag(Init->getSourceLocation(),
5735 diag::err_multiple_base_initialization)
5736 << QualType(BaseClass, 0)
5737 << Init->getSourceRange();
5738 }
5739 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5740 << 0 << PrevInit->getSourceRange();
5741
5742 return true;
5743}
5744
5745typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5746typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5747
5748bool CheckRedundantUnionInit(Sema &S,
5749 CXXCtorInitializer *Init,
5750 RedundantUnionMap &Unions) {
5751 FieldDecl *Field = Init->getAnyMember();
5752 RecordDecl *Parent = Field->getParent();
5753 NamedDecl *Child = Field;
5754
5755 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5756 if (Parent->isUnion()) {
5757 UnionEntry &En = Unions[Parent];
5758 if (En.first && En.first != Child) {
5759 S.Diag(Init->getSourceLocation(),
5760 diag::err_multiple_mem_union_initialization)
5761 << Field->getDeclName()
5762 << Init->getSourceRange();
5763 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5764 << 0 << En.second->getSourceRange();
5765 return true;
5766 }
5767 if (!En.first) {
5768 En.first = Child;
5769 En.second = Init;
5770 }
5771 if (!Parent->isAnonymousStructOrUnion())
5772 return false;
5773 }
5774
5775 Child = Parent;
5776 Parent = cast<RecordDecl>(Parent->getDeclContext());
5777 }
5778
5779 return false;
5780}
5781} // namespace
5782
5783/// ActOnMemInitializers - Handle the member initializers for a constructor.
5784void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5785 SourceLocation ColonLoc,
5786 ArrayRef<CXXCtorInitializer*> MemInits,
5787 bool AnyErrors) {
5788 if (!ConstructorDecl)
5789 return;
5790
5791 AdjustDeclIfTemplate(Decl&: ConstructorDecl);
5792
5793 CXXConstructorDecl *Constructor
5794 = dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl);
5795
5796 if (!Constructor) {
5797 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5798 return;
5799 }
5800
5801 // Mapping for the duplicate initializers check.
5802 // For member initializers, this is keyed with a FieldDecl*.
5803 // For base initializers, this is keyed with a Type*.
5804 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5805
5806 // Mapping for the inconsistent anonymous-union initializers check.
5807 RedundantUnionMap MemberUnions;
5808
5809 bool HadError = false;
5810 for (unsigned i = 0; i < MemInits.size(); i++) {
5811 CXXCtorInitializer *Init = MemInits[i];
5812
5813 // Set the source order index.
5814 Init->setSourceOrder(i);
5815
5816 if (Init->isAnyMemberInitializer()) {
5817 const void *Key = GetKeyForMember(Context, Member: Init);
5818 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]) ||
5819 CheckRedundantUnionInit(S&: *this, Init, Unions&: MemberUnions))
5820 HadError = true;
5821 } else if (Init->isBaseInitializer()) {
5822 const void *Key = GetKeyForMember(Context, Member: Init);
5823 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]))
5824 HadError = true;
5825 } else {
5826 assert(Init->isDelegatingInitializer());
5827 // This must be the only initializer
5828 if (MemInits.size() != 1) {
5829 Diag(Init->getSourceLocation(),
5830 diag::err_delegating_initializer_alone)
5831 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5832 // We will treat this as being the only initializer.
5833 }
5834 SetDelegatingInitializer(Constructor, Initializer: MemInits[i]);
5835 // Return immediately as the initializer is set.
5836 return;
5837 }
5838 }
5839
5840 if (HadError)
5841 return;
5842
5843 DiagnoseBaseOrMemInitializerOrder(SemaRef&: *this, Constructor, Inits: MemInits);
5844
5845 SetCtorInitializers(Constructor, AnyErrors, Initializers: MemInits);
5846
5847 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5848}
5849
5850void
5851Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5852 CXXRecordDecl *ClassDecl) {
5853 // Ignore dependent contexts. Also ignore unions, since their members never
5854 // have destructors implicitly called.
5855 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5856 return;
5857
5858 // FIXME: all the access-control diagnostics are positioned on the
5859 // field/base declaration. That's probably good; that said, the
5860 // user might reasonably want to know why the destructor is being
5861 // emitted, and we currently don't say.
5862
5863 // Non-static data members.
5864 for (auto *Field : ClassDecl->fields()) {
5865 if (Field->isInvalidDecl())
5866 continue;
5867
5868 // Don't destroy incomplete or zero-length arrays.
5869 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5870 continue;
5871
5872 QualType FieldType = Context.getBaseElementType(Field->getType());
5873
5874 const RecordType* RT = FieldType->getAs<RecordType>();
5875 if (!RT)
5876 continue;
5877
5878 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5879 if (FieldClassDecl->isInvalidDecl())
5880 continue;
5881 if (FieldClassDecl->hasIrrelevantDestructor())
5882 continue;
5883 // The destructor for an implicit anonymous union member is never invoked.
5884 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5885 continue;
5886
5887 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5888 // Dtor might still be missing, e.g because it's invalid.
5889 if (!Dtor)
5890 continue;
5891 CheckDestructorAccess(Field->getLocation(), Dtor,
5892 PDiag(diag::err_access_dtor_field)
5893 << Field->getDeclName()
5894 << FieldType);
5895
5896 MarkFunctionReferenced(Location, Dtor);
5897 DiagnoseUseOfDecl(Dtor, Location);
5898 }
5899
5900 // We only potentially invoke the destructors of potentially constructed
5901 // subobjects.
5902 bool VisitVirtualBases = !ClassDecl->isAbstract();
5903
5904 // If the destructor exists and has already been marked used in the MS ABI,
5905 // then virtual base destructors have already been checked and marked used.
5906 // Skip checking them again to avoid duplicate diagnostics.
5907 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5908 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5909 if (Dtor && Dtor->isUsed())
5910 VisitVirtualBases = false;
5911 }
5912
5913 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5914
5915 // Bases.
5916 for (const auto &Base : ClassDecl->bases()) {
5917 const RecordType *RT = Base.getType()->getAs<RecordType>();
5918 if (!RT)
5919 continue;
5920
5921 // Remember direct virtual bases.
5922 if (Base.isVirtual()) {
5923 if (!VisitVirtualBases)
5924 continue;
5925 DirectVirtualBases.insert(Ptr: RT);
5926 }
5927
5928 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(Val: RT->getDecl());
5929 // If our base class is invalid, we probably can't get its dtor anyway.
5930 if (BaseClassDecl->isInvalidDecl())
5931 continue;
5932 if (BaseClassDecl->hasIrrelevantDestructor())
5933 continue;
5934
5935 CXXDestructorDecl *Dtor = LookupDestructor(Class: BaseClassDecl);
5936 // Dtor might still be missing, e.g because it's invalid.
5937 if (!Dtor)
5938 continue;
5939
5940 // FIXME: caret should be on the start of the class name
5941 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5942 PDiag(diag::err_access_dtor_base)
5943 << Base.getType() << Base.getSourceRange(),
5944 Context.getTypeDeclType(ClassDecl));
5945
5946 MarkFunctionReferenced(Location, Dtor);
5947 DiagnoseUseOfDecl(Dtor, Location);
5948 }
5949
5950 if (VisitVirtualBases)
5951 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5952 DirectVirtualBases: &DirectVirtualBases);
5953}
5954
5955void Sema::MarkVirtualBaseDestructorsReferenced(
5956 SourceLocation Location, CXXRecordDecl *ClassDecl,
5957 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5958 // Virtual bases.
5959 for (const auto &VBase : ClassDecl->vbases()) {
5960 // Bases are always records in a well-formed non-dependent class.
5961 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5962
5963 // Ignore already visited direct virtual bases.
5964 if (DirectVirtualBases && DirectVirtualBases->count(Ptr: RT))
5965 continue;
5966
5967 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(Val: RT->getDecl());
5968 // If our base class is invalid, we probably can't get its dtor anyway.
5969 if (BaseClassDecl->isInvalidDecl())
5970 continue;
5971 if (BaseClassDecl->hasIrrelevantDestructor())
5972 continue;
5973
5974 CXXDestructorDecl *Dtor = LookupDestructor(Class: BaseClassDecl);
5975 // Dtor might still be missing, e.g because it's invalid.
5976 if (!Dtor)
5977 continue;
5978 if (CheckDestructorAccess(
5979 ClassDecl->getLocation(), Dtor,
5980 PDiag(diag::err_access_dtor_vbase)
5981 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5982 Context.getTypeDeclType(ClassDecl)) ==
5983 AR_accessible) {
5984 CheckDerivedToBaseConversion(
5985 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5986 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5987 SourceRange(), DeclarationName(), nullptr);
5988 }
5989
5990 MarkFunctionReferenced(Location, Dtor);
5991 DiagnoseUseOfDecl(Dtor, Location);
5992 }
5993}
5994
5995void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5996 if (!CDtorDecl)
5997 return;
5998
5999 if (CXXConstructorDecl *Constructor
6000 = dyn_cast<CXXConstructorDecl>(Val: CDtorDecl)) {
6001 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6002 !ClassDecl || ClassDecl->isInvalidDecl()) {
6003 return;
6004 }
6005 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6006 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
6007 }
6008}
6009
6010bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
6011 if (!getLangOpts().CPlusPlus)
6012 return false;
6013
6014 const auto *RD = Context.getBaseElementType(QT: T)->getAsCXXRecordDecl();
6015 if (!RD)
6016 return false;
6017
6018 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6019 // class template specialization here, but doing so breaks a lot of code.
6020
6021 // We can't answer whether something is abstract until it has a
6022 // definition. If it's currently being defined, we'll walk back
6023 // over all the declarations when we have a full definition.
6024 const CXXRecordDecl *Def = RD->getDefinition();
6025 if (!Def || Def->isBeingDefined())
6026 return false;
6027
6028 return RD->isAbstract();
6029}
6030
6031bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6032 TypeDiagnoser &Diagnoser) {
6033 if (!isAbstractType(Loc, T))
6034 return false;
6035
6036 T = Context.getBaseElementType(QT: T);
6037 Diagnoser.diagnose(S&: *this, Loc, T);
6038 DiagnoseAbstractType(RD: T->getAsCXXRecordDecl());
6039 return true;
6040}
6041
6042void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6043 // Check if we've already emitted the list of pure virtual functions
6044 // for this class.
6045 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(Ptr: RD))
6046 return;
6047
6048 // If the diagnostic is suppressed, don't emit the notes. We're only
6049 // going to emit them once, so try to attach them to a diagnostic we're
6050 // actually going to show.
6051 if (Diags.isLastDiagnosticIgnored())
6052 return;
6053
6054 CXXFinalOverriderMap FinalOverriders;
6055 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
6056
6057 // Keep a set of seen pure methods so we won't diagnose the same method
6058 // more than once.
6059 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6060
6061 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
6062 MEnd = FinalOverriders.end();
6063 M != MEnd;
6064 ++M) {
6065 for (OverridingMethods::iterator SO = M->second.begin(),
6066 SOEnd = M->second.end();
6067 SO != SOEnd; ++SO) {
6068 // C++ [class.abstract]p4:
6069 // A class is abstract if it contains or inherits at least one
6070 // pure virtual function for which the final overrider is pure
6071 // virtual.
6072
6073 //
6074 if (SO->second.size() != 1)
6075 continue;
6076
6077 if (!SO->second.front().Method->isPureVirtual())
6078 continue;
6079
6080 if (!SeenPureMethods.insert(Ptr: SO->second.front().Method).second)
6081 continue;
6082
6083 Diag(SO->second.front().Method->getLocation(),
6084 diag::note_pure_virtual_function)
6085 << SO->second.front().Method->getDeclName() << RD->getDeclName();
6086 }
6087 }
6088
6089 if (!PureVirtualClassDiagSet)
6090 PureVirtualClassDiagSet.reset(p: new RecordDeclSetTy);
6091 PureVirtualClassDiagSet->insert(Ptr: RD);
6092}
6093
6094namespace {
6095struct AbstractUsageInfo {
6096 Sema &S;
6097 CXXRecordDecl *Record;
6098 CanQualType AbstractType;
6099 bool Invalid;
6100
6101 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6102 : S(S), Record(Record),
6103 AbstractType(S.Context.getCanonicalType(
6104 S.Context.getTypeDeclType(Record))),
6105 Invalid(false) {}
6106
6107 void DiagnoseAbstractType() {
6108 if (Invalid) return;
6109 S.DiagnoseAbstractType(RD: Record);
6110 Invalid = true;
6111 }
6112
6113 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6114};
6115
6116struct CheckAbstractUsage {
6117 AbstractUsageInfo &Info;
6118 const NamedDecl *Ctx;
6119
6120 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6121 : Info(Info), Ctx(Ctx) {}
6122
6123 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6124 switch (TL.getTypeLocClass()) {
6125#define ABSTRACT_TYPELOC(CLASS, PARENT)
6126#define TYPELOC(CLASS, PARENT) \
6127 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6128#include "clang/AST/TypeLocNodes.def"
6129 }
6130 }
6131
6132 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6133 Visit(TL: TL.getReturnLoc(), Sel: Sema::AbstractReturnType);
6134 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6135 if (!TL.getParam(I))
6136 continue;
6137
6138 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6139 if (TSI) Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractParamType);
6140 }
6141 }
6142
6143 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6144 Visit(TL: TL.getElementLoc(), Sel: Sema::AbstractArrayType);
6145 }
6146
6147 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6148 // Visit the type parameters from a permissive context.
6149 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6150 TemplateArgumentLoc TAL = TL.getArgLoc(i: I);
6151 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6152 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6153 Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6154 // TODO: other template argument types?
6155 }
6156 }
6157
6158 // Visit pointee types from a permissive context.
6159#define CheckPolymorphic(Type) \
6160 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6161 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6162 }
6163 CheckPolymorphic(PointerTypeLoc)
6164 CheckPolymorphic(ReferenceTypeLoc)
6165 CheckPolymorphic(MemberPointerTypeLoc)
6166 CheckPolymorphic(BlockPointerTypeLoc)
6167 CheckPolymorphic(AtomicTypeLoc)
6168
6169 /// Handle all the types we haven't given a more specific
6170 /// implementation for above.
6171 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6172 // Every other kind of type that we haven't called out already
6173 // that has an inner type is either (1) sugar or (2) contains that
6174 // inner type in some way as a subobject.
6175 if (TypeLoc Next = TL.getNextTypeLoc())
6176 return Visit(TL: Next, Sel);
6177
6178 // If there's no inner type and we're in a permissive context,
6179 // don't diagnose.
6180 if (Sel == Sema::AbstractNone) return;
6181
6182 // Check whether the type matches the abstract type.
6183 QualType T = TL.getType();
6184 if (T->isArrayType()) {
6185 Sel = Sema::AbstractArrayType;
6186 T = Info.S.Context.getBaseElementType(QT: T);
6187 }
6188 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
6189 if (CT != Info.AbstractType) return;
6190
6191 // It matched; do some magic.
6192 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6193 if (Sel == Sema::AbstractArrayType) {
6194 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6195 << T << TL.getSourceRange();
6196 } else {
6197 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6198 << Sel << T << TL.getSourceRange();
6199 }
6200 Info.DiagnoseAbstractType();
6201 }
6202};
6203
6204void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6205 Sema::AbstractDiagSelID Sel) {
6206 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6207}
6208
6209}
6210
6211/// Check for invalid uses of an abstract type in a function declaration.
6212static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6213 FunctionDecl *FD) {
6214 // Only definitions are required to refer to complete and
6215 // non-abstract types.
6216 if (!FD->doesThisDeclarationHaveABody())
6217 return;
6218
6219 // For safety's sake, just ignore it if we don't have type source
6220 // information. This should never happen for non-implicit methods,
6221 // but...
6222 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6223 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6224}
6225
6226/// Check for invalid uses of an abstract type in a variable0 declaration.
6227static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6228 VarDecl *VD) {
6229 // No need to do the check on definitions, which require that
6230 // the type is complete.
6231 if (VD->isThisDeclarationADefinition())
6232 return;
6233
6234 Info.CheckType(D: VD, TL: VD->getTypeSourceInfo()->getTypeLoc(),
6235 Sel: Sema::AbstractVariableType);
6236}
6237
6238/// Check for invalid uses of an abstract type within a class definition.
6239static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6240 CXXRecordDecl *RD) {
6241 for (auto *D : RD->decls()) {
6242 if (D->isImplicit()) continue;
6243
6244 // Step through friends to the befriended declaration.
6245 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6246 D = FD->getFriendDecl();
6247 if (!D) continue;
6248 }
6249
6250 // Functions and function templates.
6251 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6252 CheckAbstractClassUsage(Info, FD);
6253 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6254 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6255
6256 // Fields and static variables.
6257 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6258 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6259 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6260 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6261 CheckAbstractClassUsage(Info, VD);
6262 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6263 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6264
6265 // Nested classes and class templates.
6266 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6267 CheckAbstractClassUsage(Info, RD);
6268 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6269 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6270 }
6271 }
6272}
6273
6274static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6275 Attr *ClassAttr = getDLLAttr(Class);
6276 if (!ClassAttr)
6277 return;
6278
6279 assert(ClassAttr->getKind() == attr::DLLExport);
6280
6281 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6282
6283 if (TSK == TSK_ExplicitInstantiationDeclaration)
6284 // Don't go any further if this is just an explicit instantiation
6285 // declaration.
6286 return;
6287
6288 // Add a context note to explain how we got to any diagnostics produced below.
6289 struct MarkingClassDllexported {
6290 Sema &S;
6291 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6292 SourceLocation AttrLoc)
6293 : S(S) {
6294 Sema::CodeSynthesisContext Ctx;
6295 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6296 Ctx.PointOfInstantiation = AttrLoc;
6297 Ctx.Entity = Class;
6298 S.pushCodeSynthesisContext(Ctx);
6299 }
6300 ~MarkingClassDllexported() {
6301 S.popCodeSynthesisContext();
6302 }
6303 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6304
6305 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6306 S.MarkVTableUsed(Loc: Class->getLocation(), Class, DefinitionRequired: true);
6307
6308 for (Decl *Member : Class->decls()) {
6309 // Skip members that were not marked exported.
6310 if (!Member->hasAttr<DLLExportAttr>())
6311 continue;
6312
6313 // Defined static variables that are members of an exported base
6314 // class must be marked export too.
6315 auto *VD = dyn_cast<VarDecl>(Member);
6316 if (VD && VD->getStorageClass() == SC_Static &&
6317 TSK == TSK_ImplicitInstantiation)
6318 S.MarkVariableReferenced(VD->getLocation(), VD);
6319
6320 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6321 if (!MD)
6322 continue;
6323
6324 if (MD->isUserProvided()) {
6325 // Instantiate non-default class member functions ...
6326
6327 // .. except for certain kinds of template specializations.
6328 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6329 continue;
6330
6331 // If this is an MS ABI dllexport default constructor, instantiate any
6332 // default arguments.
6333 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6334 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6335 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6336 S.InstantiateDefaultCtorDefaultArgs(CD);
6337 }
6338 }
6339
6340 S.MarkFunctionReferenced(Class->getLocation(), MD);
6341
6342 // The function will be passed to the consumer when its definition is
6343 // encountered.
6344 } else if (MD->isExplicitlyDefaulted()) {
6345 // Synthesize and instantiate explicitly defaulted methods.
6346 S.MarkFunctionReferenced(Class->getLocation(), MD);
6347
6348 if (TSK != TSK_ExplicitInstantiationDefinition) {
6349 // Except for explicit instantiation defs, we will not see the
6350 // definition again later, so pass it to the consumer now.
6351 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6352 }
6353 } else if (!MD->isTrivial() ||
6354 MD->isCopyAssignmentOperator() ||
6355 MD->isMoveAssignmentOperator()) {
6356 // Synthesize and instantiate non-trivial implicit methods, and the copy
6357 // and move assignment operators. The latter are exported even if they
6358 // are trivial, because the address of an operator can be taken and
6359 // should compare equal across libraries.
6360 S.MarkFunctionReferenced(Class->getLocation(), MD);
6361
6362 // There is no later point when we will see the definition of this
6363 // function, so pass it to the consumer now.
6364 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6365 }
6366 }
6367}
6368
6369static void checkForMultipleExportedDefaultConstructors(Sema &S,
6370 CXXRecordDecl *Class) {
6371 // Only the MS ABI has default constructor closures, so we don't need to do
6372 // this semantic checking anywhere else.
6373 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6374 return;
6375
6376 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6377 for (Decl *Member : Class->decls()) {
6378 // Look for exported default constructors.
6379 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6380 if (!CD || !CD->isDefaultConstructor())
6381 continue;
6382 auto *Attr = CD->getAttr<DLLExportAttr>();
6383 if (!Attr)
6384 continue;
6385
6386 // If the class is non-dependent, mark the default arguments as ODR-used so
6387 // that we can properly codegen the constructor closure.
6388 if (!Class->isDependentContext()) {
6389 for (ParmVarDecl *PD : CD->parameters()) {
6390 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6391 S.DiscardCleanupsInEvaluationContext();
6392 }
6393 }
6394
6395 if (LastExportedDefaultCtor) {
6396 S.Diag(LastExportedDefaultCtor->getLocation(),
6397 diag::err_attribute_dll_ambiguous_default_ctor)
6398 << Class;
6399 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6400 << CD->getDeclName();
6401 return;
6402 }
6403 LastExportedDefaultCtor = CD;
6404 }
6405}
6406
6407static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6408 CXXRecordDecl *Class) {
6409 bool ErrorReported = false;
6410 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6411 ClassTemplateDecl *TD) {
6412 if (ErrorReported)
6413 return;
6414 S.Diag(TD->getLocation(),
6415 diag::err_cuda_device_builtin_surftex_cls_template)
6416 << /*surface*/ 0 << TD;
6417 ErrorReported = true;
6418 };
6419
6420 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6421 if (!TD) {
6422 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6423 if (!SD) {
6424 S.Diag(Class->getLocation(),
6425 diag::err_cuda_device_builtin_surftex_ref_decl)
6426 << /*surface*/ 0 << Class;
6427 S.Diag(Class->getLocation(),
6428 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6429 << Class;
6430 return;
6431 }
6432 TD = SD->getSpecializedTemplate();
6433 }
6434
6435 TemplateParameterList *Params = TD->getTemplateParameters();
6436 unsigned N = Params->size();
6437
6438 if (N != 2) {
6439 reportIllegalClassTemplate(S, TD);
6440 S.Diag(TD->getLocation(),
6441 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6442 << TD << 2;
6443 }
6444 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6445 reportIllegalClassTemplate(S, TD);
6446 S.Diag(TD->getLocation(),
6447 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6448 << TD << /*1st*/ 0 << /*type*/ 0;
6449 }
6450 if (N > 1) {
6451 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6452 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6453 reportIllegalClassTemplate(S, TD);
6454 S.Diag(TD->getLocation(),
6455 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6456 << TD << /*2nd*/ 1 << /*integer*/ 1;
6457 }
6458 }
6459}
6460
6461static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6462 CXXRecordDecl *Class) {
6463 bool ErrorReported = false;
6464 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6465 ClassTemplateDecl *TD) {
6466 if (ErrorReported)
6467 return;
6468 S.Diag(TD->getLocation(),
6469 diag::err_cuda_device_builtin_surftex_cls_template)
6470 << /*texture*/ 1 << TD;
6471 ErrorReported = true;
6472 };
6473
6474 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6475 if (!TD) {
6476 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6477 if (!SD) {
6478 S.Diag(Class->getLocation(),
6479 diag::err_cuda_device_builtin_surftex_ref_decl)
6480 << /*texture*/ 1 << Class;
6481 S.Diag(Class->getLocation(),
6482 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6483 << Class;
6484 return;
6485 }
6486 TD = SD->getSpecializedTemplate();
6487 }
6488
6489 TemplateParameterList *Params = TD->getTemplateParameters();
6490 unsigned N = Params->size();
6491
6492 if (N != 3) {
6493 reportIllegalClassTemplate(S, TD);
6494 S.Diag(TD->getLocation(),
6495 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6496 << TD << 3;
6497 }
6498 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6499 reportIllegalClassTemplate(S, TD);
6500 S.Diag(TD->getLocation(),
6501 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6502 << TD << /*1st*/ 0 << /*type*/ 0;
6503 }
6504 if (N > 1) {
6505 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6506 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6507 reportIllegalClassTemplate(S, TD);
6508 S.Diag(TD->getLocation(),
6509 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6510 << TD << /*2nd*/ 1 << /*integer*/ 1;
6511 }
6512 }
6513 if (N > 2) {
6514 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 2));
6515 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6516 reportIllegalClassTemplate(S, TD);
6517 S.Diag(TD->getLocation(),
6518 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6519 << TD << /*3rd*/ 2 << /*integer*/ 1;
6520 }
6521 }
6522}
6523
6524void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6525 // Mark any compiler-generated routines with the implicit code_seg attribute.
6526 for (auto *Method : Class->methods()) {
6527 if (Method->isUserProvided())
6528 continue;
6529 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6530 Method->addAttr(A);
6531 }
6532}
6533
6534/// Check class-level dllimport/dllexport attribute.
6535void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6536 Attr *ClassAttr = getDLLAttr(Class);
6537
6538 // MSVC inherits DLL attributes to partial class template specializations.
6539 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6540 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Class)) {
6541 if (Attr *TemplateAttr =
6542 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6543 auto *A = cast<InheritableAttr>(Val: TemplateAttr->clone(C&: getASTContext()));
6544 A->setInherited(true);
6545 ClassAttr = A;
6546 }
6547 }
6548 }
6549
6550 if (!ClassAttr)
6551 return;
6552
6553 // MSVC allows imported or exported template classes that have UniqueExternal
6554 // linkage. This occurs when the template class has been instantiated with
6555 // a template parameter which itself has internal linkage.
6556 // We drop the attribute to avoid exporting or importing any members.
6557 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6558 Context.getTargetInfo().getTriple().isPS()) &&
6559 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6560 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6561 return;
6562 }
6563
6564 if (!Class->isExternallyVisible()) {
6565 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6566 << Class << ClassAttr;
6567 return;
6568 }
6569
6570 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6571 !ClassAttr->isInherited()) {
6572 // Diagnose dll attributes on members of class with dll attribute.
6573 for (Decl *Member : Class->decls()) {
6574 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6575 continue;
6576 InheritableAttr *MemberAttr = getDLLAttr(Member);
6577 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6578 continue;
6579
6580 Diag(MemberAttr->getLocation(),
6581 diag::err_attribute_dll_member_of_dll_class)
6582 << MemberAttr << ClassAttr;
6583 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6584 Member->setInvalidDecl();
6585 }
6586 }
6587
6588 if (Class->getDescribedClassTemplate())
6589 // Don't inherit dll attribute until the template is instantiated.
6590 return;
6591
6592 // The class is either imported or exported.
6593 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6594
6595 // Check if this was a dllimport attribute propagated from a derived class to
6596 // a base class template specialization. We don't apply these attributes to
6597 // static data members.
6598 const bool PropagatedImport =
6599 !ClassExported &&
6600 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6601
6602 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6603
6604 // Ignore explicit dllexport on explicit class template instantiation
6605 // declarations, except in MinGW mode.
6606 if (ClassExported && !ClassAttr->isInherited() &&
6607 TSK == TSK_ExplicitInstantiationDeclaration &&
6608 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6609 Class->dropAttr<DLLExportAttr>();
6610 return;
6611 }
6612
6613 // Force declaration of implicit members so they can inherit the attribute.
6614 ForceDeclarationOfImplicitMembers(Class);
6615
6616 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6617 // seem to be true in practice?
6618
6619 for (Decl *Member : Class->decls()) {
6620 VarDecl *VD = dyn_cast<VarDecl>(Member);
6621 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6622
6623 // Only methods and static fields inherit the attributes.
6624 if (!VD && !MD)
6625 continue;
6626
6627 if (MD) {
6628 // Don't process deleted methods.
6629 if (MD->isDeleted())
6630 continue;
6631
6632 if (MD->isInlined()) {
6633 // MinGW does not import or export inline methods. But do it for
6634 // template instantiations.
6635 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6636 TSK != TSK_ExplicitInstantiationDeclaration &&
6637 TSK != TSK_ExplicitInstantiationDefinition)
6638 continue;
6639
6640 // MSVC versions before 2015 don't export the move assignment operators
6641 // and move constructor, so don't attempt to import/export them if
6642 // we have a definition.
6643 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6644 if ((MD->isMoveAssignmentOperator() ||
6645 (Ctor && Ctor->isMoveConstructor())) &&
6646 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6647 continue;
6648
6649 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6650 // operator is exported anyway.
6651 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6652 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6653 continue;
6654 }
6655 }
6656
6657 // Don't apply dllimport attributes to static data members of class template
6658 // instantiations when the attribute is propagated from a derived class.
6659 if (VD && PropagatedImport)
6660 continue;
6661
6662 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6663 continue;
6664
6665 if (!getDLLAttr(Member)) {
6666 InheritableAttr *NewAttr = nullptr;
6667
6668 // Do not export/import inline function when -fno-dllexport-inlines is
6669 // passed. But add attribute for later local static var check.
6670 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6671 TSK != TSK_ExplicitInstantiationDeclaration &&
6672 TSK != TSK_ExplicitInstantiationDefinition) {
6673 if (ClassExported) {
6674 NewAttr = ::new (getASTContext())
6675 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6676 } else {
6677 NewAttr = ::new (getASTContext())
6678 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6679 }
6680 } else {
6681 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6682 }
6683
6684 NewAttr->setInherited(true);
6685 Member->addAttr(NewAttr);
6686
6687 if (MD) {
6688 // Propagate DLLAttr to friend re-declarations of MD that have already
6689 // been constructed.
6690 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6691 FD = FD->getPreviousDecl()) {
6692 if (FD->getFriendObjectKind() == Decl::FOK_None)
6693 continue;
6694 assert(!getDLLAttr(FD) &&
6695 "friend re-decl should not already have a DLLAttr");
6696 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6697 NewAttr->setInherited(true);
6698 FD->addAttr(NewAttr);
6699 }
6700 }
6701 }
6702 }
6703
6704 if (ClassExported)
6705 DelayedDllExportClasses.push_back(Elt: Class);
6706}
6707
6708/// Perform propagation of DLL attributes from a derived class to a
6709/// templated base class for MS compatibility.
6710void Sema::propagateDLLAttrToBaseClassTemplate(
6711 CXXRecordDecl *Class, Attr *ClassAttr,
6712 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6713 if (getDLLAttr(
6714 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6715 // If the base class template has a DLL attribute, don't try to change it.
6716 return;
6717 }
6718
6719 auto TSK = BaseTemplateSpec->getSpecializationKind();
6720 if (!getDLLAttr(BaseTemplateSpec) &&
6721 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6722 TSK == TSK_ImplicitInstantiation)) {
6723 // The template hasn't been instantiated yet (or it has, but only as an
6724 // explicit instantiation declaration or implicit instantiation, which means
6725 // we haven't codegenned any members yet), so propagate the attribute.
6726 auto *NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6727 NewAttr->setInherited(true);
6728 BaseTemplateSpec->addAttr(NewAttr);
6729
6730 // If this was an import, mark that we propagated it from a derived class to
6731 // a base class template specialization.
6732 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6733 ImportAttr->setPropagatedToBaseTemplate();
6734
6735 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6736 // needs to be run again to work see the new attribute. Otherwise this will
6737 // get run whenever the template is instantiated.
6738 if (TSK != TSK_Undeclared)
6739 checkClassLevelDLLAttribute(BaseTemplateSpec);
6740
6741 return;
6742 }
6743
6744 if (getDLLAttr(BaseTemplateSpec)) {
6745 // The template has already been specialized or instantiated with an
6746 // attribute, explicitly or through propagation. We should not try to change
6747 // it.
6748 return;
6749 }
6750
6751 // The template was previously instantiated or explicitly specialized without
6752 // a dll attribute, It's too late for us to add an attribute, so warn that
6753 // this is unsupported.
6754 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6755 << BaseTemplateSpec->isExplicitSpecialization();
6756 Diag(ClassAttr->getLocation(), diag::note_attribute);
6757 if (BaseTemplateSpec->isExplicitSpecialization()) {
6758 Diag(BaseTemplateSpec->getLocation(),
6759 diag::note_template_class_explicit_specialization_was_here)
6760 << BaseTemplateSpec;
6761 } else {
6762 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6763 diag::note_template_class_instantiation_was_here)
6764 << BaseTemplateSpec;
6765 }
6766}
6767
6768/// Determine the kind of defaulting that would be done for a given function.
6769///
6770/// If the function is both a default constructor and a copy / move constructor
6771/// (due to having a default argument for the first parameter), this picks
6772/// CXXDefaultConstructor.
6773///
6774/// FIXME: Check that case is properly handled by all callers.
6775Sema::DefaultedFunctionKind
6776Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6777 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
6778 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
6779 if (Ctor->isDefaultConstructor())
6780 return Sema::CXXDefaultConstructor;
6781
6782 if (Ctor->isCopyConstructor())
6783 return Sema::CXXCopyConstructor;
6784
6785 if (Ctor->isMoveConstructor())
6786 return Sema::CXXMoveConstructor;
6787 }
6788
6789 if (MD->isCopyAssignmentOperator())
6790 return Sema::CXXCopyAssignment;
6791
6792 if (MD->isMoveAssignmentOperator())
6793 return Sema::CXXMoveAssignment;
6794
6795 if (isa<CXXDestructorDecl>(Val: FD))
6796 return Sema::CXXDestructor;
6797 }
6798
6799 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6800 case OO_EqualEqual:
6801 return DefaultedComparisonKind::Equal;
6802
6803 case OO_ExclaimEqual:
6804 return DefaultedComparisonKind::NotEqual;
6805
6806 case OO_Spaceship:
6807 // No point allowing this if <=> doesn't exist in the current language mode.
6808 if (!getLangOpts().CPlusPlus20)
6809 break;
6810 return DefaultedComparisonKind::ThreeWay;
6811
6812 case OO_Less:
6813 case OO_LessEqual:
6814 case OO_Greater:
6815 case OO_GreaterEqual:
6816 // No point allowing this if <=> doesn't exist in the current language mode.
6817 if (!getLangOpts().CPlusPlus20)
6818 break;
6819 return DefaultedComparisonKind::Relational;
6820
6821 default:
6822 break;
6823 }
6824
6825 // Not defaultable.
6826 return DefaultedFunctionKind();
6827}
6828
6829static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6830 SourceLocation DefaultLoc) {
6831 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6832 if (DFK.isComparison())
6833 return S.DefineDefaultedComparison(Loc: DefaultLoc, FD, DCK: DFK.asComparison());
6834
6835 switch (DFK.asSpecialMember()) {
6836 case Sema::CXXDefaultConstructor:
6837 S.DefineImplicitDefaultConstructor(CurrentLocation: DefaultLoc,
6838 Constructor: cast<CXXConstructorDecl>(Val: FD));
6839 break;
6840 case Sema::CXXCopyConstructor:
6841 S.DefineImplicitCopyConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6842 break;
6843 case Sema::CXXCopyAssignment:
6844 S.DefineImplicitCopyAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6845 break;
6846 case Sema::CXXDestructor:
6847 S.DefineImplicitDestructor(CurrentLocation: DefaultLoc, Destructor: cast<CXXDestructorDecl>(Val: FD));
6848 break;
6849 case Sema::CXXMoveConstructor:
6850 S.DefineImplicitMoveConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6851 break;
6852 case Sema::CXXMoveAssignment:
6853 S.DefineImplicitMoveAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6854 break;
6855 case Sema::CXXInvalid:
6856 llvm_unreachable("Invalid special member.");
6857 }
6858}
6859
6860/// Determine whether a type is permitted to be passed or returned in
6861/// registers, per C++ [class.temporary]p3.
6862static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6863 TargetInfo::CallingConvKind CCK) {
6864 if (D->isDependentType() || D->isInvalidDecl())
6865 return false;
6866
6867 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6868 // The PS4 platform ABI follows the behavior of Clang 3.2.
6869 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6870 return !D->hasNonTrivialDestructorForCall() &&
6871 !D->hasNonTrivialCopyConstructorForCall();
6872
6873 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6874 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6875 bool DtorIsTrivialForCall = false;
6876
6877 // If a class has at least one eligible, trivial copy constructor, it
6878 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6879 //
6880 // Note: This permits classes with non-trivial copy or move ctors to be
6881 // passed in registers, so long as they *also* have a trivial copy ctor,
6882 // which is non-conforming.
6883 if (D->needsImplicitCopyConstructor()) {
6884 if (!D->defaultedCopyConstructorIsDeleted()) {
6885 if (D->hasTrivialCopyConstructor())
6886 CopyCtorIsTrivial = true;
6887 if (D->hasTrivialCopyConstructorForCall())
6888 CopyCtorIsTrivialForCall = true;
6889 }
6890 } else {
6891 for (const CXXConstructorDecl *CD : D->ctors()) {
6892 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6893 !CD->isIneligibleOrNotSelected()) {
6894 if (CD->isTrivial())
6895 CopyCtorIsTrivial = true;
6896 if (CD->isTrivialForCall())
6897 CopyCtorIsTrivialForCall = true;
6898 }
6899 }
6900 }
6901
6902 if (D->needsImplicitDestructor()) {
6903 if (!D->defaultedDestructorIsDeleted() &&
6904 D->hasTrivialDestructorForCall())
6905 DtorIsTrivialForCall = true;
6906 } else if (const auto *DD = D->getDestructor()) {
6907 if (!DD->isDeleted() && DD->isTrivialForCall())
6908 DtorIsTrivialForCall = true;
6909 }
6910
6911 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6912 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6913 return true;
6914
6915 // If a class has a destructor, we'd really like to pass it indirectly
6916 // because it allows us to elide copies. Unfortunately, MSVC makes that
6917 // impossible for small types, which it will pass in a single register or
6918 // stack slot. Most objects with dtors are large-ish, so handle that early.
6919 // We can't call out all large objects as being indirect because there are
6920 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6921 // how we pass large POD types.
6922
6923 // Note: This permits small classes with nontrivial destructors to be
6924 // passed in registers, which is non-conforming.
6925 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6926 uint64_t TypeSize = isAArch64 ? 128 : 64;
6927
6928 if (CopyCtorIsTrivial &&
6929 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6930 return true;
6931 return false;
6932 }
6933
6934 // Per C++ [class.temporary]p3, the relevant condition is:
6935 // each copy constructor, move constructor, and destructor of X is
6936 // either trivial or deleted, and X has at least one non-deleted copy
6937 // or move constructor
6938 bool HasNonDeletedCopyOrMove = false;
6939
6940 if (D->needsImplicitCopyConstructor() &&
6941 !D->defaultedCopyConstructorIsDeleted()) {
6942 if (!D->hasTrivialCopyConstructorForCall())
6943 return false;
6944 HasNonDeletedCopyOrMove = true;
6945 }
6946
6947 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6948 !D->defaultedMoveConstructorIsDeleted()) {
6949 if (!D->hasTrivialMoveConstructorForCall())
6950 return false;
6951 HasNonDeletedCopyOrMove = true;
6952 }
6953
6954 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6955 !D->hasTrivialDestructorForCall())
6956 return false;
6957
6958 for (const CXXMethodDecl *MD : D->methods()) {
6959 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6960 continue;
6961
6962 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6963 if (CD && CD->isCopyOrMoveConstructor())
6964 HasNonDeletedCopyOrMove = true;
6965 else if (!isa<CXXDestructorDecl>(Val: MD))
6966 continue;
6967
6968 if (!MD->isTrivialForCall())
6969 return false;
6970 }
6971
6972 return HasNonDeletedCopyOrMove;
6973}
6974
6975/// Report an error regarding overriding, along with any relevant
6976/// overridden methods.
6977///
6978/// \param DiagID the primary error to report.
6979/// \param MD the overriding method.
6980static bool
6981ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6982 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6983 bool IssuedDiagnostic = false;
6984 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6985 if (Report(O)) {
6986 if (!IssuedDiagnostic) {
6987 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6988 IssuedDiagnostic = true;
6989 }
6990 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6991 }
6992 }
6993 return IssuedDiagnostic;
6994}
6995
6996/// Perform semantic checks on a class definition that has been
6997/// completing, introducing implicitly-declared members, checking for
6998/// abstract types, etc.
6999///
7000/// \param S The scope in which the class was parsed. Null if we didn't just
7001/// parse a class definition.
7002/// \param Record The completed class.
7003void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
7004 if (!Record)
7005 return;
7006
7007 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7008 AbstractUsageInfo Info(*this, Record);
7009 CheckAbstractClassUsage(Info, RD: Record);
7010 }
7011
7012 // If this is not an aggregate type and has no user-declared constructor,
7013 // complain about any non-static data members of reference or const scalar
7014 // type, since they will never get initializers.
7015 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7016 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7017 !Record->isLambda()) {
7018 bool Complained = false;
7019 for (const auto *F : Record->fields()) {
7020 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
7021 continue;
7022
7023 if (F->getType()->isReferenceType() ||
7024 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7025 if (!Complained) {
7026 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7027 << llvm::to_underlying(Record->getTagKind()) << Record;
7028 Complained = true;
7029 }
7030
7031 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7032 << F->getType()->isReferenceType()
7033 << F->getDeclName();
7034 }
7035 }
7036 }
7037
7038 if (Record->getIdentifier()) {
7039 // C++ [class.mem]p13:
7040 // If T is the name of a class, then each of the following shall have a
7041 // name different from T:
7042 // - every member of every anonymous union that is a member of class T.
7043 //
7044 // C++ [class.mem]p14:
7045 // In addition, if class T has a user-declared constructor (12.1), every
7046 // non-static data member of class T shall have a name different from T.
7047 DeclContext::lookup_result R = Record->lookup(Name: Record->getDeclName());
7048 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7049 ++I) {
7050 NamedDecl *D = (*I)->getUnderlyingDecl();
7051 if (((isa<FieldDecl>(Val: D) || isa<UnresolvedUsingValueDecl>(Val: D)) &&
7052 Record->hasUserDeclaredConstructor()) ||
7053 isa<IndirectFieldDecl>(Val: D)) {
7054 Diag((*I)->getLocation(), diag::err_member_name_of_class)
7055 << D->getDeclName();
7056 break;
7057 }
7058 }
7059 }
7060
7061 // Warn if the class has virtual methods but non-virtual public destructor.
7062 if (Record->isPolymorphic() && !Record->isDependentType()) {
7063 CXXDestructorDecl *dtor = Record->getDestructor();
7064 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7065 !Record->hasAttr<FinalAttr>())
7066 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7067 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
7068 }
7069
7070 if (Record->isAbstract()) {
7071 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7072 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7073 << FA->isSpelledAsSealed();
7074 DiagnoseAbstractType(RD: Record);
7075 }
7076 }
7077
7078 // Warn if the class has a final destructor but is not itself marked final.
7079 if (!Record->hasAttr<FinalAttr>()) {
7080 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7081 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7082 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7083 << FA->isSpelledAsSealed()
7084 << FixItHint::CreateInsertion(
7085 getLocForEndOfToken(Record->getLocation()),
7086 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7087 Diag(Record->getLocation(),
7088 diag::note_final_dtor_non_final_class_silence)
7089 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
7090 }
7091 }
7092 }
7093
7094 // See if trivial_abi has to be dropped.
7095 if (Record->hasAttr<TrivialABIAttr>())
7096 checkIllFormedTrivialABIStruct(RD&: *Record);
7097
7098 // Set HasTrivialSpecialMemberForCall if the record has attribute
7099 // "trivial_abi".
7100 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7101
7102 if (HasTrivialABI)
7103 Record->setHasTrivialSpecialMemberForCall();
7104
7105 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7106 // We check these last because they can depend on the properties of the
7107 // primary comparison functions (==, <=>).
7108 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7109
7110 // Perform checks that can't be done until we know all the properties of a
7111 // member function (whether it's defaulted, deleted, virtual, overriding,
7112 // ...).
7113 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7114 // A static function cannot override anything.
7115 if (MD->getStorageClass() == SC_Static) {
7116 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7117 [](const CXXMethodDecl *) { return true; }))
7118 return;
7119 }
7120
7121 // A deleted function cannot override a non-deleted function and vice
7122 // versa.
7123 if (ReportOverrides(*this,
7124 MD->isDeleted() ? diag::err_deleted_override
7125 : diag::err_non_deleted_override,
7126 MD, [&](const CXXMethodDecl *V) {
7127 return MD->isDeleted() != V->isDeleted();
7128 })) {
7129 if (MD->isDefaulted() && MD->isDeleted())
7130 // Explain why this defaulted function was deleted.
7131 DiagnoseDeletedDefaultedFunction(MD);
7132 return;
7133 }
7134
7135 // A consteval function cannot override a non-consteval function and vice
7136 // versa.
7137 if (ReportOverrides(*this,
7138 MD->isConsteval() ? diag::err_consteval_override
7139 : diag::err_non_consteval_override,
7140 MD, [&](const CXXMethodDecl *V) {
7141 return MD->isConsteval() != V->isConsteval();
7142 })) {
7143 if (MD->isDefaulted() && MD->isDeleted())
7144 // Explain why this defaulted function was deleted.
7145 DiagnoseDeletedDefaultedFunction(MD);
7146 return;
7147 }
7148 };
7149
7150 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7151 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7152 return false;
7153
7154 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7155 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7156 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7157 DefaultedSecondaryComparisons.push_back(Elt: FD);
7158 return true;
7159 }
7160
7161 CheckExplicitlyDefaultedFunction(S, MD: FD);
7162 return false;
7163 };
7164
7165 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7166 // Check whether the explicitly-defaulted members are valid.
7167 bool Incomplete = CheckForDefaultedFunction(M);
7168
7169 // Skip the rest of the checks for a member of a dependent class.
7170 if (Record->isDependentType())
7171 return;
7172
7173 // For an explicitly defaulted or deleted special member, we defer
7174 // determining triviality until the class is complete. That time is now!
7175 CXXSpecialMember CSM = getSpecialMember(MD: M);
7176 if (!M->isImplicit() && !M->isUserProvided()) {
7177 if (CSM != CXXInvalid) {
7178 M->setTrivial(SpecialMemberIsTrivial(MD: M, CSM));
7179 // Inform the class that we've finished declaring this member.
7180 Record->finishedDefaultedOrDeletedMember(MD: M);
7181 M->setTrivialForCall(
7182 HasTrivialABI ||
7183 SpecialMemberIsTrivial(MD: M, CSM, TAH: TAH_ConsiderTrivialABI));
7184 Record->setTrivialForCallFlags(M);
7185 }
7186 }
7187
7188 // Set triviality for the purpose of calls if this is a user-provided
7189 // copy/move constructor or destructor.
7190 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
7191 CSM == CXXDestructor) && M->isUserProvided()) {
7192 M->setTrivialForCall(HasTrivialABI);
7193 Record->setTrivialForCallFlags(M);
7194 }
7195
7196 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7197 M->hasAttr<DLLExportAttr>()) {
7198 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7199 M->isTrivial() &&
7200 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
7201 CSM == CXXDestructor))
7202 M->dropAttr<DLLExportAttr>();
7203
7204 if (M->hasAttr<DLLExportAttr>()) {
7205 // Define after any fields with in-class initializers have been parsed.
7206 DelayedDllExportMemberFunctions.push_back(Elt: M);
7207 }
7208 }
7209
7210 // Define defaulted constexpr virtual functions that override a base class
7211 // function right away.
7212 // FIXME: We can defer doing this until the vtable is marked as used.
7213 if (CSM != CXXInvalid && !M->isDeleted() && M->isDefaulted() &&
7214 M->isConstexpr() && M->size_overridden_methods())
7215 DefineDefaultedFunction(*this, M, M->getLocation());
7216
7217 if (!Incomplete)
7218 CheckCompletedMemberFunction(M);
7219 };
7220
7221 // Check the destructor before any other member function. We need to
7222 // determine whether it's trivial in order to determine whether the claas
7223 // type is a literal type, which is a prerequisite for determining whether
7224 // other special member functions are valid and whether they're implicitly
7225 // 'constexpr'.
7226 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7227 CompleteMemberFunction(Dtor);
7228
7229 bool HasMethodWithOverrideControl = false,
7230 HasOverridingMethodWithoutOverrideControl = false;
7231 for (auto *D : Record->decls()) {
7232 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7233 // FIXME: We could do this check for dependent types with non-dependent
7234 // bases.
7235 if (!Record->isDependentType()) {
7236 // See if a method overloads virtual methods in a base
7237 // class without overriding any.
7238 if (!M->isStatic())
7239 DiagnoseHiddenVirtualMethods(M);
7240 if (M->hasAttr<OverrideAttr>())
7241 HasMethodWithOverrideControl = true;
7242 else if (M->size_overridden_methods() > 0)
7243 HasOverridingMethodWithoutOverrideControl = true;
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 // ArgPassingKind::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
7327/// Look up the special member function that would be called by a special
7328/// member function for a subobject of class type.
7329///
7330/// \param Class The class type of the subobject.
7331/// \param CSM The kind of special member function.
7332/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7333/// \param ConstRHS True if this is a copy operation with a const object
7334/// on its RHS, that is, if the argument to the outer special member
7335/// function is 'const' and this is not a field marked 'mutable'.
7336static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7337 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7338 unsigned FieldQuals, bool ConstRHS) {
7339 unsigned LHSQuals = 0;
7340 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7341 LHSQuals = FieldQuals;
7342
7343 unsigned RHSQuals = FieldQuals;
7344 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7345 RHSQuals = 0;
7346 else if (ConstRHS)
7347 RHSQuals |= Qualifiers::Const;
7348
7349 return S.LookupSpecialMember(D: Class, SM: CSM,
7350 ConstArg: RHSQuals & Qualifiers::Const,
7351 VolatileArg: RHSQuals & Qualifiers::Volatile,
7352 RValueThis: false,
7353 ConstThis: LHSQuals & Qualifiers::Const,
7354 VolatileThis: LHSQuals & Qualifiers::Volatile);
7355}
7356
7357class Sema::InheritedConstructorInfo {
7358 Sema &S;
7359 SourceLocation UseLoc;
7360
7361 /// A mapping from the base classes through which the constructor was
7362 /// inherited to the using shadow declaration in that base class (or a null
7363 /// pointer if the constructor was declared in that base class).
7364 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7365 InheritedFromBases;
7366
7367public:
7368 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7369 ConstructorUsingShadowDecl *Shadow)
7370 : S(S), UseLoc(UseLoc) {
7371 bool DiagnosedMultipleConstructedBases = false;
7372 CXXRecordDecl *ConstructedBase = nullptr;
7373 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7374
7375 // Find the set of such base class subobjects and check that there's a
7376 // unique constructed subobject.
7377 for (auto *D : Shadow->redecls()) {
7378 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7379 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7380 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7381
7382 InheritedFromBases.insert(
7383 std::make_pair(DNominatedBase->getCanonicalDecl(),
7384 DShadow->getNominatedBaseClassShadowDecl()));
7385 if (DShadow->constructsVirtualBase())
7386 InheritedFromBases.insert(
7387 std::make_pair(DConstructedBase->getCanonicalDecl(),
7388 DShadow->getConstructedBaseClassShadowDecl()));
7389 else
7390 assert(DNominatedBase == DConstructedBase);
7391
7392 // [class.inhctor.init]p2:
7393 // If the constructor was inherited from multiple base class subobjects
7394 // of type B, the program is ill-formed.
7395 if (!ConstructedBase) {
7396 ConstructedBase = DConstructedBase;
7397 ConstructedBaseIntroducer = D->getIntroducer();
7398 } else if (ConstructedBase != DConstructedBase &&
7399 !Shadow->isInvalidDecl()) {
7400 if (!DiagnosedMultipleConstructedBases) {
7401 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7402 << Shadow->getTargetDecl();
7403 S.Diag(ConstructedBaseIntroducer->getLocation(),
7404 diag::note_ambiguous_inherited_constructor_using)
7405 << ConstructedBase;
7406 DiagnosedMultipleConstructedBases = true;
7407 }
7408 S.Diag(D->getIntroducer()->getLocation(),
7409 diag::note_ambiguous_inherited_constructor_using)
7410 << DConstructedBase;
7411 }
7412 }
7413
7414 if (DiagnosedMultipleConstructedBases)
7415 Shadow->setInvalidDecl();
7416 }
7417
7418 /// Find the constructor to use for inherited construction of a base class,
7419 /// and whether that base class constructor inherits the constructor from a
7420 /// virtual base class (in which case it won't actually invoke it).
7421 std::pair<CXXConstructorDecl *, bool>
7422 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7423 auto It = InheritedFromBases.find(Val: Base->getCanonicalDecl());
7424 if (It == InheritedFromBases.end())
7425 return std::make_pair(x: nullptr, y: false);
7426
7427 // This is an intermediary class.
7428 if (It->second)
7429 return std::make_pair(
7430 x: S.findInheritingConstructor(Loc: UseLoc, BaseCtor: Ctor, DerivedShadow: It->second),
7431 y: It->second->constructsVirtualBase());
7432
7433 // This is the base class from which the constructor was inherited.
7434 return std::make_pair(x&: Ctor, y: false);
7435 }
7436};
7437
7438/// Is the special member function which would be selected to perform the
7439/// specified operation on the specified class type a constexpr constructor?
7440static bool
7441specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7442 Sema::CXXSpecialMember CSM, unsigned Quals,
7443 bool ConstRHS,
7444 CXXConstructorDecl *InheritedCtor = nullptr,
7445 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7446 // Suppress duplicate constraint checking here, in case a constraint check
7447 // caused us to decide to do this. Any truely recursive checks will get
7448 // caught during these checks anyway.
7449 Sema::SatisfactionStackResetRAII SSRAII{S};
7450
7451 // If we're inheriting a constructor, see if we need to call it for this base
7452 // class.
7453 if (InheritedCtor) {
7454 assert(CSM == Sema::CXXDefaultConstructor);
7455 auto BaseCtor =
7456 Inherited->findConstructorForBase(Base: ClassDecl, Ctor: InheritedCtor).first;
7457 if (BaseCtor)
7458 return BaseCtor->isConstexpr();
7459 }
7460
7461 if (CSM == Sema::CXXDefaultConstructor)
7462 return ClassDecl->hasConstexprDefaultConstructor();
7463 if (CSM == Sema::CXXDestructor)
7464 return ClassDecl->hasConstexprDestructor();
7465
7466 Sema::SpecialMemberOverloadResult SMOR =
7467 lookupCallFromSpecialMember(S, Class: ClassDecl, CSM, FieldQuals: Quals, ConstRHS);
7468 if (!SMOR.getMethod())
7469 // A constructor we wouldn't select can't be "involved in initializing"
7470 // anything.
7471 return true;
7472 return SMOR.getMethod()->isConstexpr();
7473}
7474
7475/// Determine whether the specified special member function would be constexpr
7476/// if it were implicitly defined.
7477static bool defaultedSpecialMemberIsConstexpr(
7478 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7479 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7480 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7481 if (!S.getLangOpts().CPlusPlus11)
7482 return false;
7483
7484 // C++11 [dcl.constexpr]p4:
7485 // In the definition of a constexpr constructor [...]
7486 bool Ctor = true;
7487 switch (CSM) {
7488 case Sema::CXXDefaultConstructor:
7489 if (Inherited)
7490 break;
7491 // Since default constructor lookup is essentially trivial (and cannot
7492 // involve, for instance, template instantiation), we compute whether a
7493 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7494 //
7495 // This is important for performance; we need to know whether the default
7496 // constructor is constexpr to determine whether the type is a literal type.
7497 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7498
7499 case Sema::CXXCopyConstructor:
7500 case Sema::CXXMoveConstructor:
7501 // For copy or move constructors, we need to perform overload resolution.
7502 break;
7503
7504 case Sema::CXXCopyAssignment:
7505 case Sema::CXXMoveAssignment:
7506 if (!S.getLangOpts().CPlusPlus14)
7507 return false;
7508 // In C++1y, we need to perform overload resolution.
7509 Ctor = false;
7510 break;
7511
7512 case Sema::CXXDestructor:
7513 return ClassDecl->defaultedDestructorIsConstexpr();
7514
7515 case Sema::CXXInvalid:
7516 return false;
7517 }
7518
7519 // -- if the class is a non-empty union, or for each non-empty anonymous
7520 // union member of a non-union class, exactly one non-static data member
7521 // shall be initialized; [DR1359]
7522 //
7523 // If we squint, this is guaranteed, since exactly one non-static data member
7524 // will be initialized (if the constructor isn't deleted), we just don't know
7525 // which one.
7526 if (Ctor && ClassDecl->isUnion())
7527 return CSM == Sema::CXXDefaultConstructor
7528 ? ClassDecl->hasInClassInitializer() ||
7529 !ClassDecl->hasVariantMembers()
7530 : true;
7531
7532 // -- the class shall not have any virtual base classes;
7533 if (Ctor && ClassDecl->getNumVBases())
7534 return false;
7535
7536 // C++1y [class.copy]p26:
7537 // -- [the class] is a literal type, and
7538 if (!Ctor && !ClassDecl->isLiteral())
7539 return false;
7540
7541 // -- every constructor involved in initializing [...] base class
7542 // sub-objects shall be a constexpr constructor;
7543 // -- the assignment operator selected to copy/move each direct base
7544 // class is a constexpr function, and
7545 for (const auto &B : ClassDecl->bases()) {
7546 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7547 if (!BaseType)
7548 continue;
7549 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(Val: BaseType->getDecl());
7550 if (!specialMemberIsConstexpr(S, ClassDecl: BaseClassDecl, CSM, Quals: 0, ConstRHS: ConstArg,
7551 InheritedCtor, Inherited))
7552 return false;
7553 }
7554
7555 // -- every constructor involved in initializing non-static data members
7556 // [...] shall be a constexpr constructor;
7557 // -- every non-static data member and base class sub-object shall be
7558 // initialized
7559 // -- for each non-static data member of X that is of class type (or array
7560 // thereof), the assignment operator selected to copy/move that member is
7561 // a constexpr function
7562 for (const auto *F : ClassDecl->fields()) {
7563 if (F->isInvalidDecl())
7564 continue;
7565 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7566 continue;
7567 QualType BaseType = S.Context.getBaseElementType(F->getType());
7568 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7569 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7570 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7571 BaseType.getCVRQualifiers(),
7572 ConstArg && !F->isMutable()))
7573 return false;
7574 } else if (CSM == Sema::CXXDefaultConstructor) {
7575 return false;
7576 }
7577 }
7578
7579 // All OK, it's constexpr!
7580 return true;
7581}
7582
7583namespace {
7584/// RAII object to register a defaulted function as having its exception
7585/// specification computed.
7586struct ComputingExceptionSpec {
7587 Sema &S;
7588
7589 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7590 : S(S) {
7591 Sema::CodeSynthesisContext Ctx;
7592 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7593 Ctx.PointOfInstantiation = Loc;
7594 Ctx.Entity = FD;
7595 S.pushCodeSynthesisContext(Ctx);
7596 }
7597 ~ComputingExceptionSpec() {
7598 S.popCodeSynthesisContext();
7599 }
7600};
7601}
7602
7603static Sema::ImplicitExceptionSpecification
7604ComputeDefaultedSpecialMemberExceptionSpec(
7605 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7606 Sema::InheritedConstructorInfo *ICI);
7607
7608static Sema::ImplicitExceptionSpecification
7609ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7610 FunctionDecl *FD,
7611 Sema::DefaultedComparisonKind DCK);
7612
7613static Sema::ImplicitExceptionSpecification
7614computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7615 auto DFK = S.getDefaultedFunctionKind(FD);
7616 if (DFK.isSpecialMember())
7617 return ComputeDefaultedSpecialMemberExceptionSpec(
7618 S, Loc, MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), ICI: nullptr);
7619 if (DFK.isComparison())
7620 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7621 DCK: DFK.asComparison());
7622
7623 auto *CD = cast<CXXConstructorDecl>(Val: FD);
7624 assert(CD->getInheritedConstructor() &&
7625 "only defaulted functions and inherited constructors have implicit "
7626 "exception specs");
7627 Sema::InheritedConstructorInfo ICI(
7628 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7629 return ComputeDefaultedSpecialMemberExceptionSpec(
7630 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7631}
7632
7633static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7634 CXXMethodDecl *MD) {
7635 FunctionProtoType::ExtProtoInfo EPI;
7636
7637 // Build an exception specification pointing back at this member.
7638 EPI.ExceptionSpec.Type = EST_Unevaluated;
7639 EPI.ExceptionSpec.SourceDecl = MD;
7640
7641 // Set the calling convention to the default for C++ instance methods.
7642 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7643 cc: S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7644 /*IsCXXMethod=*/true));
7645 return EPI;
7646}
7647
7648void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7649 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7650 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7651 return;
7652
7653 // Evaluate the exception specification.
7654 auto IES = computeImplicitExceptionSpec(S&: *this, Loc, FD);
7655 auto ESI = IES.getExceptionSpec();
7656
7657 // Update the type of the special member to use it.
7658 UpdateExceptionSpec(FD, ESI);
7659}
7660
7661void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7662 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7663
7664 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7665 if (!DefKind) {
7666 assert(FD->getDeclContext()->isDependentContext());
7667 return;
7668 }
7669
7670 if (DefKind.isComparison())
7671 UnusedPrivateFields.clear();
7672
7673 if (DefKind.isSpecialMember()
7674 ? CheckExplicitlyDefaultedSpecialMember(MD: cast<CXXMethodDecl>(Val: FD),
7675 CSM: DefKind.asSpecialMember(),
7676 DefaultLoc: FD->getDefaultLoc())
7677 : CheckExplicitlyDefaultedComparison(S, MD: FD, DCK: DefKind.asComparison()))
7678 FD->setInvalidDecl();
7679}
7680
7681bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7682 CXXSpecialMember CSM,
7683 SourceLocation DefaultLoc) {
7684 CXXRecordDecl *RD = MD->getParent();
7685
7686 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7687 "not an explicitly-defaulted special member");
7688
7689 // Defer all checking for special members of a dependent type.
7690 if (RD->isDependentType())
7691 return false;
7692
7693 // Whether this was the first-declared instance of the constructor.
7694 // This affects whether we implicitly add an exception spec and constexpr.
7695 bool First = MD == MD->getCanonicalDecl();
7696
7697 bool HadError = false;
7698
7699 // C++11 [dcl.fct.def.default]p1:
7700 // A function that is explicitly defaulted shall
7701 // -- be a special member function [...] (checked elsewhere),
7702 // -- have the same type (except for ref-qualifiers, and except that a
7703 // copy operation can take a non-const reference) as an implicit
7704 // declaration, and
7705 // -- not have default arguments.
7706 // C++2a changes the second bullet to instead delete the function if it's
7707 // defaulted on its first declaration, unless it's "an assignment operator,
7708 // and its return type differs or its parameter type is not a reference".
7709 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7710 bool ShouldDeleteForTypeMismatch = false;
7711 unsigned ExpectedParams = 1;
7712 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7713 ExpectedParams = 0;
7714 if (MD->getNumExplicitParams() != ExpectedParams) {
7715 // This checks for default arguments: a copy or move constructor with a
7716 // default argument is classified as a default constructor, and assignment
7717 // operations and destructors can't have default arguments.
7718 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7719 << CSM << MD->getSourceRange();
7720 HadError = true;
7721 } else if (MD->isVariadic()) {
7722 if (DeleteOnTypeMismatch)
7723 ShouldDeleteForTypeMismatch = true;
7724 else {
7725 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7726 << CSM << MD->getSourceRange();
7727 HadError = true;
7728 }
7729 }
7730
7731 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7732
7733 bool CanHaveConstParam = false;
7734 if (CSM == CXXCopyConstructor)
7735 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7736 else if (CSM == CXXCopyAssignment)
7737 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7738
7739 QualType ReturnType = Context.VoidTy;
7740 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7741 // Check for return type matching.
7742 ReturnType = Type->getReturnType();
7743 QualType ThisType = MD->getFunctionObjectParameterType();
7744
7745 QualType DeclType = Context.getTypeDeclType(RD);
7746 DeclType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
7747 NamedType: DeclType, OwnedTagDecl: nullptr);
7748 DeclType = Context.getAddrSpaceQualType(
7749 T: DeclType, AddressSpace: ThisType.getQualifiers().getAddressSpace());
7750 QualType ExpectedReturnType = Context.getLValueReferenceType(T: DeclType);
7751
7752 if (!Context.hasSameType(T1: ReturnType, T2: ExpectedReturnType)) {
7753 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7754 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7755 HadError = true;
7756 }
7757
7758 // A defaulted special member cannot have cv-qualifiers.
7759 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7760 if (DeleteOnTypeMismatch)
7761 ShouldDeleteForTypeMismatch = true;
7762 else {
7763 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7764 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7765 HadError = true;
7766 }
7767 }
7768 // [C++23][dcl.fct.def.default]/p2.2
7769 // if F2 has an implicit object parameter of type “reference to C”,
7770 // F1 may be an explicit object member function whose explicit object
7771 // parameter is of (possibly different) type “reference to C”,
7772 // in which case the type of F1 would differ from the type of F2
7773 // in that the type of F1 has an additional parameter;
7774 if (!Context.hasSameType(
7775 T1: ThisType.getNonReferenceType().getUnqualifiedType(),
7776 T2: Context.getRecordType(RD))) {
7777 if (DeleteOnTypeMismatch)
7778 ShouldDeleteForTypeMismatch = true;
7779 else {
7780 Diag(MD->getLocation(),
7781 diag::err_defaulted_special_member_explicit_object_mismatch)
7782 << (CSM == CXXMoveAssignment) << RD << MD->getSourceRange();
7783 HadError = true;
7784 }
7785 }
7786 }
7787
7788 // Check for parameter type matching.
7789 QualType ArgType =
7790 ExpectedParams
7791 ? Type->getParamType(i: MD->isExplicitObjectMemberFunction() ? 1 : 0)
7792 : QualType();
7793 bool HasConstParam = false;
7794 if (ExpectedParams && ArgType->isReferenceType()) {
7795 // Argument must be reference to possibly-const T.
7796 QualType ReferentType = ArgType->getPointeeType();
7797 HasConstParam = ReferentType.isConstQualified();
7798
7799 if (ReferentType.isVolatileQualified()) {
7800 if (DeleteOnTypeMismatch)
7801 ShouldDeleteForTypeMismatch = true;
7802 else {
7803 Diag(MD->getLocation(),
7804 diag::err_defaulted_special_member_volatile_param) << CSM;
7805 HadError = true;
7806 }
7807 }
7808
7809 if (HasConstParam && !CanHaveConstParam) {
7810 if (DeleteOnTypeMismatch)
7811 ShouldDeleteForTypeMismatch = true;
7812 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7813 Diag(MD->getLocation(),
7814 diag::err_defaulted_special_member_copy_const_param)
7815 << (CSM == CXXCopyAssignment);
7816 // FIXME: Explain why this special member can't be const.
7817 HadError = true;
7818 } else {
7819 Diag(MD->getLocation(),
7820 diag::err_defaulted_special_member_move_const_param)
7821 << (CSM == CXXMoveAssignment);
7822 HadError = true;
7823 }
7824 }
7825 } else if (ExpectedParams) {
7826 // A copy assignment operator can take its argument by value, but a
7827 // defaulted one cannot.
7828 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7829 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7830 HadError = true;
7831 }
7832
7833 // C++11 [dcl.fct.def.default]p2:
7834 // An explicitly-defaulted function may be declared constexpr only if it
7835 // would have been implicitly declared as constexpr,
7836 // Do not apply this rule to members of class templates, since core issue 1358
7837 // makes such functions always instantiate to constexpr functions. For
7838 // functions which cannot be constexpr (for non-constructors in C++11 and for
7839 // destructors in C++14 and C++17), this is checked elsewhere.
7840 //
7841 // FIXME: This should not apply if the member is deleted.
7842 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: RD, CSM,
7843 ConstArg: HasConstParam);
7844
7845 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7846 // If the instantiated template specialization of a constexpr function
7847 // template or member function of a class template would fail to satisfy
7848 // the requirements for a constexpr function or constexpr constructor, that
7849 // specialization is still a constexpr function or constexpr constructor,
7850 // even though a call to such a function cannot appear in a constant
7851 // expression.
7852 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7853 Constexpr = true;
7854
7855 if ((getLangOpts().CPlusPlus20 ||
7856 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(Val: MD)
7857 : isa<CXXConstructorDecl>(Val: MD))) &&
7858 MD->isConstexpr() && !Constexpr &&
7859 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7860 if (!MD->isConsteval() && RD->getNumVBases()) {
7861 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr_with_vb)
7862 << CSM;
7863 for (const auto &I : RD->vbases())
7864 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7865 } else {
7866 Diag(MD->getBeginLoc(), MD->isConsteval()
7867 ? diag::err_incorrect_defaulted_consteval
7868 : diag::err_incorrect_defaulted_constexpr)
7869 << CSM;
7870 }
7871 // FIXME: Explain why the special member can't be constexpr.
7872 HadError = true;
7873 }
7874
7875 if (First) {
7876 // C++2a [dcl.fct.def.default]p3:
7877 // If a function is explicitly defaulted on its first declaration, it is
7878 // implicitly considered to be constexpr if the implicit declaration
7879 // would be.
7880 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7881 ? ConstexprSpecKind::Consteval
7882 : ConstexprSpecKind::Constexpr)
7883 : ConstexprSpecKind::Unspecified);
7884
7885 if (!Type->hasExceptionSpec()) {
7886 // C++2a [except.spec]p3:
7887 // If a declaration of a function does not have a noexcept-specifier
7888 // [and] is defaulted on its first declaration, [...] the exception
7889 // specification is as specified below
7890 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7891 EPI.ExceptionSpec.Type = EST_Unevaluated;
7892 EPI.ExceptionSpec.SourceDecl = MD;
7893 MD->setType(
7894 Context.getFunctionType(ResultTy: ReturnType, Args: Type->getParamTypes(), EPI));
7895 }
7896 }
7897
7898 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7899 if (First) {
7900 SetDeclDeleted(dcl: MD, DelLoc: MD->getLocation());
7901 if (!inTemplateInstantiation() && !HadError) {
7902 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7903 if (ShouldDeleteForTypeMismatch) {
7904 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7905 } else if (ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr,
7906 /*Diagnose*/ true) &&
7907 DefaultLoc.isValid()) {
7908 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7909 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7910 }
7911 }
7912 if (ShouldDeleteForTypeMismatch && !HadError) {
7913 Diag(MD->getLocation(),
7914 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7915 }
7916 } else {
7917 // C++11 [dcl.fct.def.default]p4:
7918 // [For a] user-provided explicitly-defaulted function [...] if such a
7919 // function is implicitly defined as deleted, the program is ill-formed.
7920 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7921 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7922 ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, /*Diagnose*/true);
7923 HadError = true;
7924 }
7925 }
7926
7927 return HadError;
7928}
7929
7930namespace {
7931/// Helper class for building and checking a defaulted comparison.
7932///
7933/// Defaulted functions are built in two phases:
7934///
7935/// * First, the set of operations that the function will perform are
7936/// identified, and some of them are checked. If any of the checked
7937/// operations is invalid in certain ways, the comparison function is
7938/// defined as deleted and no body is built.
7939/// * Then, if the function is not defined as deleted, the body is built.
7940///
7941/// This is accomplished by performing two visitation steps over the eventual
7942/// body of the function.
7943template<typename Derived, typename ResultList, typename Result,
7944 typename Subobject>
7945class DefaultedComparisonVisitor {
7946public:
7947 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7948
7949 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7950 DefaultedComparisonKind DCK)
7951 : S(S), RD(RD), FD(FD), DCK(DCK) {
7952 if (auto *Info = FD->getDefaultedFunctionInfo()) {
7953 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7954 // UnresolvedSet to avoid this copy.
7955 Fns.assign(I: Info->getUnqualifiedLookups().begin(),
7956 E: Info->getUnqualifiedLookups().end());
7957 }
7958 }
7959
7960 ResultList visit() {
7961 // The type of an lvalue naming a parameter of this function.
7962 QualType ParamLvalType =
7963 FD->getParamDecl(i: 0)->getType().getNonReferenceType();
7964
7965 ResultList Results;
7966
7967 switch (DCK) {
7968 case DefaultedComparisonKind::None:
7969 llvm_unreachable("not a defaulted comparison");
7970
7971 case DefaultedComparisonKind::Equal:
7972 case DefaultedComparisonKind::ThreeWay:
7973 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7974 return Results;
7975
7976 case DefaultedComparisonKind::NotEqual:
7977 case DefaultedComparisonKind::Relational:
7978 Results.add(getDerived().visitExpandedSubobject(
7979 ParamLvalType, getDerived().getCompleteObject()));
7980 return Results;
7981 }
7982 llvm_unreachable("");
7983 }
7984
7985protected:
7986 Derived &getDerived() { return static_cast<Derived&>(*this); }
7987
7988 /// Visit the expanded list of subobjects of the given type, as specified in
7989 /// C++2a [class.compare.default].
7990 ///
7991 /// \return \c true if the ResultList object said we're done, \c false if not.
7992 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7993 Qualifiers Quals) {
7994 // C++2a [class.compare.default]p4:
7995 // The direct base class subobjects of C
7996 for (CXXBaseSpecifier &Base : Record->bases())
7997 if (Results.add(getDerived().visitSubobject(
7998 S.Context.getQualifiedType(T: Base.getType(), Qs: Quals),
7999 getDerived().getBase(&Base))))
8000 return true;
8001
8002 // followed by the non-static data members of C
8003 for (FieldDecl *Field : Record->fields()) {
8004 // C++23 [class.bit]p2:
8005 // Unnamed bit-fields are not members ...
8006 if (Field->isUnnamedBitfield())
8007 continue;
8008 // Recursively expand anonymous structs.
8009 if (Field->isAnonymousStructOrUnion()) {
8010 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8011 Quals))
8012 return true;
8013 continue;
8014 }
8015
8016 // Figure out the type of an lvalue denoting this field.
8017 Qualifiers FieldQuals = Quals;
8018 if (Field->isMutable())
8019 FieldQuals.removeConst();
8020 QualType FieldType =
8021 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8022
8023 if (Results.add(getDerived().visitSubobject(
8024 FieldType, getDerived().getField(Field))))
8025 return true;
8026 }
8027
8028 // form a list of subobjects.
8029 return false;
8030 }
8031
8032 Result visitSubobject(QualType Type, Subobject Subobj) {
8033 // In that list, any subobject of array type is recursively expanded
8034 const ArrayType *AT = S.Context.getAsArrayType(T: Type);
8035 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(Val: AT))
8036 return getDerived().visitSubobjectArray(CAT->getElementType(),
8037 CAT->getSize(), Subobj);
8038 return getDerived().visitExpandedSubobject(Type, Subobj);
8039 }
8040
8041 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8042 Subobject Subobj) {
8043 return getDerived().visitSubobject(Type, Subobj);
8044 }
8045
8046protected:
8047 Sema &S;
8048 CXXRecordDecl *RD;
8049 FunctionDecl *FD;
8050 DefaultedComparisonKind DCK;
8051 UnresolvedSet<16> Fns;
8052};
8053
8054/// Information about a defaulted comparison, as determined by
8055/// DefaultedComparisonAnalyzer.
8056struct DefaultedComparisonInfo {
8057 bool Deleted = false;
8058 bool Constexpr = true;
8059 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8060
8061 static DefaultedComparisonInfo deleted() {
8062 DefaultedComparisonInfo Deleted;
8063 Deleted.Deleted = true;
8064 return Deleted;
8065 }
8066
8067 bool add(const DefaultedComparisonInfo &R) {
8068 Deleted |= R.Deleted;
8069 Constexpr &= R.Constexpr;
8070 Category = commonComparisonType(A: Category, B: R.Category);
8071 return Deleted;
8072 }
8073};
8074
8075/// An element in the expanded list of subobjects of a defaulted comparison, as
8076/// specified in C++2a [class.compare.default]p4.
8077struct DefaultedComparisonSubobject {
8078 enum { CompleteObject, Member, Base } Kind;
8079 NamedDecl *Decl;
8080 SourceLocation Loc;
8081};
8082
8083/// A visitor over the notional body of a defaulted comparison that determines
8084/// whether that body would be deleted or constexpr.
8085class DefaultedComparisonAnalyzer
8086 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8087 DefaultedComparisonInfo,
8088 DefaultedComparisonInfo,
8089 DefaultedComparisonSubobject> {
8090public:
8091 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8092
8093private:
8094 DiagnosticKind Diagnose;
8095
8096public:
8097 using Base = DefaultedComparisonVisitor;
8098 using Result = DefaultedComparisonInfo;
8099 using Subobject = DefaultedComparisonSubobject;
8100
8101 friend Base;
8102
8103 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8104 DefaultedComparisonKind DCK,
8105 DiagnosticKind Diagnose = NoDiagnostics)
8106 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8107
8108 Result visit() {
8109 if ((DCK == DefaultedComparisonKind::Equal ||
8110 DCK == DefaultedComparisonKind::ThreeWay) &&
8111 RD->hasVariantMembers()) {
8112 // C++2a [class.compare.default]p2 [P2002R0]:
8113 // A defaulted comparison operator function for class C is defined as
8114 // deleted if [...] C has variant members.
8115 if (Diagnose == ExplainDeleted) {
8116 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8117 << FD << RD->isUnion() << RD;
8118 }
8119 return Result::deleted();
8120 }
8121
8122 return Base::visit();
8123 }
8124
8125private:
8126 Subobject getCompleteObject() {
8127 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8128 }
8129
8130 Subobject getBase(CXXBaseSpecifier *Base) {
8131 return Subobject{.Kind: Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8132 .Loc: Base->getBaseTypeLoc()};
8133 }
8134
8135 Subobject getField(FieldDecl *Field) {
8136 return Subobject{Subobject::Member, Field, Field->getLocation()};
8137 }
8138
8139 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8140 // C++2a [class.compare.default]p2 [P2002R0]:
8141 // A defaulted <=> or == operator function for class C is defined as
8142 // deleted if any non-static data member of C is of reference type
8143 if (Type->isReferenceType()) {
8144 if (Diagnose == ExplainDeleted) {
8145 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8146 << FD << RD;
8147 }
8148 return Result::deleted();
8149 }
8150
8151 // [...] Let xi be an lvalue denoting the ith element [...]
8152 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8153 Expr *Args[] = {&Xi, &Xi};
8154
8155 // All operators start by trying to apply that same operator recursively.
8156 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8157 assert(OO != OO_None && "not an overloaded operator!");
8158 return visitBinaryOperator(OO, Args, Subobj);
8159 }
8160
8161 Result
8162 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8163 Subobject Subobj,
8164 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8165 // Note that there is no need to consider rewritten candidates here if
8166 // we've already found there is no viable 'operator<=>' candidate (and are
8167 // considering synthesizing a '<=>' from '==' and '<').
8168 OverloadCandidateSet CandidateSet(
8169 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8170 OverloadCandidateSet::OperatorRewriteInfo(
8171 OO, FD->getLocation(),
8172 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8173
8174 /// C++2a [class.compare.default]p1 [P2002R0]:
8175 /// [...] the defaulted function itself is never a candidate for overload
8176 /// resolution [...]
8177 CandidateSet.exclude(FD);
8178
8179 if (Args[0]->getType()->isOverloadableType())
8180 S.LookupOverloadedBinOp(CandidateSet, Op: OO, Fns, Args);
8181 else
8182 // FIXME: We determine whether this is a valid expression by checking to
8183 // see if there's a viable builtin operator candidate for it. That isn't
8184 // really what the rules ask us to do, but should give the right results.
8185 S.AddBuiltinOperatorCandidates(Op: OO, OpLoc: FD->getLocation(), Args, CandidateSet);
8186
8187 Result R;
8188
8189 OverloadCandidateSet::iterator Best;
8190 switch (CandidateSet.BestViableFunction(S, Loc: FD->getLocation(), Best)) {
8191 case OR_Success: {
8192 // C++2a [class.compare.secondary]p2 [P2002R0]:
8193 // The operator function [...] is defined as deleted if [...] the
8194 // candidate selected by overload resolution is not a rewritten
8195 // candidate.
8196 if ((DCK == DefaultedComparisonKind::NotEqual ||
8197 DCK == DefaultedComparisonKind::Relational) &&
8198 !Best->RewriteKind) {
8199 if (Diagnose == ExplainDeleted) {
8200 if (Best->Function) {
8201 S.Diag(Best->Function->getLocation(),
8202 diag::note_defaulted_comparison_not_rewritten_callee)
8203 << FD;
8204 } else {
8205 assert(Best->Conversions.size() == 2 &&
8206 Best->Conversions[0].isUserDefined() &&
8207 "non-user-defined conversion from class to built-in "
8208 "comparison");
8209 S.Diag(Best->Conversions[0]
8210 .UserDefined.FoundConversionFunction.getDecl()
8211 ->getLocation(),
8212 diag::note_defaulted_comparison_not_rewritten_conversion)
8213 << FD;
8214 }
8215 }
8216 return Result::deleted();
8217 }
8218
8219 // Throughout C++2a [class.compare]: if overload resolution does not
8220 // result in a usable function, the candidate function is defined as
8221 // deleted. This requires that we selected an accessible function.
8222 //
8223 // Note that this only considers the access of the function when named
8224 // within the type of the subobject, and not the access path for any
8225 // derived-to-base conversion.
8226 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8227 if (ArgClass && Best->FoundDecl.getDecl() &&
8228 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8229 QualType ObjectType = Subobj.Kind == Subobject::Member
8230 ? Args[0]->getType()
8231 : S.Context.getRecordType(RD);
8232 if (!S.isMemberAccessibleForDeletion(
8233 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8234 Diagnose == ExplainDeleted
8235 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8236 << FD << Subobj.Kind << Subobj.Decl
8237 : S.PDiag()))
8238 return Result::deleted();
8239 }
8240
8241 bool NeedsDeducing =
8242 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8243
8244 if (FunctionDecl *BestFD = Best->Function) {
8245 // C++2a [class.compare.default]p3 [P2002R0]:
8246 // A defaulted comparison function is constexpr-compatible if
8247 // [...] no overlod resolution performed [...] results in a
8248 // non-constexpr function.
8249 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8250 // If it's not constexpr, explain why not.
8251 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8252 if (Subobj.Kind != Subobject::CompleteObject)
8253 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8254 << Subobj.Kind << Subobj.Decl;
8255 S.Diag(BestFD->getLocation(),
8256 diag::note_defaulted_comparison_not_constexpr_here);
8257 // Bail out after explaining; we don't want any more notes.
8258 return Result::deleted();
8259 }
8260 R.Constexpr &= BestFD->isConstexpr();
8261
8262 if (NeedsDeducing) {
8263 // If any callee has an undeduced return type, deduce it now.
8264 // FIXME: It's not clear how a failure here should be handled. For
8265 // now, we produce an eager diagnostic, because that is forward
8266 // compatible with most (all?) other reasonable options.
8267 if (BestFD->getReturnType()->isUndeducedType() &&
8268 S.DeduceReturnType(FD: BestFD, Loc: FD->getLocation(),
8269 /*Diagnose=*/false)) {
8270 // Don't produce a duplicate error when asked to explain why the
8271 // comparison is deleted: we diagnosed that when initially checking
8272 // the defaulted operator.
8273 if (Diagnose == NoDiagnostics) {
8274 S.Diag(
8275 FD->getLocation(),
8276 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8277 << Subobj.Kind << Subobj.Decl;
8278 S.Diag(
8279 Subobj.Loc,
8280 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8281 << Subobj.Kind << Subobj.Decl;
8282 S.Diag(BestFD->getLocation(),
8283 diag::note_defaulted_comparison_cannot_deduce_callee)
8284 << Subobj.Kind << Subobj.Decl;
8285 }
8286 return Result::deleted();
8287 }
8288 auto *Info = S.Context.CompCategories.lookupInfoForType(
8289 Ty: BestFD->getCallResultType());
8290 if (!Info) {
8291 if (Diagnose == ExplainDeleted) {
8292 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8293 << Subobj.Kind << Subobj.Decl
8294 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8295 S.Diag(BestFD->getLocation(),
8296 diag::note_defaulted_comparison_cannot_deduce_callee)
8297 << Subobj.Kind << Subobj.Decl;
8298 }
8299 return Result::deleted();
8300 }
8301 R.Category = Info->Kind;
8302 }
8303 } else {
8304 QualType T = Best->BuiltinParamTypes[0];
8305 assert(T == Best->BuiltinParamTypes[1] &&
8306 "builtin comparison for different types?");
8307 assert(Best->BuiltinParamTypes[2].isNull() &&
8308 "invalid builtin comparison");
8309
8310 if (NeedsDeducing) {
8311 std::optional<ComparisonCategoryType> Cat =
8312 getComparisonCategoryForBuiltinCmp(T);
8313 assert(Cat && "no category for builtin comparison?");
8314 R.Category = *Cat;
8315 }
8316 }
8317
8318 // Note that we might be rewriting to a different operator. That call is
8319 // not considered until we come to actually build the comparison function.
8320 break;
8321 }
8322
8323 case OR_Ambiguous:
8324 if (Diagnose == ExplainDeleted) {
8325 unsigned Kind = 0;
8326 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8327 Kind = OO == OO_EqualEqual ? 1 : 2;
8328 CandidateSet.NoteCandidates(
8329 PartialDiagnosticAt(
8330 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8331 << FD << Kind << Subobj.Kind << Subobj.Decl),
8332 S, OCD_AmbiguousCandidates, Args);
8333 }
8334 R = Result::deleted();
8335 break;
8336
8337 case OR_Deleted:
8338 if (Diagnose == ExplainDeleted) {
8339 if ((DCK == DefaultedComparisonKind::NotEqual ||
8340 DCK == DefaultedComparisonKind::Relational) &&
8341 !Best->RewriteKind) {
8342 S.Diag(Best->Function->getLocation(),
8343 diag::note_defaulted_comparison_not_rewritten_callee)
8344 << FD;
8345 } else {
8346 S.Diag(Subobj.Loc,
8347 diag::note_defaulted_comparison_calls_deleted)
8348 << FD << Subobj.Kind << Subobj.Decl;
8349 S.NoteDeletedFunction(FD: Best->Function);
8350 }
8351 }
8352 R = Result::deleted();
8353 break;
8354
8355 case OR_No_Viable_Function:
8356 // If there's no usable candidate, we're done unless we can rewrite a
8357 // '<=>' in terms of '==' and '<'.
8358 if (OO == OO_Spaceship &&
8359 S.Context.CompCategories.lookupInfoForType(Ty: FD->getReturnType())) {
8360 // For any kind of comparison category return type, we need a usable
8361 // '==' and a usable '<'.
8362 if (!R.add(R: visitBinaryOperator(OO: OO_EqualEqual, Args, Subobj,
8363 SpaceshipCandidates: &CandidateSet)))
8364 R.add(R: visitBinaryOperator(OO: OO_Less, Args, Subobj, SpaceshipCandidates: &CandidateSet));
8365 break;
8366 }
8367
8368 if (Diagnose == ExplainDeleted) {
8369 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8370 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8371 << Subobj.Kind << Subobj.Decl;
8372
8373 // For a three-way comparison, list both the candidates for the
8374 // original operator and the candidates for the synthesized operator.
8375 if (SpaceshipCandidates) {
8376 SpaceshipCandidates->NoteCandidates(
8377 S, Args,
8378 SpaceshipCandidates->CompleteCandidates(S, OCD: OCD_AllCandidates,
8379 Args, OpLoc: FD->getLocation()));
8380 S.Diag(Subobj.Loc,
8381 diag::note_defaulted_comparison_no_viable_function_synthesized)
8382 << (OO == OO_EqualEqual ? 0 : 1);
8383 }
8384
8385 CandidateSet.NoteCandidates(
8386 S, Args,
8387 CandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
8388 OpLoc: FD->getLocation()));
8389 }
8390 R = Result::deleted();
8391 break;
8392 }
8393
8394 return R;
8395 }
8396};
8397
8398/// A list of statements.
8399struct StmtListResult {
8400 bool IsInvalid = false;
8401 llvm::SmallVector<Stmt*, 16> Stmts;
8402
8403 bool add(const StmtResult &S) {
8404 IsInvalid |= S.isInvalid();
8405 if (IsInvalid)
8406 return true;
8407 Stmts.push_back(Elt: S.get());
8408 return false;
8409 }
8410};
8411
8412/// A visitor over the notional body of a defaulted comparison that synthesizes
8413/// the actual body.
8414class DefaultedComparisonSynthesizer
8415 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8416 StmtListResult, StmtResult,
8417 std::pair<ExprResult, ExprResult>> {
8418 SourceLocation Loc;
8419 unsigned ArrayDepth = 0;
8420
8421public:
8422 using Base = DefaultedComparisonVisitor;
8423 using ExprPair = std::pair<ExprResult, ExprResult>;
8424
8425 friend Base;
8426
8427 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8428 DefaultedComparisonKind DCK,
8429 SourceLocation BodyLoc)
8430 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8431
8432 /// Build a suitable function body for this defaulted comparison operator.
8433 StmtResult build() {
8434 Sema::CompoundScopeRAII CompoundScope(S);
8435
8436 StmtListResult Stmts = visit();
8437 if (Stmts.IsInvalid)
8438 return StmtError();
8439
8440 ExprResult RetVal;
8441 switch (DCK) {
8442 case DefaultedComparisonKind::None:
8443 llvm_unreachable("not a defaulted comparison");
8444
8445 case DefaultedComparisonKind::Equal: {
8446 // C++2a [class.eq]p3:
8447 // [...] compar[e] the corresponding elements [...] until the first
8448 // index i where xi == yi yields [...] false. If no such index exists,
8449 // V is true. Otherwise, V is false.
8450 //
8451 // Join the comparisons with '&&'s and return the result. Use a right
8452 // fold (traversing the conditions right-to-left), because that
8453 // short-circuits more naturally.
8454 auto OldStmts = std::move(Stmts.Stmts);
8455 Stmts.Stmts.clear();
8456 ExprResult CmpSoFar;
8457 // Finish a particular comparison chain.
8458 auto FinishCmp = [&] {
8459 if (Expr *Prior = CmpSoFar.get()) {
8460 // Convert the last expression to 'return ...;'
8461 if (RetVal.isUnset() && Stmts.Stmts.empty())
8462 RetVal = CmpSoFar;
8463 // Convert any prior comparison to 'if (!(...)) return false;'
8464 else if (Stmts.add(S: buildIfNotCondReturnFalse(Cond: Prior)))
8465 return true;
8466 CmpSoFar = ExprResult();
8467 }
8468 return false;
8469 };
8470 for (Stmt *EAsStmt : llvm::reverse(C&: OldStmts)) {
8471 Expr *E = dyn_cast<Expr>(Val: EAsStmt);
8472 if (!E) {
8473 // Found an array comparison.
8474 if (FinishCmp() || Stmts.add(S: EAsStmt))
8475 return StmtError();
8476 continue;
8477 }
8478
8479 if (CmpSoFar.isUnset()) {
8480 CmpSoFar = E;
8481 continue;
8482 }
8483 CmpSoFar = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_LAnd, LHSExpr: E, RHSExpr: CmpSoFar.get());
8484 if (CmpSoFar.isInvalid())
8485 return StmtError();
8486 }
8487 if (FinishCmp())
8488 return StmtError();
8489 std::reverse(first: Stmts.Stmts.begin(), last: Stmts.Stmts.end());
8490 // If no such index exists, V is true.
8491 if (RetVal.isUnset())
8492 RetVal = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_true);
8493 break;
8494 }
8495
8496 case DefaultedComparisonKind::ThreeWay: {
8497 // Per C++2a [class.spaceship]p3, as a fallback add:
8498 // return static_cast<R>(std::strong_ordering::equal);
8499 QualType StrongOrdering = S.CheckComparisonCategoryType(
8500 Kind: ComparisonCategoryType::StrongOrdering, Loc,
8501 Usage: Sema::ComparisonCategoryUsage::DefaultedOperator);
8502 if (StrongOrdering.isNull())
8503 return StmtError();
8504 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(Ty: StrongOrdering)
8505 .getValueInfo(ValueKind: ComparisonCategoryResult::Equal)
8506 ->VD;
8507 RetVal = getDecl(EqualVD);
8508 if (RetVal.isInvalid())
8509 return StmtError();
8510 RetVal = buildStaticCastToR(E: RetVal.get());
8511 break;
8512 }
8513
8514 case DefaultedComparisonKind::NotEqual:
8515 case DefaultedComparisonKind::Relational:
8516 RetVal = cast<Expr>(Val: Stmts.Stmts.pop_back_val());
8517 break;
8518 }
8519
8520 // Build the final return statement.
8521 if (RetVal.isInvalid())
8522 return StmtError();
8523 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: RetVal.get());
8524 if (ReturnStmt.isInvalid())
8525 return StmtError();
8526 Stmts.Stmts.push_back(Elt: ReturnStmt.get());
8527
8528 return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts.Stmts, /*IsStmtExpr=*/isStmtExpr: false);
8529 }
8530
8531private:
8532 ExprResult getDecl(ValueDecl *VD) {
8533 return S.BuildDeclarationNameExpr(
8534 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8535 }
8536
8537 ExprResult getParam(unsigned I) {
8538 ParmVarDecl *PD = FD->getParamDecl(i: I);
8539 return getDecl(PD);
8540 }
8541
8542 ExprPair getCompleteObject() {
8543 unsigned Param = 0;
8544 ExprResult LHS;
8545 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
8546 MD && MD->isImplicitObjectMemberFunction()) {
8547 // LHS is '*this'.
8548 LHS = S.ActOnCXXThis(loc: Loc);
8549 if (!LHS.isInvalid())
8550 LHS = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: LHS.get());
8551 } else {
8552 LHS = getParam(I: Param++);
8553 }
8554 ExprResult RHS = getParam(I: Param++);
8555 assert(Param == FD->getNumParams());
8556 return {LHS, RHS};
8557 }
8558
8559 ExprPair getBase(CXXBaseSpecifier *Base) {
8560 ExprPair Obj = getCompleteObject();
8561 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8562 return {ExprError(), ExprError()};
8563 CXXCastPath Path = {Base};
8564 return {S.ImpCastExprToType(E: Obj.first.get(), Type: Base->getType(),
8565 CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path),
8566 S.ImpCastExprToType(E: Obj.second.get(), Type: Base->getType(),
8567 CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path)};
8568 }
8569
8570 ExprPair getField(FieldDecl *Field) {
8571 ExprPair Obj = getCompleteObject();
8572 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8573 return {ExprError(), ExprError()};
8574
8575 DeclAccessPair Found = DeclAccessPair::make(D: Field, AS: Field->getAccess());
8576 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8577 return {S.BuildFieldReferenceExpr(BaseExpr: Obj.first.get(), /*IsArrow=*/false, OpLoc: Loc,
8578 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo),
8579 S.BuildFieldReferenceExpr(BaseExpr: Obj.second.get(), /*IsArrow=*/false, OpLoc: Loc,
8580 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo)};
8581 }
8582
8583 // FIXME: When expanding a subobject, register a note in the code synthesis
8584 // stack to say which subobject we're comparing.
8585
8586 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8587 if (Cond.isInvalid())
8588 return StmtError();
8589
8590 ExprResult NotCond = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_LNot, InputExpr: Cond.get());
8591 if (NotCond.isInvalid())
8592 return StmtError();
8593
8594 ExprResult False = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_false);
8595 assert(!False.isInvalid() && "should never fail");
8596 StmtResult ReturnFalse = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: False.get());
8597 if (ReturnFalse.isInvalid())
8598 return StmtError();
8599
8600 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt: nullptr,
8601 Cond: S.ActOnCondition(S: nullptr, Loc, SubExpr: NotCond.get(),
8602 CK: Sema::ConditionKind::Boolean),
8603 RParenLoc: Loc, ThenVal: ReturnFalse.get(), ElseLoc: SourceLocation(), ElseVal: nullptr);
8604 }
8605
8606 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8607 ExprPair Subobj) {
8608 QualType SizeType = S.Context.getSizeType();
8609 Size = Size.zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
8610
8611 // Build 'size_t i$n = 0'.
8612 IdentifierInfo *IterationVarName = nullptr;
8613 {
8614 SmallString<8> Str;
8615 llvm::raw_svector_ostream OS(Str);
8616 OS << "i" << ArrayDepth;
8617 IterationVarName = &S.Context.Idents.get(Name: OS.str());
8618 }
8619 VarDecl *IterationVar = VarDecl::Create(
8620 C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: IterationVarName, T: SizeType,
8621 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), S: SC_None);
8622 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
8623 IterationVar->setInit(
8624 IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
8625 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8626
8627 auto IterRef = [&] {
8628 ExprResult Ref = S.BuildDeclarationNameExpr(
8629 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8630 IterationVar);
8631 assert(!Ref.isInvalid() && "can't reference our own variable?");
8632 return Ref.get();
8633 };
8634
8635 // Build 'i$n != Size'.
8636 ExprResult Cond = S.CreateBuiltinBinOp(
8637 OpLoc: Loc, Opc: BO_NE, LHSExpr: IterRef(),
8638 RHSExpr: IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc));
8639 assert(!Cond.isInvalid() && "should never fail");
8640
8641 // Build '++i$n'.
8642 ExprResult Inc = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_PreInc, InputExpr: IterRef());
8643 assert(!Inc.isInvalid() && "should never fail");
8644
8645 // Build 'a[i$n]' and 'b[i$n]'.
8646 auto Index = [&](ExprResult E) {
8647 if (E.isInvalid())
8648 return ExprError();
8649 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8650 };
8651 Subobj.first = Index(Subobj.first);
8652 Subobj.second = Index(Subobj.second);
8653
8654 // Compare the array elements.
8655 ++ArrayDepth;
8656 StmtResult Substmt = visitSubobject(Type, Subobj);
8657 --ArrayDepth;
8658
8659 if (Substmt.isInvalid())
8660 return StmtError();
8661
8662 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8663 // For outer levels or for an 'operator<=>' we already have a suitable
8664 // statement that returns as necessary.
8665 if (Expr *ElemCmp = dyn_cast<Expr>(Val: Substmt.get())) {
8666 assert(DCK == DefaultedComparisonKind::Equal &&
8667 "should have non-expression statement");
8668 Substmt = buildIfNotCondReturnFalse(Cond: ElemCmp);
8669 if (Substmt.isInvalid())
8670 return StmtError();
8671 }
8672
8673 // Build 'for (...) ...'
8674 return S.ActOnForStmt(ForLoc: Loc, LParenLoc: Loc, First: Init,
8675 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Cond.get(),
8676 CK: Sema::ConditionKind::Boolean),
8677 Third: S.MakeFullDiscardedValueExpr(Arg: Inc.get()), RParenLoc: Loc,
8678 Body: Substmt.get());
8679 }
8680
8681 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8682 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8683 return StmtError();
8684
8685 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8686 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8687 ExprResult Op;
8688 if (Type->isOverloadableType())
8689 Op = S.CreateOverloadedBinOp(OpLoc: Loc, Opc, Fns, LHS: Obj.first.get(),
8690 RHS: Obj.second.get(), /*PerformADL=*/RequiresADL: true,
8691 /*AllowRewrittenCandidates=*/true, DefaultedFn: FD);
8692 else
8693 Op = S.CreateBuiltinBinOp(OpLoc: Loc, Opc, LHSExpr: Obj.first.get(), RHSExpr: Obj.second.get());
8694 if (Op.isInvalid())
8695 return StmtError();
8696
8697 switch (DCK) {
8698 case DefaultedComparisonKind::None:
8699 llvm_unreachable("not a defaulted comparison");
8700
8701 case DefaultedComparisonKind::Equal:
8702 // Per C++2a [class.eq]p2, each comparison is individually contextually
8703 // converted to bool.
8704 Op = S.PerformContextuallyConvertToBool(From: Op.get());
8705 if (Op.isInvalid())
8706 return StmtError();
8707 return Op.get();
8708
8709 case DefaultedComparisonKind::ThreeWay: {
8710 // Per C++2a [class.spaceship]p3, form:
8711 // if (R cmp = static_cast<R>(op); cmp != 0)
8712 // return cmp;
8713 QualType R = FD->getReturnType();
8714 Op = buildStaticCastToR(E: Op.get());
8715 if (Op.isInvalid())
8716 return StmtError();
8717
8718 // R cmp = ...;
8719 IdentifierInfo *Name = &S.Context.Idents.get(Name: "cmp");
8720 VarDecl *VD =
8721 VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: Name, T: R,
8722 TInfo: S.Context.getTrivialTypeSourceInfo(T: R, Loc), S: SC_None);
8723 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8724 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8725
8726 // cmp != 0
8727 ExprResult VDRef = getDecl(VD);
8728 if (VDRef.isInvalid())
8729 return StmtError();
8730 llvm::APInt ZeroVal(S.Context.getIntWidth(T: S.Context.IntTy), 0);
8731 Expr *Zero =
8732 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8733 ExprResult Comp;
8734 if (VDRef.get()->getType()->isOverloadableType())
8735 Comp = S.CreateOverloadedBinOp(OpLoc: Loc, Opc: BO_NE, Fns, LHS: VDRef.get(), RHS: Zero, RequiresADL: true,
8736 AllowRewrittenCandidates: true, DefaultedFn: FD);
8737 else
8738 Comp = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_NE, LHSExpr: VDRef.get(), RHSExpr: Zero);
8739 if (Comp.isInvalid())
8740 return StmtError();
8741 Sema::ConditionResult Cond = S.ActOnCondition(
8742 S: nullptr, Loc, SubExpr: Comp.get(), CK: Sema::ConditionKind::Boolean);
8743 if (Cond.isInvalid())
8744 return StmtError();
8745
8746 // return cmp;
8747 VDRef = getDecl(VD);
8748 if (VDRef.isInvalid())
8749 return StmtError();
8750 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: VDRef.get());
8751 if (ReturnStmt.isInvalid())
8752 return StmtError();
8753
8754 // if (...)
8755 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt, Cond,
8756 RParenLoc: Loc, ThenVal: ReturnStmt.get(),
8757 /*ElseLoc=*/SourceLocation(), /*Else=*/ElseVal: nullptr);
8758 }
8759
8760 case DefaultedComparisonKind::NotEqual:
8761 case DefaultedComparisonKind::Relational:
8762 // C++2a [class.compare.secondary]p2:
8763 // Otherwise, the operator function yields x @ y.
8764 return Op.get();
8765 }
8766 llvm_unreachable("");
8767 }
8768
8769 /// Build "static_cast<R>(E)".
8770 ExprResult buildStaticCastToR(Expr *E) {
8771 QualType R = FD->getReturnType();
8772 assert(!R->isUndeducedType() && "type should have been deduced already");
8773
8774 // Don't bother forming a no-op cast in the common case.
8775 if (E->isPRValue() && S.Context.hasSameType(T1: E->getType(), T2: R))
8776 return E;
8777 return S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast,
8778 Ty: S.Context.getTrivialTypeSourceInfo(T: R, Loc), E,
8779 AngleBrackets: SourceRange(Loc, Loc), Parens: SourceRange(Loc, Loc));
8780 }
8781};
8782}
8783
8784/// Perform the unqualified lookups that might be needed to form a defaulted
8785/// comparison function for the given operator.
8786static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8787 UnresolvedSetImpl &Operators,
8788 OverloadedOperatorKind Op) {
8789 auto Lookup = [&](OverloadedOperatorKind OO) {
8790 Self.LookupOverloadedOperatorName(Op: OO, S, Functions&: Operators);
8791 };
8792
8793 // Every defaulted operator looks up itself.
8794 Lookup(Op);
8795 // ... and the rewritten form of itself, if any.
8796 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: Op))
8797 Lookup(ExtraOp);
8798
8799 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8800 // synthesize a three-way comparison from '<' and '=='. In a dependent
8801 // context, we also need to look up '==' in case we implicitly declare a
8802 // defaulted 'operator=='.
8803 if (Op == OO_Spaceship) {
8804 Lookup(OO_ExclaimEqual);
8805 Lookup(OO_Less);
8806 Lookup(OO_EqualEqual);
8807 }
8808}
8809
8810bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8811 DefaultedComparisonKind DCK) {
8812 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8813
8814 // Perform any unqualified lookups we're going to need to default this
8815 // function.
8816 if (S) {
8817 UnresolvedSet<32> Operators;
8818 lookupOperatorsForDefaultedComparison(Self&: *this, S, Operators,
8819 Op: FD->getOverloadedOperator());
8820 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8821 Context, Lookups: Operators.pairs()));
8822 }
8823
8824 // C++2a [class.compare.default]p1:
8825 // A defaulted comparison operator function for some class C shall be a
8826 // non-template function declared in the member-specification of C that is
8827 // -- a non-static const non-volatile member of C having one parameter of
8828 // type const C& and either no ref-qualifier or the ref-qualifier &, or
8829 // -- a friend of C having two parameters of type const C& or two
8830 // parameters of type C.
8831
8832 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8833 bool IsMethod = isa<CXXMethodDecl>(Val: FD);
8834 if (IsMethod) {
8835 auto *MD = cast<CXXMethodDecl>(Val: FD);
8836 assert(!MD->isStatic() && "comparison function cannot be a static member");
8837
8838 if (MD->getRefQualifier() == RQ_RValue) {
8839 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8840
8841 // Remove the ref qualifier to recover.
8842 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8843 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8844 EPI.RefQualifier = RQ_None;
8845 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
8846 Args: FPT->getParamTypes(), EPI));
8847 }
8848
8849 // If we're out-of-class, this is the class we're comparing.
8850 if (!RD)
8851 RD = MD->getParent();
8852 QualType T = MD->getFunctionObjectParameterType();
8853 if (!T.isConstQualified()) {
8854 SourceLocation Loc, InsertLoc;
8855 if (MD->isExplicitObjectMemberFunction()) {
8856 Loc = MD->getParamDecl(0)->getBeginLoc();
8857 InsertLoc = getLocForEndOfToken(
8858 Loc: MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
8859 } else {
8860 Loc = MD->getLocation();
8861 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8862 InsertLoc = Loc.getRParenLoc();
8863 }
8864 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8865 // corresponding defaulted 'operator<=>' already.
8866 if (!MD->isImplicit()) {
8867 Diag(Loc, diag::err_defaulted_comparison_non_const)
8868 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8869 }
8870
8871 // Add the 'const' to the type to recover.
8872 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8873 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8874 EPI.TypeQuals.addConst();
8875 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
8876 Args: FPT->getParamTypes(), EPI));
8877 }
8878
8879 if (MD->isVolatile()) {
8880 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8881
8882 // Remove the 'volatile' from the type to recover.
8883 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8884 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8885 EPI.TypeQuals.removeVolatile();
8886 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
8887 Args: FPT->getParamTypes(), EPI));
8888 }
8889 }
8890
8891 if ((FD->getNumParams() -
8892 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8893 (IsMethod ? 1 : 2)) {
8894 // Let's not worry about using a variadic template pack here -- who would do
8895 // such a thing?
8896 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8897 << int(IsMethod) << int(DCK);
8898 return true;
8899 }
8900
8901 const ParmVarDecl *KnownParm = nullptr;
8902 for (const ParmVarDecl *Param : FD->parameters()) {
8903 if (Param->isExplicitObjectParameter())
8904 continue;
8905 QualType ParmTy = Param->getType();
8906
8907 if (!KnownParm) {
8908 auto CTy = ParmTy;
8909 // Is it `T const &`?
8910 bool Ok = !IsMethod;
8911 QualType ExpectedTy;
8912 if (RD)
8913 ExpectedTy = Context.getRecordType(RD);
8914 if (auto *Ref = CTy->getAs<ReferenceType>()) {
8915 CTy = Ref->getPointeeType();
8916 if (RD)
8917 ExpectedTy.addConst();
8918 Ok = true;
8919 }
8920
8921 // Is T a class?
8922 if (!Ok) {
8923 } else if (RD) {
8924 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8925 Ok = false;
8926 } else if (auto *CRD = CTy->getAsRecordDecl()) {
8927 RD = cast<CXXRecordDecl>(CRD);
8928 } else {
8929 Ok = false;
8930 }
8931
8932 if (Ok) {
8933 KnownParm = Param;
8934 } else {
8935 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8936 // corresponding defaulted 'operator<=>' already.
8937 if (!FD->isImplicit()) {
8938 if (RD) {
8939 QualType PlainTy = Context.getRecordType(RD);
8940 QualType RefTy =
8941 Context.getLValueReferenceType(T: PlainTy.withConst());
8942 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8943 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8944 << Param->getSourceRange();
8945 } else {
8946 assert(!IsMethod && "should know expected type for method");
8947 Diag(FD->getLocation(),
8948 diag::err_defaulted_comparison_param_unknown)
8949 << int(DCK) << ParmTy << Param->getSourceRange();
8950 }
8951 }
8952 return true;
8953 }
8954 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8955 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8956 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8957 << ParmTy << Param->getSourceRange();
8958 return true;
8959 }
8960 }
8961
8962 assert(RD && "must have determined class");
8963 if (IsMethod) {
8964 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8965 // In-class, must be a friend decl.
8966 assert(FD->getFriendObjectKind() && "expected a friend declaration");
8967 } else {
8968 // Out of class, require the defaulted comparison to be a friend (of a
8969 // complete type).
8970 if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8971 diag::err_defaulted_comparison_not_friend, int(DCK),
8972 int(1)))
8973 return true;
8974
8975 if (llvm::none_of(Range: RD->friends(), P: [&](const FriendDecl *F) {
8976 return FD->getCanonicalDecl() ==
8977 F->getFriendDecl()->getCanonicalDecl();
8978 })) {
8979 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8980 << int(DCK) << int(0) << RD;
8981 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8982 return true;
8983 }
8984 }
8985
8986 // C++2a [class.eq]p1, [class.rel]p1:
8987 // A [defaulted comparison other than <=>] shall have a declared return
8988 // type bool.
8989 if (DCK != DefaultedComparisonKind::ThreeWay &&
8990 !FD->getDeclaredReturnType()->isDependentType() &&
8991 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8992 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8993 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8994 << FD->getReturnTypeSourceRange();
8995 return true;
8996 }
8997 // C++2a [class.spaceship]p2 [P2002R0]:
8998 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8999 // R shall not contain a placeholder type.
9000 if (QualType RT = FD->getDeclaredReturnType();
9001 DCK == DefaultedComparisonKind::ThreeWay &&
9002 RT->getContainedDeducedType() &&
9003 (!Context.hasSameType(T1: RT, T2: Context.getAutoDeductType()) ||
9004 RT->getContainedAutoType()->isConstrained())) {
9005 Diag(FD->getLocation(),
9006 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9007 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9008 << FD->getReturnTypeSourceRange();
9009 return true;
9010 }
9011
9012 // For a defaulted function in a dependent class, defer all remaining checks
9013 // until instantiation.
9014 if (RD->isDependentType())
9015 return false;
9016
9017 // Determine whether the function should be defined as deleted.
9018 DefaultedComparisonInfo Info =
9019 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9020
9021 bool First = FD == FD->getCanonicalDecl();
9022
9023 if (!First) {
9024 if (Info.Deleted) {
9025 // C++11 [dcl.fct.def.default]p4:
9026 // [For a] user-provided explicitly-defaulted function [...] if such a
9027 // function is implicitly defined as deleted, the program is ill-formed.
9028 //
9029 // This is really just a consequence of the general rule that you can
9030 // only delete a function on its first declaration.
9031 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9032 << FD->isImplicit() << (int)DCK;
9033 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9034 DefaultedComparisonAnalyzer::ExplainDeleted)
9035 .visit();
9036 return true;
9037 }
9038 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9039 // C++20 [class.compare.default]p1:
9040 // [...] A definition of a comparison operator as defaulted that appears
9041 // in a class shall be the first declaration of that function.
9042 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9043 << (int)DCK;
9044 Diag(FD->getCanonicalDecl()->getLocation(),
9045 diag::note_previous_declaration);
9046 return true;
9047 }
9048 }
9049
9050 // If we want to delete the function, then do so; there's nothing else to
9051 // check in that case.
9052 if (Info.Deleted) {
9053 SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation());
9054 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9055 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9056 << (int)DCK;
9057 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9058 DefaultedComparisonAnalyzer::ExplainDeleted)
9059 .visit();
9060 if (FD->getDefaultLoc().isValid())
9061 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9062 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9063 }
9064 return false;
9065 }
9066
9067 // C++2a [class.spaceship]p2:
9068 // The return type is deduced as the common comparison type of R0, R1, ...
9069 if (DCK == DefaultedComparisonKind::ThreeWay &&
9070 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9071 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9072 if (RetLoc.isInvalid())
9073 RetLoc = FD->getBeginLoc();
9074 // FIXME: Should we really care whether we have the complete type and the
9075 // 'enumerator' constants here? A forward declaration seems sufficient.
9076 QualType Cat = CheckComparisonCategoryType(
9077 Kind: Info.Category, Loc: RetLoc, Usage: ComparisonCategoryUsage::DefaultedOperator);
9078 if (Cat.isNull())
9079 return true;
9080 Context.adjustDeducedFunctionResultType(
9081 FD, ResultType: SubstAutoType(TypeWithAuto: FD->getDeclaredReturnType(), Replacement: Cat));
9082 }
9083
9084 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9085 // An explicitly-defaulted function that is not defined as deleted may be
9086 // declared constexpr or consteval only if it is constexpr-compatible.
9087 // C++2a [class.compare.default]p3 [P2002R0]:
9088 // A defaulted comparison function is constexpr-compatible if it satisfies
9089 // the requirements for a constexpr function [...]
9090 // The only relevant requirements are that the parameter and return types are
9091 // literal types. The remaining conditions are checked by the analyzer.
9092 //
9093 // We support P2448R2 in language modes earlier than C++23 as an extension.
9094 // The concept of constexpr-compatible was removed.
9095 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9096 // A function explicitly defaulted on its first declaration is implicitly
9097 // inline, and is implicitly constexpr if it is constexpr-suitable.
9098 // C++23 [dcl.constexpr]p3
9099 // A function is constexpr-suitable if
9100 // - it is not a coroutine, and
9101 // - if the function is a constructor or destructor, its class does not
9102 // have any virtual base classes.
9103 if (FD->isConstexpr()) {
9104 if (CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9105 CheckConstexprParameterTypes(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9106 !Info.Constexpr) {
9107 Diag(FD->getBeginLoc(),
9108 getLangOpts().CPlusPlus23
9109 ? diag::warn_cxx23_compat_defaulted_comparison_constexpr_mismatch
9110 : diag::ext_defaulted_comparison_constexpr_mismatch)
9111 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9112 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9113 DefaultedComparisonAnalyzer::ExplainConstexpr)
9114 .visit();
9115 }
9116 }
9117
9118 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9119 // If a constexpr-compatible function is explicitly defaulted on its first
9120 // declaration, it is implicitly considered to be constexpr.
9121 // FIXME: Only applying this to the first declaration seems problematic, as
9122 // simple reorderings can affect the meaning of the program.
9123 if (First && !FD->isConstexpr() && Info.Constexpr)
9124 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9125
9126 // C++2a [except.spec]p3:
9127 // If a declaration of a function does not have a noexcept-specifier
9128 // [and] is defaulted on its first declaration, [...] the exception
9129 // specification is as specified below
9130 if (FD->getExceptionSpecType() == EST_None) {
9131 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9132 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9133 EPI.ExceptionSpec.Type = EST_Unevaluated;
9134 EPI.ExceptionSpec.SourceDecl = FD;
9135 FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9136 Args: FPT->getParamTypes(), EPI));
9137 }
9138
9139 return false;
9140}
9141
9142void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9143 FunctionDecl *Spaceship) {
9144 Sema::CodeSynthesisContext Ctx;
9145 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9146 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9147 Ctx.Entity = Spaceship;
9148 pushCodeSynthesisContext(Ctx);
9149
9150 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9151 EqualEqual->setImplicit();
9152
9153 popCodeSynthesisContext();
9154}
9155
9156void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9157 DefaultedComparisonKind DCK) {
9158 assert(FD->isDefaulted() && !FD->isDeleted() &&
9159 !FD->doesThisDeclarationHaveABody());
9160 if (FD->willHaveBody() || FD->isInvalidDecl())
9161 return;
9162
9163 SynthesizedFunctionScope Scope(*this, FD);
9164
9165 // Add a context note for diagnostics produced after this point.
9166 Scope.addContextNote(UseLoc);
9167
9168 {
9169 // Build and set up the function body.
9170 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9171 // the type of the class being compared.
9172 auto PT = FD->getParamDecl(i: 0)->getType();
9173 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9174 SourceLocation BodyLoc =
9175 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9176 StmtResult Body =
9177 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9178 if (Body.isInvalid()) {
9179 FD->setInvalidDecl();
9180 return;
9181 }
9182 FD->setBody(Body.get());
9183 FD->markUsed(Context);
9184 }
9185
9186 // The exception specification is needed because we are defining the
9187 // function. Note that this will reuse the body we just built.
9188 ResolveExceptionSpec(Loc: UseLoc, FPT: FD->getType()->castAs<FunctionProtoType>());
9189
9190 if (ASTMutationListener *L = getASTMutationListener())
9191 L->CompletedImplicitDefinition(D: FD);
9192}
9193
9194static Sema::ImplicitExceptionSpecification
9195ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9196 FunctionDecl *FD,
9197 Sema::DefaultedComparisonKind DCK) {
9198 ComputingExceptionSpec CES(S, FD, Loc);
9199 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9200
9201 if (FD->isInvalidDecl())
9202 return ExceptSpec;
9203
9204 // The common case is that we just defined the comparison function. In that
9205 // case, just look at whether the body can throw.
9206 if (FD->hasBody()) {
9207 ExceptSpec.CalledStmt(S: FD->getBody());
9208 } else {
9209 // Otherwise, build a body so we can check it. This should ideally only
9210 // happen when we're not actually marking the function referenced. (This is
9211 // only really important for efficiency: we don't want to build and throw
9212 // away bodies for comparison functions more than we strictly need to.)
9213
9214 // Pretend to synthesize the function body in an unevaluated context.
9215 // Note that we can't actually just go ahead and define the function here:
9216 // we are not permitted to mark its callees as referenced.
9217 Sema::SynthesizedFunctionScope Scope(S, FD);
9218 EnterExpressionEvaluationContext Context(
9219 S, Sema::ExpressionEvaluationContext::Unevaluated);
9220
9221 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
9222 SourceLocation BodyLoc =
9223 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9224 StmtResult Body =
9225 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9226 if (!Body.isInvalid())
9227 ExceptSpec.CalledStmt(S: Body.get());
9228
9229 // FIXME: Can we hold onto this body and just transform it to potentially
9230 // evaluated when we're asked to define the function rather than rebuilding
9231 // it? Either that, or we should only build the bits of the body that we
9232 // need (the expressions, not the statements).
9233 }
9234
9235 return ExceptSpec;
9236}
9237
9238void Sema::CheckDelayedMemberExceptionSpecs() {
9239 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9240 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9241
9242 std::swap(LHS&: Overriding, RHS&: DelayedOverridingExceptionSpecChecks);
9243 std::swap(LHS&: Equivalent, RHS&: DelayedEquivalentExceptionSpecChecks);
9244
9245 // Perform any deferred checking of exception specifications for virtual
9246 // destructors.
9247 for (auto &Check : Overriding)
9248 CheckOverridingFunctionExceptionSpec(New: Check.first, Old: Check.second);
9249
9250 // Perform any deferred checking of exception specifications for befriended
9251 // special members.
9252 for (auto &Check : Equivalent)
9253 CheckEquivalentExceptionSpec(Old: Check.second, New: Check.first);
9254}
9255
9256namespace {
9257/// CRTP base class for visiting operations performed by a special member
9258/// function (or inherited constructor).
9259template<typename Derived>
9260struct SpecialMemberVisitor {
9261 Sema &S;
9262 CXXMethodDecl *MD;
9263 Sema::CXXSpecialMember CSM;
9264 Sema::InheritedConstructorInfo *ICI;
9265
9266 // Properties of the special member, computed for convenience.
9267 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9268
9269 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
9270 Sema::InheritedConstructorInfo *ICI)
9271 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9272 switch (CSM) {
9273 case Sema::CXXDefaultConstructor:
9274 case Sema::CXXCopyConstructor:
9275 case Sema::CXXMoveConstructor:
9276 IsConstructor = true;
9277 break;
9278 case Sema::CXXCopyAssignment:
9279 case Sema::CXXMoveAssignment:
9280 IsAssignment = true;
9281 break;
9282 case Sema::CXXDestructor:
9283 break;
9284 case Sema::CXXInvalid:
9285 llvm_unreachable("invalid special member kind");
9286 }
9287
9288 if (MD->getNumExplicitParams()) {
9289 if (const ReferenceType *RT =
9290 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9291 ConstArg = RT->getPointeeType().isConstQualified();
9292 }
9293 }
9294
9295 Derived &getDerived() { return static_cast<Derived&>(*this); }
9296
9297 /// Is this a "move" special member?
9298 bool isMove() const {
9299 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
9300 }
9301
9302 /// Look up the corresponding special member in the given class.
9303 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9304 unsigned Quals, bool IsMutable) {
9305 return lookupCallFromSpecialMember(S, Class, CSM, FieldQuals: Quals,
9306 ConstRHS: ConstArg && !IsMutable);
9307 }
9308
9309 /// Look up the constructor for the specified base class to see if it's
9310 /// overridden due to this being an inherited constructor.
9311 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9312 if (!ICI)
9313 return {};
9314 assert(CSM == Sema::CXXDefaultConstructor);
9315 auto *BaseCtor =
9316 cast<CXXConstructorDecl>(Val: MD)->getInheritedConstructor().getConstructor();
9317 if (auto *MD = ICI->findConstructorForBase(Base: Class, Ctor: BaseCtor).first)
9318 return MD;
9319 return {};
9320 }
9321
9322 /// A base or member subobject.
9323 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9324
9325 /// Get the location to use for a subobject in diagnostics.
9326 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9327 // FIXME: For an indirect virtual base, the direct base leading to
9328 // the indirect virtual base would be a more useful choice.
9329 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9330 return B->getBaseTypeLoc();
9331 else
9332 return Subobj.get<FieldDecl*>()->getLocation();
9333 }
9334
9335 enum BasesToVisit {
9336 /// Visit all non-virtual (direct) bases.
9337 VisitNonVirtualBases,
9338 /// Visit all direct bases, virtual or not.
9339 VisitDirectBases,
9340 /// Visit all non-virtual bases, and all virtual bases if the class
9341 /// is not abstract.
9342 VisitPotentiallyConstructedBases,
9343 /// Visit all direct or virtual bases.
9344 VisitAllBases
9345 };
9346
9347 // Visit the bases and members of the class.
9348 bool visit(BasesToVisit Bases) {
9349 CXXRecordDecl *RD = MD->getParent();
9350
9351 if (Bases == VisitPotentiallyConstructedBases)
9352 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9353
9354 for (auto &B : RD->bases())
9355 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9356 getDerived().visitBase(&B))
9357 return true;
9358
9359 if (Bases == VisitAllBases)
9360 for (auto &B : RD->vbases())
9361 if (getDerived().visitBase(&B))
9362 return true;
9363
9364 for (auto *F : RD->fields())
9365 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
9366 getDerived().visitField(F))
9367 return true;
9368
9369 return false;
9370 }
9371};
9372}
9373
9374namespace {
9375struct SpecialMemberDeletionInfo
9376 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9377 bool Diagnose;
9378
9379 SourceLocation Loc;
9380
9381 bool AllFieldsAreConst;
9382
9383 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9384 Sema::CXXSpecialMember CSM,
9385 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9386 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9387 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9388
9389 bool inUnion() const { return MD->getParent()->isUnion(); }
9390
9391 Sema::CXXSpecialMember getEffectiveCSM() {
9392 return ICI ? Sema::CXXInvalid : CSM;
9393 }
9394
9395 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9396
9397 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9398 bool visitField(FieldDecl *Field) { return shouldDeleteForField(FD: Field); }
9399
9400 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9401 bool shouldDeleteForField(FieldDecl *FD);
9402 bool shouldDeleteForAllConstMembers();
9403
9404 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9405 unsigned Quals);
9406 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9407 Sema::SpecialMemberOverloadResult SMOR,
9408 bool IsDtorCallInCtor);
9409
9410 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9411};
9412}
9413
9414/// Is the given special member inaccessible when used on the given
9415/// sub-object.
9416bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9417 CXXMethodDecl *target) {
9418 /// If we're operating on a base class, the object type is the
9419 /// type of this special member.
9420 QualType objectTy;
9421 AccessSpecifier access = target->getAccess();
9422 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9423 objectTy = S.Context.getTypeDeclType(MD->getParent());
9424 access = CXXRecordDecl::MergeAccess(PathAccess: base->getAccessSpecifier(), DeclAccess: access);
9425
9426 // If we're operating on a field, the object type is the type of the field.
9427 } else {
9428 objectTy = S.Context.getTypeDeclType(target->getParent());
9429 }
9430
9431 return S.isMemberAccessibleForDeletion(
9432 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9433}
9434
9435/// Check whether we should delete a special member due to the implicit
9436/// definition containing a call to a special member of a subobject.
9437bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9438 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9439 bool IsDtorCallInCtor) {
9440 CXXMethodDecl *Decl = SMOR.getMethod();
9441 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9442
9443 int DiagKind = -1;
9444
9445 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9446 DiagKind = !Decl ? 0 : 1;
9447 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9448 DiagKind = 2;
9449 else if (!isAccessible(Subobj, target: Decl))
9450 DiagKind = 3;
9451 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9452 !Decl->isTrivial()) {
9453 // A member of a union must have a trivial corresponding special member.
9454 // As a weird special case, a destructor call from a union's constructor
9455 // must be accessible and non-deleted, but need not be trivial. Such a
9456 // destructor is never actually called, but is semantically checked as
9457 // if it were.
9458 if (CSM == Sema::CXXDefaultConstructor) {
9459 // [class.default.ctor]p2:
9460 // A defaulted default constructor for class X is defined as deleted if
9461 // - X is a union that has a variant member with a non-trivial default
9462 // constructor and no variant member of X has a default member
9463 // initializer
9464 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9465 if (!RD->hasInClassInitializer())
9466 DiagKind = 4;
9467 } else {
9468 DiagKind = 4;
9469 }
9470 }
9471
9472 if (DiagKind == -1)
9473 return false;
9474
9475 if (Diagnose) {
9476 if (Field) {
9477 S.Diag(Field->getLocation(),
9478 diag::note_deleted_special_member_class_subobject)
9479 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9480 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9481 } else {
9482 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9483 S.Diag(Base->getBeginLoc(),
9484 diag::note_deleted_special_member_class_subobject)
9485 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9486 << Base->getType() << DiagKind << IsDtorCallInCtor
9487 << /*IsObjCPtr*/false;
9488 }
9489
9490 if (DiagKind == 1)
9491 S.NoteDeletedFunction(Decl);
9492 // FIXME: Explain inaccessibility if DiagKind == 3.
9493 }
9494
9495 return true;
9496}
9497
9498/// Check whether we should delete a special member function due to having a
9499/// direct or virtual base class or non-static data member of class type M.
9500bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9501 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9502 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9503 bool IsMutable = Field && Field->isMutable();
9504
9505 // C++11 [class.ctor]p5:
9506 // -- any direct or virtual base class, or non-static data member with no
9507 // brace-or-equal-initializer, has class type M (or array thereof) and
9508 // either M has no default constructor or overload resolution as applied
9509 // to M's default constructor results in an ambiguity or in a function
9510 // that is deleted or inaccessible
9511 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9512 // -- a direct or virtual base class B that cannot be copied/moved because
9513 // overload resolution, as applied to B's corresponding special member,
9514 // results in an ambiguity or a function that is deleted or inaccessible
9515 // from the defaulted special member
9516 // C++11 [class.dtor]p5:
9517 // -- any direct or virtual base class [...] has a type with a destructor
9518 // that is deleted or inaccessible
9519 if (!(CSM == Sema::CXXDefaultConstructor &&
9520 Field && Field->hasInClassInitializer()) &&
9521 shouldDeleteForSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable),
9522 IsDtorCallInCtor: false))
9523 return true;
9524
9525 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9526 // -- any direct or virtual base class or non-static data member has a
9527 // type with a destructor that is deleted or inaccessible
9528 if (IsConstructor) {
9529 Sema::SpecialMemberOverloadResult SMOR =
9530 S.LookupSpecialMember(D: Class, SM: Sema::CXXDestructor,
9531 ConstArg: false, VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false);
9532 if (shouldDeleteForSubobjectCall(Subobj, SMOR, IsDtorCallInCtor: true))
9533 return true;
9534 }
9535
9536 return false;
9537}
9538
9539bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9540 FieldDecl *FD, QualType FieldType) {
9541 // The defaulted special functions are defined as deleted if this is a variant
9542 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9543 // type under ARC.
9544 if (!FieldType.hasNonTrivialObjCLifetime())
9545 return false;
9546
9547 // Don't make the defaulted default constructor defined as deleted if the
9548 // member has an in-class initializer.
9549 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9550 return false;
9551
9552 if (Diagnose) {
9553 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9554 S.Diag(FD->getLocation(),
9555 diag::note_deleted_special_member_class_subobject)
9556 << getEffectiveCSM() << ParentClass << /*IsField*/true
9557 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9558 }
9559
9560 return true;
9561}
9562
9563/// Check whether we should delete a special member function due to the class
9564/// having a particular direct or virtual base class.
9565bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9566 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9567 // If program is correct, BaseClass cannot be null, but if it is, the error
9568 // must be reported elsewhere.
9569 if (!BaseClass)
9570 return false;
9571 // If we have an inheriting constructor, check whether we're calling an
9572 // inherited constructor instead of a default constructor.
9573 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
9574 if (auto *BaseCtor = SMOR.getMethod()) {
9575 // Note that we do not check access along this path; other than that,
9576 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9577 // FIXME: Check that the base has a usable destructor! Sink this into
9578 // shouldDeleteForClassSubobject.
9579 if (BaseCtor->isDeleted() && Diagnose) {
9580 S.Diag(Base->getBeginLoc(),
9581 diag::note_deleted_special_member_class_subobject)
9582 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9583 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9584 << /*IsObjCPtr*/false;
9585 S.NoteDeletedFunction(BaseCtor);
9586 }
9587 return BaseCtor->isDeleted();
9588 }
9589 return shouldDeleteForClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
9590}
9591
9592/// Check whether we should delete a special member function due to the class
9593/// having a particular non-static data member.
9594bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9595 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9596 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9597
9598 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9599 return true;
9600
9601 if (CSM == Sema::CXXDefaultConstructor) {
9602 // For a default constructor, all references must be initialized in-class
9603 // and, if a union, it must have a non-const member.
9604 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9605 if (Diagnose)
9606 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9607 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9608 return true;
9609 }
9610 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9611 // data member of const-qualified type (or array thereof) with no
9612 // brace-or-equal-initializer is not const-default-constructible.
9613 if (!inUnion() && FieldType.isConstQualified() &&
9614 !FD->hasInClassInitializer() &&
9615 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9616 if (Diagnose)
9617 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9618 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9619 return true;
9620 }
9621
9622 if (inUnion() && !FieldType.isConstQualified())
9623 AllFieldsAreConst = false;
9624 } else if (CSM == Sema::CXXCopyConstructor) {
9625 // For a copy constructor, data members must not be of rvalue reference
9626 // type.
9627 if (FieldType->isRValueReferenceType()) {
9628 if (Diagnose)
9629 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9630 << MD->getParent() << FD << FieldType;
9631 return true;
9632 }
9633 } else if (IsAssignment) {
9634 // For an assignment operator, data members must not be of reference type.
9635 if (FieldType->isReferenceType()) {
9636 if (Diagnose)
9637 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9638 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9639 return true;
9640 }
9641 if (!FieldRecord && FieldType.isConstQualified()) {
9642 // C++11 [class.copy]p23:
9643 // -- a non-static data member of const non-class type (or array thereof)
9644 if (Diagnose)
9645 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9646 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9647 return true;
9648 }
9649 }
9650
9651 if (FieldRecord) {
9652 // Some additional restrictions exist on the variant members.
9653 if (!inUnion() && FieldRecord->isUnion() &&
9654 FieldRecord->isAnonymousStructOrUnion()) {
9655 bool AllVariantFieldsAreConst = true;
9656
9657 // FIXME: Handle anonymous unions declared within anonymous unions.
9658 for (auto *UI : FieldRecord->fields()) {
9659 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9660
9661 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9662 return true;
9663
9664 if (!UnionFieldType.isConstQualified())
9665 AllVariantFieldsAreConst = false;
9666
9667 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9668 if (UnionFieldRecord &&
9669 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9670 UnionFieldType.getCVRQualifiers()))
9671 return true;
9672 }
9673
9674 // At least one member in each anonymous union must be non-const
9675 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9676 !FieldRecord->field_empty()) {
9677 if (Diagnose)
9678 S.Diag(FieldRecord->getLocation(),
9679 diag::note_deleted_default_ctor_all_const)
9680 << !!ICI << MD->getParent() << /*anonymous union*/1;
9681 return true;
9682 }
9683
9684 // Don't check the implicit member of the anonymous union type.
9685 // This is technically non-conformant but supported, and we have a
9686 // diagnostic for this elsewhere.
9687 return false;
9688 }
9689
9690 if (shouldDeleteForClassSubobject(Class: FieldRecord, Subobj: FD,
9691 Quals: FieldType.getCVRQualifiers()))
9692 return true;
9693 }
9694
9695 return false;
9696}
9697
9698/// C++11 [class.ctor] p5:
9699/// A defaulted default constructor for a class X is defined as deleted if
9700/// X is a union and all of its variant members are of const-qualified type.
9701bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9702 // This is a silly definition, because it gives an empty union a deleted
9703 // default constructor. Don't do that.
9704 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9705 bool AnyFields = false;
9706 for (auto *F : MD->getParent()->fields())
9707 if ((AnyFields = !F->isUnnamedBitfield()))
9708 break;
9709 if (!AnyFields)
9710 return false;
9711 if (Diagnose)
9712 S.Diag(MD->getParent()->getLocation(),
9713 diag::note_deleted_default_ctor_all_const)
9714 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9715 return true;
9716 }
9717 return false;
9718}
9719
9720/// Determine whether a defaulted special member function should be defined as
9721/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9722/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9723bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9724 InheritedConstructorInfo *ICI,
9725 bool Diagnose) {
9726 if (MD->isInvalidDecl())
9727 return false;
9728 CXXRecordDecl *RD = MD->getParent();
9729 assert(!RD->isDependentType() && "do deletion after instantiation");
9730 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9731 return false;
9732
9733 // C++11 [expr.lambda.prim]p19:
9734 // The closure type associated with a lambda-expression has a
9735 // deleted (8.4.3) default constructor and a deleted copy
9736 // assignment operator.
9737 // C++2a adds back these operators if the lambda has no lambda-capture.
9738 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9739 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9740 if (Diagnose)
9741 Diag(RD->getLocation(), diag::note_lambda_decl);
9742 return true;
9743 }
9744
9745 // For an anonymous struct or union, the copy and assignment special members
9746 // will never be used, so skip the check. For an anonymous union declared at
9747 // namespace scope, the constructor and destructor are used.
9748 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9749 RD->isAnonymousStructOrUnion())
9750 return false;
9751
9752 // C++11 [class.copy]p7, p18:
9753 // If the class definition declares a move constructor or move assignment
9754 // operator, an implicitly declared copy constructor or copy assignment
9755 // operator is defined as deleted.
9756 if (MD->isImplicit() &&
9757 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9758 CXXMethodDecl *UserDeclaredMove = nullptr;
9759
9760 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9761 // deletion of the corresponding copy operation, not both copy operations.
9762 // MSVC 2015 has adopted the standards conforming behavior.
9763 bool DeletesOnlyMatchingCopy =
9764 getLangOpts().MSVCCompat &&
9765 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
9766
9767 if (RD->hasUserDeclaredMoveConstructor() &&
9768 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9769 if (!Diagnose) return true;
9770
9771 // Find any user-declared move constructor.
9772 for (auto *I : RD->ctors()) {
9773 if (I->isMoveConstructor()) {
9774 UserDeclaredMove = I;
9775 break;
9776 }
9777 }
9778 assert(UserDeclaredMove);
9779 } else if (RD->hasUserDeclaredMoveAssignment() &&
9780 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9781 if (!Diagnose) return true;
9782
9783 // Find any user-declared move assignment operator.
9784 for (auto *I : RD->methods()) {
9785 if (I->isMoveAssignmentOperator()) {
9786 UserDeclaredMove = I;
9787 break;
9788 }
9789 }
9790 assert(UserDeclaredMove);
9791 }
9792
9793 if (UserDeclaredMove) {
9794 Diag(UserDeclaredMove->getLocation(),
9795 diag::note_deleted_copy_user_declared_move)
9796 << (CSM == CXXCopyAssignment) << RD
9797 << UserDeclaredMove->isMoveAssignmentOperator();
9798 return true;
9799 }
9800 }
9801
9802 // Do access control from the special member function
9803 ContextRAII MethodContext(*this, MD);
9804
9805 // C++11 [class.dtor]p5:
9806 // -- for a virtual destructor, lookup of the non-array deallocation function
9807 // results in an ambiguity or in a function that is deleted or inaccessible
9808 if (CSM == CXXDestructor && MD->isVirtual()) {
9809 FunctionDecl *OperatorDelete = nullptr;
9810 DeclarationName Name =
9811 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
9812 if (FindDeallocationFunction(StartLoc: MD->getLocation(), RD: MD->getParent(), Name,
9813 Operator&: OperatorDelete, /*Diagnose*/false)) {
9814 if (Diagnose)
9815 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9816 return true;
9817 }
9818 }
9819
9820 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9821
9822 // Per DR1611, do not consider virtual bases of constructors of abstract
9823 // classes, since we are not going to construct them.
9824 // Per DR1658, do not consider virtual bases of destructors of abstract
9825 // classes either.
9826 // Per DR2180, for assignment operators we only assign (and thus only
9827 // consider) direct bases.
9828 if (SMI.visit(Bases: SMI.IsAssignment ? SMI.VisitDirectBases
9829 : SMI.VisitPotentiallyConstructedBases))
9830 return true;
9831
9832 if (SMI.shouldDeleteForAllConstMembers())
9833 return true;
9834
9835 if (getLangOpts().CUDA) {
9836 // We should delete the special member in CUDA mode if target inference
9837 // failed.
9838 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9839 // is treated as certain special member, which may not reflect what special
9840 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9841 // expects CSM to match MD, therefore recalculate CSM.
9842 assert(ICI || CSM == getSpecialMember(MD));
9843 auto RealCSM = CSM;
9844 if (ICI)
9845 RealCSM = getSpecialMember(MD);
9846
9847 return inferCUDATargetForImplicitSpecialMember(ClassDecl: RD, CSM: RealCSM, MemberDecl: MD,
9848 ConstRHS: SMI.ConstArg, Diagnose);
9849 }
9850
9851 return false;
9852}
9853
9854void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9855 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9856 assert(DFK && "not a defaultable function");
9857 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9858
9859 if (DFK.isSpecialMember()) {
9860 ShouldDeleteSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(),
9861 ICI: nullptr, /*Diagnose=*/true);
9862 } else {
9863 DefaultedComparisonAnalyzer(
9864 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9865 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9866 .visit();
9867 }
9868}
9869
9870/// Perform lookup for a special member of the specified kind, and determine
9871/// whether it is trivial. If the triviality can be determined without the
9872/// lookup, skip it. This is intended for use when determining whether a
9873/// special member of a containing object is trivial, and thus does not ever
9874/// perform overload resolution for default constructors.
9875///
9876/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9877/// member that was most likely to be intended to be trivial, if any.
9878///
9879/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9880/// determine whether the special member is trivial.
9881static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9882 Sema::CXXSpecialMember CSM, unsigned Quals,
9883 bool ConstRHS,
9884 Sema::TrivialABIHandling TAH,
9885 CXXMethodDecl **Selected) {
9886 if (Selected)
9887 *Selected = nullptr;
9888
9889 switch (CSM) {
9890 case Sema::CXXInvalid:
9891 llvm_unreachable("not a special member");
9892
9893 case Sema::CXXDefaultConstructor:
9894 // C++11 [class.ctor]p5:
9895 // A default constructor is trivial if:
9896 // - all the [direct subobjects] have trivial default constructors
9897 //
9898 // Note, no overload resolution is performed in this case.
9899 if (RD->hasTrivialDefaultConstructor())
9900 return true;
9901
9902 if (Selected) {
9903 // If there's a default constructor which could have been trivial, dig it
9904 // out. Otherwise, if there's any user-provided default constructor, point
9905 // to that as an example of why there's not a trivial one.
9906 CXXConstructorDecl *DefCtor = nullptr;
9907 if (RD->needsImplicitDefaultConstructor())
9908 S.DeclareImplicitDefaultConstructor(ClassDecl: RD);
9909 for (auto *CI : RD->ctors()) {
9910 if (!CI->isDefaultConstructor())
9911 continue;
9912 DefCtor = CI;
9913 if (!DefCtor->isUserProvided())
9914 break;
9915 }
9916
9917 *Selected = DefCtor;
9918 }
9919
9920 return false;
9921
9922 case Sema::CXXDestructor:
9923 // C++11 [class.dtor]p5:
9924 // A destructor is trivial if:
9925 // - all the direct [subobjects] have trivial destructors
9926 if (RD->hasTrivialDestructor() ||
9927 (TAH == Sema::TAH_ConsiderTrivialABI &&
9928 RD->hasTrivialDestructorForCall()))
9929 return true;
9930
9931 if (Selected) {
9932 if (RD->needsImplicitDestructor())
9933 S.DeclareImplicitDestructor(ClassDecl: RD);
9934 *Selected = RD->getDestructor();
9935 }
9936
9937 return false;
9938
9939 case Sema::CXXCopyConstructor:
9940 // C++11 [class.copy]p12:
9941 // A copy constructor is trivial if:
9942 // - the constructor selected to copy each direct [subobject] is trivial
9943 if (RD->hasTrivialCopyConstructor() ||
9944 (TAH == Sema::TAH_ConsiderTrivialABI &&
9945 RD->hasTrivialCopyConstructorForCall())) {
9946 if (Quals == Qualifiers::Const)
9947 // We must either select the trivial copy constructor or reach an
9948 // ambiguity; no need to actually perform overload resolution.
9949 return true;
9950 } else if (!Selected) {
9951 return false;
9952 }
9953 // In C++98, we are not supposed to perform overload resolution here, but we
9954 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9955 // cases like B as having a non-trivial copy constructor:
9956 // struct A { template<typename T> A(T&); };
9957 // struct B { mutable A a; };
9958 goto NeedOverloadResolution;
9959
9960 case Sema::CXXCopyAssignment:
9961 // C++11 [class.copy]p25:
9962 // A copy assignment operator is trivial if:
9963 // - the assignment operator selected to copy each direct [subobject] is
9964 // trivial
9965 if (RD->hasTrivialCopyAssignment()) {
9966 if (Quals == Qualifiers::Const)
9967 return true;
9968 } else if (!Selected) {
9969 return false;
9970 }
9971 // In C++98, we are not supposed to perform overload resolution here, but we
9972 // treat that as a language defect.
9973 goto NeedOverloadResolution;
9974
9975 case Sema::CXXMoveConstructor:
9976 case Sema::CXXMoveAssignment:
9977 NeedOverloadResolution:
9978 Sema::SpecialMemberOverloadResult SMOR =
9979 lookupCallFromSpecialMember(S, Class: RD, CSM, FieldQuals: Quals, ConstRHS);
9980
9981 // The standard doesn't describe how to behave if the lookup is ambiguous.
9982 // We treat it as not making the member non-trivial, just like the standard
9983 // mandates for the default constructor. This should rarely matter, because
9984 // the member will also be deleted.
9985 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9986 return true;
9987
9988 if (!SMOR.getMethod()) {
9989 assert(SMOR.getKind() ==
9990 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9991 return false;
9992 }
9993
9994 // We deliberately don't check if we found a deleted special member. We're
9995 // not supposed to!
9996 if (Selected)
9997 *Selected = SMOR.getMethod();
9998
9999 if (TAH == Sema::TAH_ConsiderTrivialABI &&
10000 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
10001 return SMOR.getMethod()->isTrivialForCall();
10002 return SMOR.getMethod()->isTrivial();
10003 }
10004
10005 llvm_unreachable("unknown special method kind");
10006}
10007
10008static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10009 for (auto *CI : RD->ctors())
10010 if (!CI->isImplicit())
10011 return CI;
10012
10013 // Look for constructor templates.
10014 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10015 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10016 if (CXXConstructorDecl *CD =
10017 dyn_cast<CXXConstructorDecl>(Val: TI->getTemplatedDecl()))
10018 return CD;
10019 }
10020
10021 return nullptr;
10022}
10023
10024/// The kind of subobject we are checking for triviality. The values of this
10025/// enumeration are used in diagnostics.
10026enum TrivialSubobjectKind {
10027 /// The subobject is a base class.
10028 TSK_BaseClass,
10029 /// The subobject is a non-static data member.
10030 TSK_Field,
10031 /// The object is actually the complete object.
10032 TSK_CompleteObject
10033};
10034
10035/// Check whether the special member selected for a given type would be trivial.
10036static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10037 QualType SubType, bool ConstRHS,
10038 Sema::CXXSpecialMember CSM,
10039 TrivialSubobjectKind Kind,
10040 Sema::TrivialABIHandling TAH, bool Diagnose) {
10041 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10042 if (!SubRD)
10043 return true;
10044
10045 CXXMethodDecl *Selected;
10046 if (findTrivialSpecialMember(S, RD: SubRD, CSM, Quals: SubType.getCVRQualifiers(),
10047 ConstRHS, TAH, Selected: Diagnose ? &Selected : nullptr))
10048 return true;
10049
10050 if (Diagnose) {
10051 if (ConstRHS)
10052 SubType.addConst();
10053
10054 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
10055 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10056 << Kind << SubType.getUnqualifiedType();
10057 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
10058 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10059 } else if (!Selected)
10060 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10061 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10062 else if (Selected->isUserProvided()) {
10063 if (Kind == TSK_CompleteObject)
10064 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10065 << Kind << SubType.getUnqualifiedType() << CSM;
10066 else {
10067 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10068 << Kind << SubType.getUnqualifiedType() << CSM;
10069 S.Diag(Selected->getLocation(), diag::note_declared_at);
10070 }
10071 } else {
10072 if (Kind != TSK_CompleteObject)
10073 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10074 << Kind << SubType.getUnqualifiedType() << CSM;
10075
10076 // Explain why the defaulted or deleted special member isn't trivial.
10077 S.SpecialMemberIsTrivial(MD: Selected, CSM, TAH: Sema::TAH_IgnoreTrivialABI,
10078 Diagnose);
10079 }
10080 }
10081
10082 return false;
10083}
10084
10085/// Check whether the members of a class type allow a special member to be
10086/// trivial.
10087static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10088 Sema::CXXSpecialMember CSM,
10089 bool ConstArg,
10090 Sema::TrivialABIHandling TAH,
10091 bool Diagnose) {
10092 for (const auto *FI : RD->fields()) {
10093 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
10094 continue;
10095
10096 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10097
10098 // Pretend anonymous struct or union members are members of this class.
10099 if (FI->isAnonymousStructOrUnion()) {
10100 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10101 CSM, ConstArg, TAH, Diagnose))
10102 return false;
10103 continue;
10104 }
10105
10106 // C++11 [class.ctor]p5:
10107 // A default constructor is trivial if [...]
10108 // -- no non-static data member of its class has a
10109 // brace-or-equal-initializer
10110 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
10111 if (Diagnose)
10112 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10113 << FI;
10114 return false;
10115 }
10116
10117 // Objective C ARC 4.3.5:
10118 // [...] nontrivally ownership-qualified types are [...] not trivially
10119 // default constructible, copy constructible, move constructible, copy
10120 // assignable, move assignable, or destructible [...]
10121 if (FieldType.hasNonTrivialObjCLifetime()) {
10122 if (Diagnose)
10123 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10124 << RD << FieldType.getObjCLifetime();
10125 return false;
10126 }
10127
10128 bool ConstRHS = ConstArg && !FI->isMutable();
10129 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10130 CSM, TSK_Field, TAH, Diagnose))
10131 return false;
10132 }
10133
10134 return true;
10135}
10136
10137/// Diagnose why the specified class does not have a trivial special member of
10138/// the given kind.
10139void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
10140 QualType Ty = Context.getRecordType(RD);
10141
10142 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
10143 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10144 TSK_CompleteObject, TAH_IgnoreTrivialABI,
10145 /*Diagnose*/true);
10146}
10147
10148/// Determine whether a defaulted or deleted special member function is trivial,
10149/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
10150/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
10151bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
10152 TrivialABIHandling TAH, bool Diagnose) {
10153 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
10154
10155 CXXRecordDecl *RD = MD->getParent();
10156
10157 bool ConstArg = false;
10158
10159 // C++11 [class.copy]p12, p25: [DR1593]
10160 // A [special member] is trivial if [...] its parameter-type-list is
10161 // equivalent to the parameter-type-list of an implicit declaration [...]
10162 switch (CSM) {
10163 case CXXDefaultConstructor:
10164 case CXXDestructor:
10165 // Trivial default constructors and destructors cannot have parameters.
10166 break;
10167
10168 case CXXCopyConstructor:
10169 case CXXCopyAssignment: {
10170 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10171 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10172
10173 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10174 // if they are not user-provided and their parameter-type-list is equivalent
10175 // to the parameter-type-list of an implicit declaration. This maintains the
10176 // behavior before dr2171 was implemented.
10177 //
10178 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10179 // trivial, if they are not user-provided, regardless of the qualifiers on
10180 // the reference type.
10181 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10182 LangOptions::ClangABI::Ver14;
10183 if (!RT ||
10184 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10185 ClangABICompat14)) {
10186 if (Diagnose)
10187 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10188 << Param0->getSourceRange() << Param0->getType()
10189 << Context.getLValueReferenceType(
10190 Context.getRecordType(RD).withConst());
10191 return false;
10192 }
10193
10194 ConstArg = RT->getPointeeType().isConstQualified();
10195 break;
10196 }
10197
10198 case CXXMoveConstructor:
10199 case CXXMoveAssignment: {
10200 // Trivial move operations always have non-cv-qualified parameters.
10201 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10202 const RValueReferenceType *RT =
10203 Param0->getType()->getAs<RValueReferenceType>();
10204 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10205 if (Diagnose)
10206 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10207 << Param0->getSourceRange() << Param0->getType()
10208 << Context.getRValueReferenceType(Context.getRecordType(RD));
10209 return false;
10210 }
10211 break;
10212 }
10213
10214 case CXXInvalid:
10215 llvm_unreachable("not a special member");
10216 }
10217
10218 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10219 if (Diagnose)
10220 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
10221 diag::note_nontrivial_default_arg)
10222 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
10223 return false;
10224 }
10225 if (MD->isVariadic()) {
10226 if (Diagnose)
10227 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10228 return false;
10229 }
10230
10231 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10232 // A copy/move [constructor or assignment operator] is trivial if
10233 // -- the [member] selected to copy/move each direct base class subobject
10234 // is trivial
10235 //
10236 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10237 // A [default constructor or destructor] is trivial if
10238 // -- all the direct base classes have trivial [default constructors or
10239 // destructors]
10240 for (const auto &BI : RD->bases())
10241 if (!checkTrivialSubobjectCall(S&: *this, SubobjLoc: BI.getBeginLoc(), SubType: BI.getType(),
10242 ConstRHS: ConstArg, CSM, Kind: TSK_BaseClass, TAH, Diagnose))
10243 return false;
10244
10245 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10246 // A copy/move [constructor or assignment operator] for a class X is
10247 // trivial if
10248 // -- for each non-static data member of X that is of class type (or array
10249 // thereof), the constructor selected to copy/move that member is
10250 // trivial
10251 //
10252 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10253 // A [default constructor or destructor] is trivial if
10254 // -- for all of the non-static data members of its class that are of class
10255 // type (or array thereof), each such class has a trivial [default
10256 // constructor or destructor]
10257 if (!checkTrivialClassMembers(S&: *this, RD, CSM, ConstArg, TAH, Diagnose))
10258 return false;
10259
10260 // C++11 [class.dtor]p5:
10261 // A destructor is trivial if [...]
10262 // -- the destructor is not virtual
10263 if (CSM == CXXDestructor && MD->isVirtual()) {
10264 if (Diagnose)
10265 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10266 return false;
10267 }
10268
10269 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10270 // A [special member] for class X is trivial if [...]
10271 // -- class X has no virtual functions and no virtual base classes
10272 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
10273 if (!Diagnose)
10274 return false;
10275
10276 if (RD->getNumVBases()) {
10277 // Check for virtual bases. We already know that the corresponding
10278 // member in all bases is trivial, so vbases must all be direct.
10279 CXXBaseSpecifier &BS = *RD->vbases_begin();
10280 assert(BS.isVirtual());
10281 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10282 return false;
10283 }
10284
10285 // Must have a virtual method.
10286 for (const auto *MI : RD->methods()) {
10287 if (MI->isVirtual()) {
10288 SourceLocation MLoc = MI->getBeginLoc();
10289 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10290 return false;
10291 }
10292 }
10293
10294 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10295 }
10296
10297 // Looks like it's trivial!
10298 return true;
10299}
10300
10301namespace {
10302struct FindHiddenVirtualMethod {
10303 Sema *S;
10304 CXXMethodDecl *Method;
10305 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10306 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10307
10308private:
10309 /// Check whether any most overridden method from MD in Methods
10310 static bool CheckMostOverridenMethods(
10311 const CXXMethodDecl *MD,
10312 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10313 if (MD->size_overridden_methods() == 0)
10314 return Methods.count(Ptr: MD->getCanonicalDecl());
10315 for (const CXXMethodDecl *O : MD->overridden_methods())
10316 if (CheckMostOverridenMethods(MD: O, Methods))
10317 return true;
10318 return false;
10319 }
10320
10321public:
10322 /// Member lookup function that determines whether a given C++
10323 /// method overloads virtual methods in a base class without overriding any,
10324 /// to be used with CXXRecordDecl::lookupInBases().
10325 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10326 RecordDecl *BaseRecord =
10327 Specifier->getType()->castAs<RecordType>()->getDecl();
10328
10329 DeclarationName Name = Method->getDeclName();
10330 assert(Name.getNameKind() == DeclarationName::Identifier);
10331
10332 bool foundSameNameMethod = false;
10333 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10334 for (Path.Decls = BaseRecord->lookup(Name).begin();
10335 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10336 NamedDecl *D = *Path.Decls;
10337 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
10338 MD = MD->getCanonicalDecl();
10339 foundSameNameMethod = true;
10340 // Interested only in hidden virtual methods.
10341 if (!MD->isVirtual())
10342 continue;
10343 // If the method we are checking overrides a method from its base
10344 // don't warn about the other overloaded methods. Clang deviates from
10345 // GCC by only diagnosing overloads of inherited virtual functions that
10346 // do not override any other virtual functions in the base. GCC's
10347 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10348 // function from a base class. These cases may be better served by a
10349 // warning (not specific to virtual functions) on call sites when the
10350 // call would select a different function from the base class, were it
10351 // visible.
10352 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10353 if (!S->IsOverload(Method, MD, false))
10354 return true;
10355 // Collect the overload only if its hidden.
10356 if (!CheckMostOverridenMethods(MD, Methods: OverridenAndUsingBaseMethods))
10357 overloadedMethods.push_back(Elt: MD);
10358 }
10359 }
10360
10361 if (foundSameNameMethod)
10362 OverloadedMethods.append(in_start: overloadedMethods.begin(),
10363 in_end: overloadedMethods.end());
10364 return foundSameNameMethod;
10365 }
10366};
10367} // end anonymous namespace
10368
10369/// Add the most overridden methods from MD to Methods
10370static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10371 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10372 if (MD->size_overridden_methods() == 0)
10373 Methods.insert(Ptr: MD->getCanonicalDecl());
10374 else
10375 for (const CXXMethodDecl *O : MD->overridden_methods())
10376 AddMostOverridenMethods(MD: O, Methods);
10377}
10378
10379/// Check if a method overloads virtual methods in a base class without
10380/// overriding any.
10381void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10382 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10383 if (!MD->getDeclName().isIdentifier())
10384 return;
10385
10386 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10387 /*bool RecordPaths=*/false,
10388 /*bool DetectVirtual=*/false);
10389 FindHiddenVirtualMethod FHVM;
10390 FHVM.Method = MD;
10391 FHVM.S = this;
10392
10393 // Keep the base methods that were overridden or introduced in the subclass
10394 // by 'using' in a set. A base method not in this set is hidden.
10395 CXXRecordDecl *DC = MD->getParent();
10396 DeclContext::lookup_result R = DC->lookup(Name: MD->getDeclName());
10397 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10398 NamedDecl *ND = *I;
10399 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(Val: *I))
10400 ND = shad->getTargetDecl();
10401 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ND))
10402 AddMostOverridenMethods(MD, Methods&: FHVM.OverridenAndUsingBaseMethods);
10403 }
10404
10405 if (DC->lookupInBases(BaseMatches: FHVM, Paths))
10406 OverloadedMethods = FHVM.OverloadedMethods;
10407}
10408
10409void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10410 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10411 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10412 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10413 PartialDiagnostic PD = PDiag(
10414 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10415 HandleFunctionTypeMismatch(PDiag&: PD, FromType: MD->getType(), ToType: overloadedMD->getType());
10416 Diag(overloadedMD->getLocation(), PD);
10417 }
10418}
10419
10420/// Diagnose methods which overload virtual methods in a base class
10421/// without overriding any.
10422void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10423 if (MD->isInvalidDecl())
10424 return;
10425
10426 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10427 return;
10428
10429 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10430 FindHiddenVirtualMethods(MD, OverloadedMethods);
10431 if (!OverloadedMethods.empty()) {
10432 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10433 << MD << (OverloadedMethods.size() > 1);
10434
10435 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10436 }
10437}
10438
10439void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10440 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10441 // No diagnostics if this is a template instantiation.
10442 if (!isTemplateInstantiation(Kind: RD.getTemplateSpecializationKind())) {
10443 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10444 diag::ext_cannot_use_trivial_abi) << &RD;
10445 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10446 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10447 }
10448 RD.dropAttr<TrivialABIAttr>();
10449 };
10450
10451 // Ill-formed if the copy and move constructors are deleted.
10452 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10453 // If the type is dependent, then assume it might have
10454 // implicit copy or move ctor because we won't know yet at this point.
10455 if (RD.isDependentType())
10456 return true;
10457 if (RD.needsImplicitCopyConstructor() &&
10458 !RD.defaultedCopyConstructorIsDeleted())
10459 return true;
10460 if (RD.needsImplicitMoveConstructor() &&
10461 !RD.defaultedMoveConstructorIsDeleted())
10462 return true;
10463 for (const CXXConstructorDecl *CD : RD.ctors())
10464 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10465 return true;
10466 return false;
10467 };
10468
10469 if (!HasNonDeletedCopyOrMoveConstructor()) {
10470 PrintDiagAndRemoveAttr(0);
10471 return;
10472 }
10473
10474 // Ill-formed if the struct has virtual functions.
10475 if (RD.isPolymorphic()) {
10476 PrintDiagAndRemoveAttr(1);
10477 return;
10478 }
10479
10480 for (const auto &B : RD.bases()) {
10481 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10482 // virtual base.
10483 if (!B.getType()->isDependentType() &&
10484 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10485 PrintDiagAndRemoveAttr(2);
10486 return;
10487 }
10488
10489 if (B.isVirtual()) {
10490 PrintDiagAndRemoveAttr(3);
10491 return;
10492 }
10493 }
10494
10495 for (const auto *FD : RD.fields()) {
10496 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10497 // non-trivial for the purpose of calls.
10498 QualType FT = FD->getType();
10499 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10500 PrintDiagAndRemoveAttr(4);
10501 return;
10502 }
10503
10504 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10505 if (!RT->isDependentType() &&
10506 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10507 PrintDiagAndRemoveAttr(5);
10508 return;
10509 }
10510 }
10511}
10512
10513void Sema::ActOnFinishCXXMemberSpecification(
10514 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10515 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10516 if (!TagDecl)
10517 return;
10518
10519 AdjustDeclIfTemplate(Decl&: TagDecl);
10520
10521 for (const ParsedAttr &AL : AttrList) {
10522 if (AL.getKind() != ParsedAttr::AT_Visibility)
10523 continue;
10524 AL.setInvalid();
10525 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10526 }
10527
10528 ActOnFields(S, RecLoc: RLoc, TagDecl,
10529 Fields: llvm::ArrayRef(
10530 // strict aliasing violation!
10531 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10532 FieldCollector->getCurNumFields()),
10533 LBrac, RBrac, AttrList);
10534
10535 CheckCompletedCXXClass(S, Record: cast<CXXRecordDecl>(Val: TagDecl));
10536}
10537
10538/// Find the equality comparison functions that should be implicitly declared
10539/// in a given class definition, per C++2a [class.compare.default]p3.
10540static void findImplicitlyDeclaredEqualityComparisons(
10541 ASTContext &Ctx, CXXRecordDecl *RD,
10542 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10543 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual);
10544 if (!RD->lookup(EqEq).empty())
10545 // Member operator== explicitly declared: no implicit operator==s.
10546 return;
10547
10548 // Traverse friends looking for an '==' or a '<=>'.
10549 for (FriendDecl *Friend : RD->friends()) {
10550 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Friend->getFriendDecl());
10551 if (!FD) continue;
10552
10553 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10554 // Friend operator== explicitly declared: no implicit operator==s.
10555 Spaceships.clear();
10556 return;
10557 }
10558
10559 if (FD->getOverloadedOperator() == OO_Spaceship &&
10560 FD->isExplicitlyDefaulted())
10561 Spaceships.push_back(Elt: FD);
10562 }
10563
10564 // Look for members named 'operator<=>'.
10565 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_Spaceship);
10566 for (NamedDecl *ND : RD->lookup(Cmp)) {
10567 // Note that we could find a non-function here (either a function template
10568 // or a using-declaration). Neither case results in an implicit
10569 // 'operator=='.
10570 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10571 if (FD->isExplicitlyDefaulted())
10572 Spaceships.push_back(FD);
10573 }
10574}
10575
10576/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10577/// special functions, such as the default constructor, copy
10578/// constructor, or destructor, to the given C++ class (C++
10579/// [special]p1). This routine can only be executed just before the
10580/// definition of the class is complete.
10581void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10582 // Don't add implicit special members to templated classes.
10583 // FIXME: This means unqualified lookups for 'operator=' within a class
10584 // template don't work properly.
10585 if (!ClassDecl->isDependentType()) {
10586 if (ClassDecl->needsImplicitDefaultConstructor()) {
10587 ++getASTContext().NumImplicitDefaultConstructors;
10588
10589 if (ClassDecl->hasInheritedConstructor())
10590 DeclareImplicitDefaultConstructor(ClassDecl);
10591 }
10592
10593 if (ClassDecl->needsImplicitCopyConstructor()) {
10594 ++getASTContext().NumImplicitCopyConstructors;
10595
10596 // If the properties or semantics of the copy constructor couldn't be
10597 // determined while the class was being declared, force a declaration
10598 // of it now.
10599 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10600 ClassDecl->hasInheritedConstructor())
10601 DeclareImplicitCopyConstructor(ClassDecl);
10602 // For the MS ABI we need to know whether the copy ctor is deleted. A
10603 // prerequisite for deleting the implicit copy ctor is that the class has
10604 // a move ctor or move assignment that is either user-declared or whose
10605 // semantics are inherited from a subobject. FIXME: We should provide a
10606 // more direct way for CodeGen to ask whether the constructor was deleted.
10607 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10608 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10609 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10610 ClassDecl->hasUserDeclaredMoveAssignment() ||
10611 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10612 DeclareImplicitCopyConstructor(ClassDecl);
10613 }
10614
10615 if (getLangOpts().CPlusPlus11 &&
10616 ClassDecl->needsImplicitMoveConstructor()) {
10617 ++getASTContext().NumImplicitMoveConstructors;
10618
10619 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10620 ClassDecl->hasInheritedConstructor())
10621 DeclareImplicitMoveConstructor(ClassDecl);
10622 }
10623
10624 if (ClassDecl->needsImplicitCopyAssignment()) {
10625 ++getASTContext().NumImplicitCopyAssignmentOperators;
10626
10627 // If we have a dynamic class, then the copy assignment operator may be
10628 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10629 // it shows up in the right place in the vtable and that we diagnose
10630 // problems with the implicit exception specification.
10631 if (ClassDecl->isDynamicClass() ||
10632 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10633 ClassDecl->hasInheritedAssignment())
10634 DeclareImplicitCopyAssignment(ClassDecl);
10635 }
10636
10637 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10638 ++getASTContext().NumImplicitMoveAssignmentOperators;
10639
10640 // Likewise for the move assignment operator.
10641 if (ClassDecl->isDynamicClass() ||
10642 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10643 ClassDecl->hasInheritedAssignment())
10644 DeclareImplicitMoveAssignment(ClassDecl);
10645 }
10646
10647 if (ClassDecl->needsImplicitDestructor()) {
10648 ++getASTContext().NumImplicitDestructors;
10649
10650 // If we have a dynamic class, then the destructor may be virtual, so we
10651 // have to declare the destructor immediately. This ensures that, e.g., it
10652 // shows up in the right place in the vtable and that we diagnose problems
10653 // with the implicit exception specification.
10654 if (ClassDecl->isDynamicClass() ||
10655 ClassDecl->needsOverloadResolutionForDestructor())
10656 DeclareImplicitDestructor(ClassDecl);
10657 }
10658 }
10659
10660 // C++2a [class.compare.default]p3:
10661 // If the member-specification does not explicitly declare any member or
10662 // friend named operator==, an == operator function is declared implicitly
10663 // for each defaulted three-way comparison operator function defined in
10664 // the member-specification
10665 // FIXME: Consider doing this lazily.
10666 // We do this during the initial parse for a class template, not during
10667 // instantiation, so that we can handle unqualified lookups for 'operator=='
10668 // when parsing the template.
10669 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10670 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10671 findImplicitlyDeclaredEqualityComparisons(Ctx&: Context, RD: ClassDecl,
10672 Spaceships&: DefaultedSpaceships);
10673 for (auto *FD : DefaultedSpaceships)
10674 DeclareImplicitEqualityComparison(RD: ClassDecl, Spaceship: FD);
10675 }
10676}
10677
10678unsigned
10679Sema::ActOnReenterTemplateScope(Decl *D,
10680 llvm::function_ref<Scope *()> EnterScope) {
10681 if (!D)
10682 return 0;
10683 AdjustDeclIfTemplate(Decl&: D);
10684
10685 // In order to get name lookup right, reenter template scopes in order from
10686 // outermost to innermost.
10687 SmallVector<TemplateParameterList *, 4> ParameterLists;
10688 DeclContext *LookupDC = dyn_cast<DeclContext>(Val: D);
10689
10690 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
10691 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10692 ParameterLists.push_back(Elt: DD->getTemplateParameterList(index: i));
10693
10694 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
10695 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10696 ParameterLists.push_back(Elt: FTD->getTemplateParameters());
10697 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
10698 LookupDC = VD->getDeclContext();
10699
10700 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10701 ParameterLists.push_back(Elt: VTD->getTemplateParameters());
10702 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D))
10703 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
10704 }
10705 } else if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
10706 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10707 ParameterLists.push_back(Elt: TD->getTemplateParameterList(i));
10708
10709 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TD)) {
10710 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10711 ParameterLists.push_back(Elt: CTD->getTemplateParameters());
10712 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D))
10713 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
10714 }
10715 }
10716 // FIXME: Alias declarations and concepts.
10717
10718 unsigned Count = 0;
10719 Scope *InnermostTemplateScope = nullptr;
10720 for (TemplateParameterList *Params : ParameterLists) {
10721 // Ignore explicit specializations; they don't contribute to the template
10722 // depth.
10723 if (Params->size() == 0)
10724 continue;
10725
10726 InnermostTemplateScope = EnterScope();
10727 for (NamedDecl *Param : *Params) {
10728 if (Param->getDeclName()) {
10729 InnermostTemplateScope->AddDecl(Param);
10730 IdResolver.AddDecl(D: Param);
10731 }
10732 }
10733 ++Count;
10734 }
10735
10736 // Associate the new template scopes with the corresponding entities.
10737 if (InnermostTemplateScope) {
10738 assert(LookupDC && "no enclosing DeclContext for template lookup");
10739 EnterTemplatedContext(S: InnermostTemplateScope, DC: LookupDC);
10740 }
10741
10742 return Count;
10743}
10744
10745void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10746 if (!RecordD) return;
10747 AdjustDeclIfTemplate(Decl&: RecordD);
10748 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: RecordD);
10749 PushDeclContext(S, Record);
10750}
10751
10752void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10753 if (!RecordD) return;
10754 PopDeclContext();
10755}
10756
10757/// This is used to implement the constant expression evaluation part of the
10758/// attribute enable_if extension. There is nothing in standard C++ which would
10759/// require reentering parameters.
10760void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10761 if (!Param)
10762 return;
10763
10764 S->AddDecl(Param);
10765 if (Param->getDeclName())
10766 IdResolver.AddDecl(Param);
10767}
10768
10769/// ActOnStartDelayedCXXMethodDeclaration - We have completed
10770/// parsing a top-level (non-nested) C++ class, and we are now
10771/// parsing those parts of the given Method declaration that could
10772/// not be parsed earlier (C++ [class.mem]p2), such as default
10773/// arguments. This action should enter the scope of the given
10774/// Method declaration as if we had just parsed the qualified method
10775/// name. However, it should not bring the parameters into scope;
10776/// that will be performed by ActOnDelayedCXXMethodParameter.
10777void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10778}
10779
10780/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10781/// C++ method declaration. We're (re-)introducing the given
10782/// function parameter into scope for use in parsing later parts of
10783/// the method declaration. For example, we could see an
10784/// ActOnParamDefaultArgument event for this parameter.
10785void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10786 if (!ParamD)
10787 return;
10788
10789 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamD);
10790
10791 S->AddDecl(Param);
10792 if (Param->getDeclName())
10793 IdResolver.AddDecl(Param);
10794}
10795
10796/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10797/// processing the delayed method declaration for Method. The method
10798/// declaration is now considered finished. There may be a separate
10799/// ActOnStartOfFunctionDef action later (not necessarily
10800/// immediately!) for this method, if it was also defined inside the
10801/// class body.
10802void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10803 if (!MethodD)
10804 return;
10805
10806 AdjustDeclIfTemplate(Decl&: MethodD);
10807
10808 FunctionDecl *Method = cast<FunctionDecl>(Val: MethodD);
10809
10810 // Now that we have our default arguments, check the constructor
10811 // again. It could produce additional diagnostics or affect whether
10812 // the class has implicitly-declared destructors, among other
10813 // things.
10814 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method))
10815 CheckConstructor(Constructor);
10816
10817 // Check the default arguments, which we may have added.
10818 if (!Method->isInvalidDecl())
10819 CheckCXXDefaultArguments(FD: Method);
10820}
10821
10822// Emit the given diagnostic for each non-address-space qualifier.
10823// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10824static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10825 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10826 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10827 bool DiagOccured = false;
10828 FTI.MethodQualifiers->forEachQualifier(
10829 Handle: [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10830 SourceLocation SL) {
10831 // This diagnostic should be emitted on any qualifier except an addr
10832 // space qualifier. However, forEachQualifier currently doesn't visit
10833 // addr space qualifiers, so there's no way to write this condition
10834 // right now; we just diagnose on everything.
10835 S.Diag(Loc: SL, DiagID) << QualName << SourceRange(SL);
10836 DiagOccured = true;
10837 });
10838 if (DiagOccured)
10839 D.setInvalidType();
10840 }
10841}
10842
10843/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10844/// the well-formedness of the constructor declarator @p D with type @p
10845/// R. If there are any errors in the declarator, this routine will
10846/// emit diagnostics and set the invalid bit to true. In any case, the type
10847/// will be updated to reflect a well-formed type for the constructor and
10848/// returned.
10849QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10850 StorageClass &SC) {
10851 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10852
10853 // C++ [class.ctor]p3:
10854 // A constructor shall not be virtual (10.3) or static (9.4). A
10855 // constructor can be invoked for a const, volatile or const
10856 // volatile object. A constructor shall not be declared const,
10857 // volatile, or const volatile (9.3.2).
10858 if (isVirtual) {
10859 if (!D.isInvalidType())
10860 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10861 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10862 << SourceRange(D.getIdentifierLoc());
10863 D.setInvalidType();
10864 }
10865 if (SC == SC_Static) {
10866 if (!D.isInvalidType())
10867 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10868 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10869 << SourceRange(D.getIdentifierLoc());
10870 D.setInvalidType();
10871 SC = SC_None;
10872 }
10873
10874 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10875 diagnoseIgnoredQualifiers(
10876 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10877 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10878 D.getDeclSpec().getRestrictSpecLoc(),
10879 D.getDeclSpec().getAtomicSpecLoc());
10880 D.setInvalidType();
10881 }
10882
10883 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10884
10885 // C++0x [class.ctor]p4:
10886 // A constructor shall not be declared with a ref-qualifier.
10887 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10888 if (FTI.hasRefQualifier()) {
10889 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10890 << FTI.RefQualifierIsLValueRef
10891 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10892 D.setInvalidType();
10893 }
10894
10895 // Rebuild the function type "R" without any type qualifiers (in
10896 // case any of the errors above fired) and with "void" as the
10897 // return type, since constructors don't have return types.
10898 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10899 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10900 return R;
10901
10902 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10903 EPI.TypeQuals = Qualifiers();
10904 EPI.RefQualifier = RQ_None;
10905
10906 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: Proto->getParamTypes(), EPI);
10907}
10908
10909/// CheckConstructor - Checks a fully-formed constructor for
10910/// well-formedness, issuing any diagnostics required. Returns true if
10911/// the constructor declarator is invalid.
10912void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10913 CXXRecordDecl *ClassDecl
10914 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10915 if (!ClassDecl)
10916 return Constructor->setInvalidDecl();
10917
10918 // C++ [class.copy]p3:
10919 // A declaration of a constructor for a class X is ill-formed if
10920 // its first parameter is of type (optionally cv-qualified) X and
10921 // either there are no other parameters or else all other
10922 // parameters have default arguments.
10923 if (!Constructor->isInvalidDecl() &&
10924 Constructor->hasOneParamOrDefaultArgs() &&
10925 Constructor->getTemplateSpecializationKind() !=
10926 TSK_ImplicitInstantiation) {
10927 QualType ParamType = Constructor->getParamDecl(0)->getType();
10928 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10929 if (Context.getCanonicalType(T: ParamType).getUnqualifiedType() == ClassTy) {
10930 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10931 const char *ConstRef
10932 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10933 : " const &";
10934 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10935 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10936
10937 // FIXME: Rather that making the constructor invalid, we should endeavor
10938 // to fix the type.
10939 Constructor->setInvalidDecl();
10940 }
10941 }
10942}
10943
10944/// CheckDestructor - Checks a fully-formed destructor definition for
10945/// well-formedness, issuing any diagnostics required. Returns true
10946/// on error.
10947bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10948 CXXRecordDecl *RD = Destructor->getParent();
10949
10950 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10951 SourceLocation Loc;
10952
10953 if (!Destructor->isImplicit())
10954 Loc = Destructor->getLocation();
10955 else
10956 Loc = RD->getLocation();
10957
10958 // If we have a virtual destructor, look up the deallocation function
10959 if (FunctionDecl *OperatorDelete =
10960 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD)) {
10961 Expr *ThisArg = nullptr;
10962
10963 // If the notional 'delete this' expression requires a non-trivial
10964 // conversion from 'this' to the type of a destroying operator delete's
10965 // first parameter, perform that conversion now.
10966 if (OperatorDelete->isDestroyingOperatorDelete()) {
10967 QualType ParamType = OperatorDelete->getParamDecl(i: 0)->getType();
10968 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10969 // C++ [class.dtor]p13:
10970 // ... as if for the expression 'delete this' appearing in a
10971 // non-virtual destructor of the destructor's class.
10972 ContextRAII SwitchContext(*this, Destructor);
10973 ExprResult This =
10974 ActOnCXXThis(loc: OperatorDelete->getParamDecl(i: 0)->getLocation());
10975 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10976 This = PerformImplicitConversion(From: This.get(), ToType: ParamType, Action: AA_Passing);
10977 if (This.isInvalid()) {
10978 // FIXME: Register this as a context note so that it comes out
10979 // in the right order.
10980 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10981 return true;
10982 }
10983 ThisArg = This.get();
10984 }
10985 }
10986
10987 DiagnoseUseOfDecl(OperatorDelete, Loc);
10988 MarkFunctionReferenced(Loc, Func: OperatorDelete);
10989 Destructor->setOperatorDelete(OD: OperatorDelete, ThisArg);
10990 }
10991 }
10992
10993 return false;
10994}
10995
10996/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10997/// the well-formednes of the destructor declarator @p D with type @p
10998/// R. If there are any errors in the declarator, this routine will
10999/// emit diagnostics and set the declarator to invalid. Even if this happens,
11000/// will be updated to reflect a well-formed type for the destructor and
11001/// returned.
11002QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11003 StorageClass& SC) {
11004 // C++ [class.dtor]p1:
11005 // [...] A typedef-name that names a class is a class-name
11006 // (7.1.3); however, a typedef-name that names a class shall not
11007 // be used as the identifier in the declarator for a destructor
11008 // declaration.
11009 QualType DeclaratorType = GetTypeFromParser(Ty: D.getName().DestructorName);
11010 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11011 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11012 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11013 else if (const TemplateSpecializationType *TST =
11014 DeclaratorType->getAs<TemplateSpecializationType>())
11015 if (TST->isTypeAlias())
11016 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11017 << DeclaratorType << 1;
11018
11019 // C++ [class.dtor]p2:
11020 // A destructor is used to destroy objects of its class type. A
11021 // destructor takes no parameters, and no return type can be
11022 // specified for it (not even void). The address of a destructor
11023 // shall not be taken. A destructor shall not be static. A
11024 // destructor can be invoked for a const, volatile or const
11025 // volatile object. A destructor shall not be declared const,
11026 // volatile or const volatile (9.3.2).
11027 if (SC == SC_Static) {
11028 if (!D.isInvalidType())
11029 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11030 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11031 << SourceRange(D.getIdentifierLoc())
11032 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
11033
11034 SC = SC_None;
11035 }
11036 if (!D.isInvalidType()) {
11037 // Destructors don't have return types, but the parser will
11038 // happily parse something like:
11039 //
11040 // class X {
11041 // float ~X();
11042 // };
11043 //
11044 // The return type will be eliminated later.
11045 if (D.getDeclSpec().hasTypeSpecifier())
11046 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11047 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11048 << SourceRange(D.getIdentifierLoc());
11049 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11050 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11051 SourceLocation(),
11052 D.getDeclSpec().getConstSpecLoc(),
11053 D.getDeclSpec().getVolatileSpecLoc(),
11054 D.getDeclSpec().getRestrictSpecLoc(),
11055 D.getDeclSpec().getAtomicSpecLoc());
11056 D.setInvalidType();
11057 }
11058 }
11059
11060 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11061
11062 // C++0x [class.dtor]p2:
11063 // A destructor shall not be declared with a ref-qualifier.
11064 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11065 if (FTI.hasRefQualifier()) {
11066 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11067 << FTI.RefQualifierIsLValueRef
11068 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
11069 D.setInvalidType();
11070 }
11071
11072 // Make sure we don't have any parameters.
11073 if (FTIHasNonVoidParameters(FTI)) {
11074 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11075
11076 // Delete the parameters.
11077 FTI.freeParams();
11078 D.setInvalidType();
11079 }
11080
11081 // Make sure the destructor isn't variadic.
11082 if (FTI.isVariadic) {
11083 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11084 D.setInvalidType();
11085 }
11086
11087 // Rebuild the function type "R" without any type qualifiers or
11088 // parameters (in case any of the errors above fired) and with
11089 // "void" as the return type, since destructors don't have return
11090 // types.
11091 if (!D.isInvalidType())
11092 return R;
11093
11094 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11095 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11096 EPI.Variadic = false;
11097 EPI.TypeQuals = Qualifiers();
11098 EPI.RefQualifier = RQ_None;
11099 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: std::nullopt, EPI);
11100}
11101
11102static void extendLeft(SourceRange &R, SourceRange Before) {
11103 if (Before.isInvalid())
11104 return;
11105 R.setBegin(Before.getBegin());
11106 if (R.getEnd().isInvalid())
11107 R.setEnd(Before.getEnd());
11108}
11109
11110static void extendRight(SourceRange &R, SourceRange After) {
11111 if (After.isInvalid())
11112 return;
11113 if (R.getBegin().isInvalid())
11114 R.setBegin(After.getBegin());
11115 R.setEnd(After.getEnd());
11116}
11117
11118/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
11119/// well-formednes of the conversion function declarator @p D with
11120/// type @p R. If there are any errors in the declarator, this routine
11121/// will emit diagnostics and return true. Otherwise, it will return
11122/// false. Either way, the type @p R will be updated to reflect a
11123/// well-formed type for the conversion operator.
11124void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11125 StorageClass& SC) {
11126 // C++ [class.conv.fct]p1:
11127 // Neither parameter types nor return type can be specified. The
11128 // type of a conversion function (8.3.5) is "function taking no
11129 // parameter returning conversion-type-id."
11130 if (SC == SC_Static) {
11131 if (!D.isInvalidType())
11132 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11133 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11134 << D.getName().getSourceRange();
11135 D.setInvalidType();
11136 SC = SC_None;
11137 }
11138
11139 TypeSourceInfo *ConvTSI = nullptr;
11140 QualType ConvType =
11141 GetTypeFromParser(Ty: D.getName().ConversionFunctionId, TInfo: &ConvTSI);
11142
11143 const DeclSpec &DS = D.getDeclSpec();
11144 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11145 // Conversion functions don't have return types, but the parser will
11146 // happily parse something like:
11147 //
11148 // class X {
11149 // float operator bool();
11150 // };
11151 //
11152 // The return type will be changed later anyway.
11153 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11154 << SourceRange(DS.getTypeSpecTypeLoc())
11155 << SourceRange(D.getIdentifierLoc());
11156 D.setInvalidType();
11157 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11158 // It's also plausible that the user writes type qualifiers in the wrong
11159 // place, such as:
11160 // struct S { const operator int(); };
11161 // FIXME: we could provide a fixit to move the qualifiers onto the
11162 // conversion type.
11163 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11164 << SourceRange(D.getIdentifierLoc()) << 0;
11165 D.setInvalidType();
11166 }
11167 const auto *Proto = R->castAs<FunctionProtoType>();
11168 // Make sure we don't have any parameters.
11169 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11170 unsigned NumParam = Proto->getNumParams();
11171
11172 // [C++2b]
11173 // A conversion function shall have no non-object parameters.
11174 if (NumParam == 1) {
11175 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11176 if (const auto *First =
11177 dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param);
11178 First && First->isExplicitObjectParameter())
11179 NumParam--;
11180 }
11181
11182 if (NumParam != 0) {
11183 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11184 // Delete the parameters.
11185 FTI.freeParams();
11186 D.setInvalidType();
11187 } else if (Proto->isVariadic()) {
11188 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11189 D.setInvalidType();
11190 }
11191
11192 // Diagnose "&operator bool()" and other such nonsense. This
11193 // is actually a gcc extension which we don't support.
11194 if (Proto->getReturnType() != ConvType) {
11195 bool NeedsTypedef = false;
11196 SourceRange Before, After;
11197
11198 // Walk the chunks and extract information on them for our diagnostic.
11199 bool PastFunctionChunk = false;
11200 for (auto &Chunk : D.type_objects()) {
11201 switch (Chunk.Kind) {
11202 case DeclaratorChunk::Function:
11203 if (!PastFunctionChunk) {
11204 if (Chunk.Fun.HasTrailingReturnType) {
11205 TypeSourceInfo *TRT = nullptr;
11206 GetTypeFromParser(Ty: Chunk.Fun.getTrailingReturnType(), TInfo: &TRT);
11207 if (TRT) extendRight(R&: After, After: TRT->getTypeLoc().getSourceRange());
11208 }
11209 PastFunctionChunk = true;
11210 break;
11211 }
11212 [[fallthrough]];
11213 case DeclaratorChunk::Array:
11214 NeedsTypedef = true;
11215 extendRight(R&: After, After: Chunk.getSourceRange());
11216 break;
11217
11218 case DeclaratorChunk::Pointer:
11219 case DeclaratorChunk::BlockPointer:
11220 case DeclaratorChunk::Reference:
11221 case DeclaratorChunk::MemberPointer:
11222 case DeclaratorChunk::Pipe:
11223 extendLeft(R&: Before, Before: Chunk.getSourceRange());
11224 break;
11225
11226 case DeclaratorChunk::Paren:
11227 extendLeft(R&: Before, Before: Chunk.Loc);
11228 extendRight(R&: After, After: Chunk.EndLoc);
11229 break;
11230 }
11231 }
11232
11233 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11234 After.isValid() ? After.getBegin() :
11235 D.getIdentifierLoc();
11236 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11237 DB << Before << After;
11238
11239 if (!NeedsTypedef) {
11240 DB << /*don't need a typedef*/0;
11241
11242 // If we can provide a correct fix-it hint, do so.
11243 if (After.isInvalid() && ConvTSI) {
11244 SourceLocation InsertLoc =
11245 getLocForEndOfToken(Loc: ConvTSI->getTypeLoc().getEndLoc());
11246 DB << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " ")
11247 << FixItHint::CreateInsertionFromRange(
11248 InsertionLoc: InsertLoc, FromRange: CharSourceRange::getTokenRange(R: Before))
11249 << FixItHint::CreateRemoval(RemoveRange: Before);
11250 }
11251 } else if (!Proto->getReturnType()->isDependentType()) {
11252 DB << /*typedef*/1 << Proto->getReturnType();
11253 } else if (getLangOpts().CPlusPlus11) {
11254 DB << /*alias template*/2 << Proto->getReturnType();
11255 } else {
11256 DB << /*might not be fixable*/3;
11257 }
11258
11259 // Recover by incorporating the other type chunks into the result type.
11260 // Note, this does *not* change the name of the function. This is compatible
11261 // with the GCC extension:
11262 // struct S { &operator int(); } s;
11263 // int &r = s.operator int(); // ok in GCC
11264 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11265 ConvType = Proto->getReturnType();
11266 }
11267
11268 // C++ [class.conv.fct]p4:
11269 // The conversion-type-id shall not represent a function type nor
11270 // an array type.
11271 if (ConvType->isArrayType()) {
11272 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11273 ConvType = Context.getPointerType(T: ConvType);
11274 D.setInvalidType();
11275 } else if (ConvType->isFunctionType()) {
11276 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11277 ConvType = Context.getPointerType(T: ConvType);
11278 D.setInvalidType();
11279 }
11280
11281 // Rebuild the function type "R" without any parameters (in case any
11282 // of the errors above fired) and with the conversion type as the
11283 // return type.
11284 if (D.isInvalidType())
11285 R = Context.getFunctionType(ResultTy: ConvType, Args: std::nullopt,
11286 EPI: Proto->getExtProtoInfo());
11287
11288 // C++0x explicit conversion operators.
11289 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11290 Diag(DS.getExplicitSpecLoc(),
11291 getLangOpts().CPlusPlus11
11292 ? diag::warn_cxx98_compat_explicit_conversion_functions
11293 : diag::ext_explicit_conversion_functions)
11294 << SourceRange(DS.getExplicitSpecRange());
11295}
11296
11297/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
11298/// the declaration of the given C++ conversion function. This routine
11299/// is responsible for recording the conversion function in the C++
11300/// class, if possible.
11301Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11302 assert(Conversion && "Expected to receive a conversion function declaration");
11303
11304 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11305
11306 // Make sure we aren't redeclaring the conversion function.
11307 QualType ConvType = Context.getCanonicalType(T: Conversion->getConversionType());
11308 // C++ [class.conv.fct]p1:
11309 // [...] A conversion function is never used to convert a
11310 // (possibly cv-qualified) object to the (possibly cv-qualified)
11311 // same object type (or a reference to it), to a (possibly
11312 // cv-qualified) base class of that type (or a reference to it),
11313 // or to (possibly cv-qualified) void.
11314 QualType ClassType
11315 = Context.getCanonicalType(T: Context.getTypeDeclType(ClassDecl));
11316 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11317 ConvType = ConvTypeRef->getPointeeType();
11318 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11319 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11320 /* Suppress diagnostics for instantiations. */;
11321 else if (Conversion->size_overridden_methods() != 0)
11322 /* Suppress diagnostics for overriding virtual function in a base class. */;
11323 else if (ConvType->isRecordType()) {
11324 ConvType = Context.getCanonicalType(T: ConvType).getUnqualifiedType();
11325 if (ConvType == ClassType)
11326 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11327 << ClassType;
11328 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11329 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11330 << ClassType << ConvType;
11331 } else if (ConvType->isVoidType()) {
11332 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11333 << ClassType << ConvType;
11334 }
11335
11336 if (FunctionTemplateDecl *ConversionTemplate =
11337 Conversion->getDescribedFunctionTemplate()) {
11338 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11339 ConvType = ConvTypePtr->getPointeeType();
11340 }
11341 if (ConvType->isUndeducedAutoType()) {
11342 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11343 << getReturnTypeLoc(Conversion).getSourceRange()
11344 << llvm::to_underlying(ConvType->getAs<AutoType>()->getKeyword())
11345 << /* in declaration of conversion function template= */ 24;
11346 }
11347
11348 return ConversionTemplate;
11349 }
11350
11351 return Conversion;
11352}
11353
11354void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11355 DeclarationName Name, QualType R) {
11356 CheckExplicitObjectMemberFunction(D, Name, R, IsLambda: false, DC);
11357}
11358
11359void Sema::CheckExplicitObjectLambda(Declarator &D) {
11360 CheckExplicitObjectMemberFunction(D, Name: {}, R: {}, IsLambda: true);
11361}
11362
11363void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11364 DeclarationName Name, QualType R,
11365 bool IsLambda, DeclContext *DC) {
11366 if (!D.isFunctionDeclarator())
11367 return;
11368
11369 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11370 if (FTI.NumParams == 0)
11371 return;
11372 ParmVarDecl *ExplicitObjectParam = nullptr;
11373 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11374 const auto &ParamInfo = FTI.Params[Idx];
11375 if (!ParamInfo.Param)
11376 continue;
11377 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamInfo.Param);
11378 if (!Param->isExplicitObjectParameter())
11379 continue;
11380 if (Idx == 0) {
11381 ExplicitObjectParam = Param;
11382 continue;
11383 } else {
11384 Diag(Param->getLocation(),
11385 diag::err_explicit_object_parameter_must_be_first)
11386 << IsLambda << Param->getSourceRange();
11387 }
11388 }
11389 if (!ExplicitObjectParam)
11390 return;
11391
11392 if (ExplicitObjectParam->hasDefaultArg()) {
11393 Diag(ExplicitObjectParam->getLocation(),
11394 diag::err_explicit_object_default_arg)
11395 << ExplicitObjectParam->getSourceRange();
11396 }
11397
11398 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) {
11399 Diag(ExplicitObjectParam->getBeginLoc(),
11400 diag::err_explicit_object_parameter_nonmember)
11401 << D.getSourceRange() << /*static=*/0 << IsLambda;
11402 D.setInvalidType();
11403 }
11404
11405 if (D.getDeclSpec().isVirtualSpecified()) {
11406 Diag(ExplicitObjectParam->getBeginLoc(),
11407 diag::err_explicit_object_parameter_nonmember)
11408 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11409 D.setInvalidType();
11410 }
11411
11412 if (IsLambda && FTI.hasMutableQualifier()) {
11413 Diag(ExplicitObjectParam->getBeginLoc(),
11414 diag::err_explicit_object_parameter_mutable)
11415 << D.getSourceRange();
11416 }
11417
11418 if (IsLambda)
11419 return;
11420
11421 if (!DC || !DC->isRecord()) {
11422 Diag(ExplicitObjectParam->getLocation(),
11423 diag::err_explicit_object_parameter_nonmember)
11424 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11425 D.setInvalidType();
11426 return;
11427 }
11428
11429 // CWG2674: constructors and destructors cannot have explicit parameters.
11430 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11431 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11432 Diag(ExplicitObjectParam->getBeginLoc(),
11433 diag::err_explicit_object_parameter_constructor)
11434 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11435 << D.getSourceRange();
11436 D.setInvalidType();
11437 }
11438}
11439
11440namespace {
11441/// Utility class to accumulate and print a diagnostic listing the invalid
11442/// specifier(s) on a declaration.
11443struct BadSpecifierDiagnoser {
11444 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11445 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11446 ~BadSpecifierDiagnoser() {
11447 Diagnostic << Specifiers;
11448 }
11449
11450 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11451 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11452 }
11453 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11454 return check(SpecLoc,
11455 Spec: DeclSpec::getSpecifierName(T: Spec, Policy: S.getPrintingPolicy()));
11456 }
11457 void check(SourceLocation SpecLoc, const char *Spec) {
11458 if (SpecLoc.isInvalid()) return;
11459 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11460 if (!Specifiers.empty()) Specifiers += " ";
11461 Specifiers += Spec;
11462 }
11463
11464 Sema &S;
11465 Sema::SemaDiagnosticBuilder Diagnostic;
11466 std::string Specifiers;
11467};
11468}
11469
11470/// Check the validity of a declarator that we parsed for a deduction-guide.
11471/// These aren't actually declarators in the grammar, so we need to check that
11472/// the user didn't specify any pieces that are not part of the deduction-guide
11473/// grammar. Return true on invalid deduction-guide.
11474bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11475 StorageClass &SC) {
11476 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11477 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11478 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11479
11480 // C++ [temp.deduct.guide]p3:
11481 // A deduction-gide shall be declared in the same scope as the
11482 // corresponding class template.
11483 if (!CurContext->getRedeclContext()->Equals(
11484 DC: GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11485 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11486 << GuidedTemplateDecl;
11487 NoteTemplateLocation(*GuidedTemplateDecl);
11488 }
11489
11490 auto &DS = D.getMutableDeclSpec();
11491 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11492 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11493 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11494 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11495 BadSpecifierDiagnoser Diagnoser(
11496 *this, D.getIdentifierLoc(),
11497 diag::err_deduction_guide_invalid_specifier);
11498
11499 Diagnoser.check(SpecLoc: DS.getStorageClassSpecLoc(), Spec: DS.getStorageClassSpec());
11500 DS.ClearStorageClassSpecs();
11501 SC = SC_None;
11502
11503 // 'explicit' is permitted.
11504 Diagnoser.check(SpecLoc: DS.getInlineSpecLoc(), Spec: "inline");
11505 Diagnoser.check(SpecLoc: DS.getNoreturnSpecLoc(), Spec: "_Noreturn");
11506 Diagnoser.check(SpecLoc: DS.getConstexprSpecLoc(), Spec: "constexpr");
11507 DS.ClearConstexprSpec();
11508
11509 Diagnoser.check(SpecLoc: DS.getConstSpecLoc(), Spec: "const");
11510 Diagnoser.check(SpecLoc: DS.getRestrictSpecLoc(), Spec: "__restrict");
11511 Diagnoser.check(SpecLoc: DS.getVolatileSpecLoc(), Spec: "volatile");
11512 Diagnoser.check(SpecLoc: DS.getAtomicSpecLoc(), Spec: "_Atomic");
11513 Diagnoser.check(SpecLoc: DS.getUnalignedSpecLoc(), Spec: "__unaligned");
11514 DS.ClearTypeQualifiers();
11515
11516 Diagnoser.check(SpecLoc: DS.getTypeSpecComplexLoc(), Spec: DS.getTypeSpecComplex());
11517 Diagnoser.check(SpecLoc: DS.getTypeSpecSignLoc(), Spec: DS.getTypeSpecSign());
11518 Diagnoser.check(SpecLoc: DS.getTypeSpecWidthLoc(), Spec: DS.getTypeSpecWidth());
11519 Diagnoser.check(SpecLoc: DS.getTypeSpecTypeLoc(), Spec: DS.getTypeSpecType());
11520 DS.ClearTypeSpecType();
11521 }
11522
11523 if (D.isInvalidType())
11524 return true;
11525
11526 // Check the declarator is simple enough.
11527 bool FoundFunction = false;
11528 for (const DeclaratorChunk &Chunk : llvm::reverse(C: D.type_objects())) {
11529 if (Chunk.Kind == DeclaratorChunk::Paren)
11530 continue;
11531 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11532 Diag(D.getDeclSpec().getBeginLoc(),
11533 diag::err_deduction_guide_with_complex_decl)
11534 << D.getSourceRange();
11535 break;
11536 }
11537 if (!Chunk.Fun.hasTrailingReturnType())
11538 return Diag(D.getName().getBeginLoc(),
11539 diag::err_deduction_guide_no_trailing_return_type);
11540
11541 // Check that the return type is written as a specialization of
11542 // the template specified as the deduction-guide's name.
11543 // The template name may not be qualified. [temp.deduct.guide]
11544 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11545 TypeSourceInfo *TSI = nullptr;
11546 QualType RetTy = GetTypeFromParser(Ty: TrailingReturnType, TInfo: &TSI);
11547 assert(TSI && "deduction guide has valid type but invalid return type?");
11548 bool AcceptableReturnType = false;
11549 bool MightInstantiateToSpecialization = false;
11550 if (auto RetTST =
11551 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11552 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11553 bool TemplateMatches =
11554 Context.hasSameTemplateName(X: SpecifiedName, Y: GuidedTemplate);
11555 auto TKind = SpecifiedName.getKind();
11556 // A Using TemplateName can't actually be valid (either it's qualified, or
11557 // we're in the wrong scope). But we have diagnosed these problems
11558 // already.
11559 bool SimplyWritten = TKind == TemplateName::Template ||
11560 TKind == TemplateName::UsingTemplate;
11561 if (SimplyWritten && TemplateMatches)
11562 AcceptableReturnType = true;
11563 else {
11564 // This could still instantiate to the right type, unless we know it
11565 // names the wrong class template.
11566 auto *TD = SpecifiedName.getAsTemplateDecl();
11567 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11568 !TemplateMatches);
11569 }
11570 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11571 MightInstantiateToSpecialization = true;
11572 }
11573
11574 if (!AcceptableReturnType)
11575 return Diag(TSI->getTypeLoc().getBeginLoc(),
11576 diag::err_deduction_guide_bad_trailing_return_type)
11577 << GuidedTemplate << TSI->getType()
11578 << MightInstantiateToSpecialization
11579 << TSI->getTypeLoc().getSourceRange();
11580
11581 // Keep going to check that we don't have any inner declarator pieces (we
11582 // could still have a function returning a pointer to a function).
11583 FoundFunction = true;
11584 }
11585
11586 if (D.isFunctionDefinition())
11587 // we can still create a valid deduction guide here.
11588 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11589 return false;
11590}
11591
11592//===----------------------------------------------------------------------===//
11593// Namespace Handling
11594//===----------------------------------------------------------------------===//
11595
11596/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11597/// reopened.
11598static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11599 SourceLocation Loc,
11600 IdentifierInfo *II, bool *IsInline,
11601 NamespaceDecl *PrevNS) {
11602 assert(*IsInline != PrevNS->isInline());
11603
11604 // 'inline' must appear on the original definition, but not necessarily
11605 // on all extension definitions, so the note should point to the first
11606 // definition to avoid confusion.
11607 PrevNS = PrevNS->getFirstDecl();
11608
11609 if (PrevNS->isInline())
11610 // The user probably just forgot the 'inline', so suggest that it
11611 // be added back.
11612 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11613 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11614 else
11615 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11616
11617 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11618 *IsInline = PrevNS->isInline();
11619}
11620
11621/// ActOnStartNamespaceDef - This is called at the start of a namespace
11622/// definition.
11623Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11624 SourceLocation InlineLoc,
11625 SourceLocation NamespaceLoc,
11626 SourceLocation IdentLoc, IdentifierInfo *II,
11627 SourceLocation LBrace,
11628 const ParsedAttributesView &AttrList,
11629 UsingDirectiveDecl *&UD, bool IsNested) {
11630 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11631 // For anonymous namespace, take the location of the left brace.
11632 SourceLocation Loc = II ? IdentLoc : LBrace;
11633 bool IsInline = InlineLoc.isValid();
11634 bool IsInvalid = false;
11635 bool IsStd = false;
11636 bool AddToKnown = false;
11637 Scope *DeclRegionScope = NamespcScope->getParent();
11638
11639 NamespaceDecl *PrevNS = nullptr;
11640 if (II) {
11641 // C++ [namespace.std]p7:
11642 // A translation unit shall not declare namespace std to be an inline
11643 // namespace (9.8.2).
11644 //
11645 // Precondition: the std namespace is in the file scope and is declared to
11646 // be inline
11647 auto DiagnoseInlineStdNS = [&]() {
11648 assert(IsInline && II->isStr("std") &&
11649 CurContext->getRedeclContext()->isTranslationUnit() &&
11650 "Precondition of DiagnoseInlineStdNS not met");
11651 Diag(InlineLoc, diag::err_inline_namespace_std)
11652 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11653 IsInline = false;
11654 };
11655 // C++ [namespace.def]p2:
11656 // The identifier in an original-namespace-definition shall not
11657 // have been previously defined in the declarative region in
11658 // which the original-namespace-definition appears. The
11659 // identifier in an original-namespace-definition is the name of
11660 // the namespace. Subsequently in that declarative region, it is
11661 // treated as an original-namespace-name.
11662 //
11663 // Since namespace names are unique in their scope, and we don't
11664 // look through using directives, just look for any ordinary names
11665 // as if by qualified name lookup.
11666 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11667 ForExternalRedeclaration);
11668 LookupQualifiedName(R, LookupCtx: CurContext->getRedeclContext());
11669 NamedDecl *PrevDecl =
11670 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11671 PrevNS = dyn_cast_or_null<NamespaceDecl>(Val: PrevDecl);
11672
11673 if (PrevNS) {
11674 // This is an extended namespace definition.
11675 if (IsInline && II->isStr(Str: "std") &&
11676 CurContext->getRedeclContext()->isTranslationUnit())
11677 DiagnoseInlineStdNS();
11678 else if (IsInline != PrevNS->isInline())
11679 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc, II,
11680 IsInline: &IsInline, PrevNS);
11681 } else if (PrevDecl) {
11682 // This is an invalid name redefinition.
11683 Diag(Loc, diag::err_redefinition_different_kind)
11684 << II;
11685 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11686 IsInvalid = true;
11687 // Continue on to push Namespc as current DeclContext and return it.
11688 } else if (II->isStr(Str: "std") &&
11689 CurContext->getRedeclContext()->isTranslationUnit()) {
11690 if (IsInline)
11691 DiagnoseInlineStdNS();
11692 // This is the first "real" definition of the namespace "std", so update
11693 // our cache of the "std" namespace to point at this definition.
11694 PrevNS = getStdNamespace();
11695 IsStd = true;
11696 AddToKnown = !IsInline;
11697 } else {
11698 // We've seen this namespace for the first time.
11699 AddToKnown = !IsInline;
11700 }
11701 } else {
11702 // Anonymous namespaces.
11703
11704 // Determine whether the parent already has an anonymous namespace.
11705 DeclContext *Parent = CurContext->getRedeclContext();
11706 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
11707 PrevNS = TU->getAnonymousNamespace();
11708 } else {
11709 NamespaceDecl *ND = cast<NamespaceDecl>(Val: Parent);
11710 PrevNS = ND->getAnonymousNamespace();
11711 }
11712
11713 if (PrevNS && IsInline != PrevNS->isInline())
11714 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc: NamespaceLoc, II,
11715 IsInline: &IsInline, PrevNS);
11716 }
11717
11718 NamespaceDecl *Namespc = NamespaceDecl::Create(
11719 C&: Context, DC: CurContext, Inline: IsInline, StartLoc, IdLoc: Loc, Id: II, PrevDecl: PrevNS, Nested: IsNested);
11720 if (IsInvalid)
11721 Namespc->setInvalidDecl();
11722
11723 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11724 AddPragmaAttributes(DeclRegionScope, Namespc);
11725
11726 // FIXME: Should we be merging attributes?
11727 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11728 PushNamespaceVisibilityAttr(Attr, Loc);
11729
11730 if (IsStd)
11731 StdNamespace = Namespc;
11732 if (AddToKnown)
11733 KnownNamespaces[Namespc] = false;
11734
11735 if (II) {
11736 PushOnScopeChains(Namespc, DeclRegionScope);
11737 } else {
11738 // Link the anonymous namespace into its parent.
11739 DeclContext *Parent = CurContext->getRedeclContext();
11740 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
11741 TU->setAnonymousNamespace(Namespc);
11742 } else {
11743 cast<NamespaceDecl>(Val: Parent)->setAnonymousNamespace(Namespc);
11744 }
11745
11746 CurContext->addDecl(Namespc);
11747
11748 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11749 // behaves as if it were replaced by
11750 // namespace unique { /* empty body */ }
11751 // using namespace unique;
11752 // namespace unique { namespace-body }
11753 // where all occurrences of 'unique' in a translation unit are
11754 // replaced by the same identifier and this identifier differs
11755 // from all other identifiers in the entire program.
11756
11757 // We just create the namespace with an empty name and then add an
11758 // implicit using declaration, just like the standard suggests.
11759 //
11760 // CodeGen enforces the "universally unique" aspect by giving all
11761 // declarations semantically contained within an anonymous
11762 // namespace internal linkage.
11763
11764 if (!PrevNS) {
11765 UD = UsingDirectiveDecl::Create(Context, Parent,
11766 /* 'using' */ LBrace,
11767 /* 'namespace' */ SourceLocation(),
11768 /* qualifier */ NestedNameSpecifierLoc(),
11769 /* identifier */ SourceLocation(),
11770 Namespc,
11771 /* Ancestor */ Parent);
11772 UD->setImplicit();
11773 Parent->addDecl(UD);
11774 }
11775 }
11776
11777 ActOnDocumentableDecl(Namespc);
11778
11779 // Although we could have an invalid decl (i.e. the namespace name is a
11780 // redefinition), push it as current DeclContext and try to continue parsing.
11781 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11782 // for the namespace has the declarations that showed up in that particular
11783 // namespace definition.
11784 PushDeclContext(NamespcScope, Namespc);
11785 return Namespc;
11786}
11787
11788/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11789/// is a namespace alias, returns the namespace it points to.
11790static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11791 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(Val: D))
11792 return AD->getNamespace();
11793 return dyn_cast_or_null<NamespaceDecl>(Val: D);
11794}
11795
11796/// ActOnFinishNamespaceDef - This callback is called after a namespace is
11797/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11798void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11799 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Val: Dcl);
11800 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11801 Namespc->setRBraceLoc(RBrace);
11802 PopDeclContext();
11803 if (Namespc->hasAttr<VisibilityAttr>())
11804 PopPragmaVisibility(IsNamespaceEnd: true, EndLoc: RBrace);
11805 // If this namespace contains an export-declaration, export it now.
11806 if (DeferredExportedNamespaces.erase(Ptr: Namespc))
11807 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11808}
11809
11810CXXRecordDecl *Sema::getStdBadAlloc() const {
11811 return cast_or_null<CXXRecordDecl>(
11812 Val: StdBadAlloc.get(Source: Context.getExternalSource()));
11813}
11814
11815EnumDecl *Sema::getStdAlignValT() const {
11816 return cast_or_null<EnumDecl>(Val: StdAlignValT.get(Source: Context.getExternalSource()));
11817}
11818
11819NamespaceDecl *Sema::getStdNamespace() const {
11820 return cast_or_null<NamespaceDecl>(
11821 Val: StdNamespace.get(Source: Context.getExternalSource()));
11822}
11823namespace {
11824
11825enum UnsupportedSTLSelect {
11826 USS_InvalidMember,
11827 USS_MissingMember,
11828 USS_NonTrivial,
11829 USS_Other
11830};
11831
11832struct InvalidSTLDiagnoser {
11833 Sema &S;
11834 SourceLocation Loc;
11835 QualType TyForDiags;
11836
11837 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11838 const VarDecl *VD = nullptr) {
11839 {
11840 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11841 << TyForDiags << ((int)Sel);
11842 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11843 assert(!Name.empty());
11844 D << Name;
11845 }
11846 }
11847 if (Sel == USS_InvalidMember) {
11848 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11849 << VD << VD->getSourceRange();
11850 }
11851 return QualType();
11852 }
11853};
11854} // namespace
11855
11856QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11857 SourceLocation Loc,
11858 ComparisonCategoryUsage Usage) {
11859 assert(getLangOpts().CPlusPlus &&
11860 "Looking for comparison category type outside of C++.");
11861
11862 // Use an elaborated type for diagnostics which has a name containing the
11863 // prepended 'std' namespace but not any inline namespace names.
11864 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11865 auto *NNS =
11866 NestedNameSpecifier::Create(Context, Prefix: nullptr, NS: getStdNamespace());
11867 return Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS,
11868 NamedType: Info->getType());
11869 };
11870
11871 // Check if we've already successfully checked the comparison category type
11872 // before. If so, skip checking it again.
11873 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11874 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11875 // The only thing we need to check is that the type has a reachable
11876 // definition in the current context.
11877 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11878 return QualType();
11879
11880 return Info->getType();
11881 }
11882
11883 // If lookup failed
11884 if (!Info) {
11885 std::string NameForDiags = "std::";
11886 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11887 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11888 << NameForDiags << (int)Usage;
11889 return QualType();
11890 }
11891
11892 assert(Info->Kind == Kind);
11893 assert(Info->Record);
11894
11895 // Update the Record decl in case we encountered a forward declaration on our
11896 // first pass. FIXME: This is a bit of a hack.
11897 if (Info->Record->hasDefinition())
11898 Info->Record = Info->Record->getDefinition();
11899
11900 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11901 return QualType();
11902
11903 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11904
11905 if (!Info->Record->isTriviallyCopyable())
11906 return UnsupportedSTLError(USS_NonTrivial);
11907
11908 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11909 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11910 // Tolerate empty base classes.
11911 if (Base->isEmpty())
11912 continue;
11913 // Reject STL implementations which have at least one non-empty base.
11914 return UnsupportedSTLError();
11915 }
11916
11917 // Check that the STL has implemented the types using a single integer field.
11918 // This expectation allows better codegen for builtin operators. We require:
11919 // (1) The class has exactly one field.
11920 // (2) The field is an integral or enumeration type.
11921 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11922 if (std::distance(FIt, FEnd) != 1 ||
11923 !FIt->getType()->isIntegralOrEnumerationType()) {
11924 return UnsupportedSTLError();
11925 }
11926
11927 // Build each of the require values and store them in Info.
11928 for (ComparisonCategoryResult CCR :
11929 ComparisonCategories::getPossibleResultsForType(Type: Kind)) {
11930 StringRef MemName = ComparisonCategories::getResultString(Kind: CCR);
11931 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(ValueKind: CCR);
11932
11933 if (!ValInfo)
11934 return UnsupportedSTLError(USS_MissingMember, MemName);
11935
11936 VarDecl *VD = ValInfo->VD;
11937 assert(VD && "should not be null!");
11938
11939 // Attempt to diagnose reasons why the STL definition of this type
11940 // might be foobar, including it failing to be a constant expression.
11941 // TODO Handle more ways the lookup or result can be invalid.
11942 if (!VD->isStaticDataMember() ||
11943 !VD->isUsableInConstantExpressions(C: Context))
11944 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11945
11946 // Attempt to evaluate the var decl as a constant expression and extract
11947 // the value of its first field as a ICE. If this fails, the STL
11948 // implementation is not supported.
11949 if (!ValInfo->hasValidIntValue())
11950 return UnsupportedSTLError();
11951
11952 MarkVariableReferenced(Loc, Var: VD);
11953 }
11954
11955 // We've successfully built the required types and expressions. Update
11956 // the cache and return the newly cached value.
11957 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11958 return Info->getType();
11959}
11960
11961/// Retrieve the special "std" namespace, which may require us to
11962/// implicitly define the namespace.
11963NamespaceDecl *Sema::getOrCreateStdNamespace() {
11964 if (!StdNamespace) {
11965 // The "std" namespace has not yet been defined, so build one implicitly.
11966 StdNamespace = NamespaceDecl::Create(
11967 Context, Context.getTranslationUnitDecl(),
11968 /*Inline=*/false, SourceLocation(), SourceLocation(),
11969 &PP.getIdentifierTable().get(Name: "std"),
11970 /*PrevDecl=*/nullptr, /*Nested=*/false);
11971 getStdNamespace()->setImplicit(true);
11972 // We want the created NamespaceDecl to be available for redeclaration
11973 // lookups, but not for regular name lookups.
11974 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
11975 getStdNamespace()->clearIdentifierNamespace();
11976 }
11977
11978 return getStdNamespace();
11979}
11980
11981bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11982 assert(getLangOpts().CPlusPlus &&
11983 "Looking for std::initializer_list outside of C++.");
11984
11985 // We're looking for implicit instantiations of
11986 // template <typename E> class std::initializer_list.
11987
11988 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11989 return false;
11990
11991 ClassTemplateDecl *Template = nullptr;
11992 const TemplateArgument *Arguments = nullptr;
11993
11994 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11995
11996 ClassTemplateSpecializationDecl *Specialization =
11997 dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
11998 if (!Specialization)
11999 return false;
12000
12001 Template = Specialization->getSpecializedTemplate();
12002 Arguments = Specialization->getTemplateArgs().data();
12003 } else if (const TemplateSpecializationType *TST =
12004 Ty->getAs<TemplateSpecializationType>()) {
12005 Template = dyn_cast_or_null<ClassTemplateDecl>(
12006 Val: TST->getTemplateName().getAsTemplateDecl());
12007 Arguments = TST->template_arguments().begin();
12008 }
12009 if (!Template)
12010 return false;
12011
12012 if (!StdInitializerList) {
12013 // Haven't recognized std::initializer_list yet, maybe this is it.
12014 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12015 if (TemplateClass->getIdentifier() !=
12016 &PP.getIdentifierTable().get(Name: "initializer_list") ||
12017 !getStdNamespace()->InEnclosingNamespaceSetOf(
12018 NS: TemplateClass->getDeclContext()))
12019 return false;
12020 // This is a template called std::initializer_list, but is it the right
12021 // template?
12022 TemplateParameterList *Params = Template->getTemplateParameters();
12023 if (Params->getMinRequiredArguments() != 1)
12024 return false;
12025 if (!isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0)))
12026 return false;
12027
12028 // It's the right template.
12029 StdInitializerList = Template;
12030 }
12031
12032 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
12033 return false;
12034
12035 // This is an instance of std::initializer_list. Find the argument type.
12036 if (Element)
12037 *Element = Arguments[0].getAsType();
12038 return true;
12039}
12040
12041static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
12042 NamespaceDecl *Std = S.getStdNamespace();
12043 if (!Std) {
12044 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12045 return nullptr;
12046 }
12047
12048 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: "initializer_list"),
12049 Loc, Sema::LookupOrdinaryName);
12050 if (!S.LookupQualifiedName(Result, Std)) {
12051 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12052 return nullptr;
12053 }
12054 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12055 if (!Template) {
12056 Result.suppressDiagnostics();
12057 // We found something weird. Complain about the first thing we found.
12058 NamedDecl *Found = *Result.begin();
12059 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
12060 return nullptr;
12061 }
12062
12063 // We found some template called std::initializer_list. Now verify that it's
12064 // correct.
12065 TemplateParameterList *Params = Template->getTemplateParameters();
12066 if (Params->getMinRequiredArguments() != 1 ||
12067 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
12068 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
12069 return nullptr;
12070 }
12071
12072 return Template;
12073}
12074
12075QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12076 if (!StdInitializerList) {
12077 StdInitializerList = LookupStdInitializerList(S&: *this, Loc);
12078 if (!StdInitializerList)
12079 return QualType();
12080 }
12081
12082 TemplateArgumentListInfo Args(Loc, Loc);
12083 Args.addArgument(Loc: TemplateArgumentLoc(TemplateArgument(Element),
12084 Context.getTrivialTypeSourceInfo(T: Element,
12085 Loc)));
12086 return Context.getElaboratedType(
12087 Keyword: ElaboratedTypeKeyword::None,
12088 NNS: NestedNameSpecifier::Create(Context, Prefix: nullptr, NS: getStdNamespace()),
12089 NamedType: CheckTemplateIdType(Template: TemplateName(StdInitializerList), TemplateLoc: Loc, TemplateArgs&: Args));
12090}
12091
12092bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12093 // C++ [dcl.init.list]p2:
12094 // A constructor is an initializer-list constructor if its first parameter
12095 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12096 // std::initializer_list<E> for some type E, and either there are no other
12097 // parameters or else all other parameters have default arguments.
12098 if (!Ctor->hasOneParamOrDefaultArgs())
12099 return false;
12100
12101 QualType ArgType = Ctor->getParamDecl(i: 0)->getType();
12102 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12103 ArgType = RT->getPointeeType().getUnqualifiedType();
12104
12105 return isStdInitializerList(Ty: ArgType, Element: nullptr);
12106}
12107
12108/// Determine whether a using statement is in a context where it will be
12109/// apply in all contexts.
12110static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12111 switch (CurContext->getDeclKind()) {
12112 case Decl::TranslationUnit:
12113 return true;
12114 case Decl::LinkageSpec:
12115 return IsUsingDirectiveInToplevelContext(CurContext: CurContext->getParent());
12116 default:
12117 return false;
12118 }
12119}
12120
12121namespace {
12122
12123// Callback to only accept typo corrections that are namespaces.
12124class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12125public:
12126 bool ValidateCandidate(const TypoCorrection &candidate) override {
12127 if (NamedDecl *ND = candidate.getCorrectionDecl())
12128 return isa<NamespaceDecl>(Val: ND) || isa<NamespaceAliasDecl>(Val: ND);
12129 return false;
12130 }
12131
12132 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12133 return std::make_unique<NamespaceValidatorCCC>(args&: *this);
12134 }
12135};
12136
12137}
12138
12139static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12140 Sema &S) {
12141 auto *ND = cast<NamespaceDecl>(Val: Corrected.getFoundDecl());
12142 Module *M = ND->getOwningModule();
12143 assert(M && "hidden namespace definition not in a module?");
12144
12145 if (M->isExplicitGlobalModule())
12146 S.Diag(Corrected.getCorrectionRange().getBegin(),
12147 diag::err_module_unimported_use_header)
12148 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12149 << /*Header Name*/ false;
12150 else
12151 S.Diag(Corrected.getCorrectionRange().getBegin(),
12152 diag::err_module_unimported_use)
12153 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12154 << M->getTopLevelModuleName();
12155}
12156
12157static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12158 CXXScopeSpec &SS,
12159 SourceLocation IdentLoc,
12160 IdentifierInfo *Ident) {
12161 R.clear();
12162 NamespaceValidatorCCC CCC{};
12163 if (TypoCorrection Corrected =
12164 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Sc, SS: &SS, CCC,
12165 Mode: Sema::CTK_ErrorRecovery)) {
12166 // Generally we find it is confusing more than helpful to diagnose the
12167 // invisible namespace.
12168 // See https://github.com/llvm/llvm-project/issues/73893.
12169 //
12170 // However, we should diagnose when the users are trying to using an
12171 // invisible namespace. So we handle the case specially here.
12172 if (isa_and_nonnull<NamespaceDecl>(Val: Corrected.getFoundDecl()) &&
12173 Corrected.requiresImport()) {
12174 DiagnoseInvisibleNamespace(Corrected, S);
12175 } else if (DeclContext *DC = S.computeDeclContext(SS, EnteringContext: false)) {
12176 std::string CorrectedStr(Corrected.getAsString(LO: S.getLangOpts()));
12177 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
12178 Ident->getName().equals(RHS: CorrectedStr);
12179 S.diagnoseTypo(Corrected,
12180 S.PDiag(diag::err_using_directive_member_suggest)
12181 << Ident << DC << DroppedSpecifier << SS.getRange(),
12182 S.PDiag(diag::note_namespace_defined_here));
12183 } else {
12184 S.diagnoseTypo(Corrected,
12185 S.PDiag(diag::err_using_directive_suggest) << Ident,
12186 S.PDiag(diag::note_namespace_defined_here));
12187 }
12188 R.addDecl(D: Corrected.getFoundDecl());
12189 return true;
12190 }
12191 return false;
12192}
12193
12194Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12195 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12196 SourceLocation IdentLoc,
12197 IdentifierInfo *NamespcName,
12198 const ParsedAttributesView &AttrList) {
12199 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12200 assert(NamespcName && "Invalid NamespcName.");
12201 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12202
12203 // This can only happen along a recovery path.
12204 while (S->isTemplateParamScope())
12205 S = S->getParent();
12206 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12207
12208 UsingDirectiveDecl *UDir = nullptr;
12209 NestedNameSpecifier *Qualifier = nullptr;
12210 if (SS.isSet())
12211 Qualifier = SS.getScopeRep();
12212
12213 // Lookup namespace name.
12214 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12215 LookupParsedName(R, S, SS: &SS);
12216 if (R.isAmbiguous())
12217 return nullptr;
12218
12219 if (R.empty()) {
12220 R.clear();
12221 // Allow "using namespace std;" or "using namespace ::std;" even if
12222 // "std" hasn't been defined yet, for GCC compatibility.
12223 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12224 NamespcName->isStr(Str: "std")) {
12225 Diag(IdentLoc, diag::ext_using_undefined_std);
12226 R.addDecl(getOrCreateStdNamespace());
12227 R.resolveKind();
12228 }
12229 // Otherwise, attempt typo correction.
12230 else TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident: NamespcName);
12231 }
12232
12233 if (!R.empty()) {
12234 NamedDecl *Named = R.getRepresentativeDecl();
12235 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12236 assert(NS && "expected namespace decl");
12237
12238 // The use of a nested name specifier may trigger deprecation warnings.
12239 DiagnoseUseOfDecl(D: Named, Locs: IdentLoc);
12240
12241 // C++ [namespace.udir]p1:
12242 // A using-directive specifies that the names in the nominated
12243 // namespace can be used in the scope in which the
12244 // using-directive appears after the using-directive. During
12245 // unqualified name lookup (3.4.1), the names appear as if they
12246 // were declared in the nearest enclosing namespace which
12247 // contains both the using-directive and the nominated
12248 // namespace. [Note: in this context, "contains" means "contains
12249 // directly or indirectly". ]
12250
12251 // Find enclosing context containing both using-directive and
12252 // nominated namespace.
12253 DeclContext *CommonAncestor = NS;
12254 while (CommonAncestor && !CommonAncestor->Encloses(DC: CurContext))
12255 CommonAncestor = CommonAncestor->getParent();
12256
12257 UDir = UsingDirectiveDecl::Create(C&: Context, DC: CurContext, UsingLoc, NamespaceLoc: NamespcLoc,
12258 QualifierLoc: SS.getWithLocInContext(Context),
12259 IdentLoc, Nominated: Named, CommonAncestor);
12260
12261 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12262 !SourceMgr.isInMainFile(Loc: SourceMgr.getExpansionLoc(Loc: IdentLoc))) {
12263 Diag(IdentLoc, diag::warn_using_directive_in_header);
12264 }
12265
12266 PushUsingDirective(S, UDir);
12267 } else {
12268 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12269 }
12270
12271 if (UDir)
12272 ProcessDeclAttributeList(S, UDir, AttrList);
12273
12274 return UDir;
12275}
12276
12277void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12278 // If the scope has an associated entity and the using directive is at
12279 // namespace or translation unit scope, add the UsingDirectiveDecl into
12280 // its lookup structure so qualified name lookup can find it.
12281 DeclContext *Ctx = S->getEntity();
12282 if (Ctx && !Ctx->isFunctionOrMethod())
12283 Ctx->addDecl(UDir);
12284 else
12285 // Otherwise, it is at block scope. The using-directives will affect lookup
12286 // only to the end of the scope.
12287 S->PushUsingDirective(UDir);
12288}
12289
12290Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12291 SourceLocation UsingLoc,
12292 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12293 UnqualifiedId &Name,
12294 SourceLocation EllipsisLoc,
12295 const ParsedAttributesView &AttrList) {
12296 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12297
12298 if (SS.isEmpty()) {
12299 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12300 return nullptr;
12301 }
12302
12303 switch (Name.getKind()) {
12304 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12305 case UnqualifiedIdKind::IK_Identifier:
12306 case UnqualifiedIdKind::IK_OperatorFunctionId:
12307 case UnqualifiedIdKind::IK_LiteralOperatorId:
12308 case UnqualifiedIdKind::IK_ConversionFunctionId:
12309 break;
12310
12311 case UnqualifiedIdKind::IK_ConstructorName:
12312 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12313 // C++11 inheriting constructors.
12314 Diag(Name.getBeginLoc(),
12315 getLangOpts().CPlusPlus11
12316 ? diag::warn_cxx98_compat_using_decl_constructor
12317 : diag::err_using_decl_constructor)
12318 << SS.getRange();
12319
12320 if (getLangOpts().CPlusPlus11) break;
12321
12322 return nullptr;
12323
12324 case UnqualifiedIdKind::IK_DestructorName:
12325 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12326 return nullptr;
12327
12328 case UnqualifiedIdKind::IK_TemplateId:
12329 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12330 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12331 return nullptr;
12332
12333 case UnqualifiedIdKind::IK_DeductionGuideName:
12334 llvm_unreachable("cannot parse qualified deduction guide name");
12335 }
12336
12337 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12338 DeclarationName TargetName = TargetNameInfo.getName();
12339 if (!TargetName)
12340 return nullptr;
12341
12342 // Warn about access declarations.
12343 if (UsingLoc.isInvalid()) {
12344 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12345 ? diag::err_access_decl
12346 : diag::warn_access_decl_deprecated)
12347 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12348 }
12349
12350 if (EllipsisLoc.isInvalid()) {
12351 if (DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_UsingDeclaration) ||
12352 DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC: UPPC_UsingDeclaration))
12353 return nullptr;
12354 } else {
12355 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
12356 !TargetNameInfo.containsUnexpandedParameterPack()) {
12357 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12358 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12359 EllipsisLoc = SourceLocation();
12360 }
12361 }
12362
12363 NamedDecl *UD =
12364 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12365 SS, TargetNameInfo, EllipsisLoc, AttrList,
12366 /*IsInstantiation*/ false,
12367 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12368 if (UD)
12369 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12370
12371 return UD;
12372}
12373
12374Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12375 SourceLocation UsingLoc,
12376 SourceLocation EnumLoc,
12377 SourceLocation IdentLoc,
12378 IdentifierInfo &II, CXXScopeSpec *SS) {
12379 assert(!SS->isInvalid() && "ScopeSpec is invalid");
12380 TypeSourceInfo *TSI = nullptr;
12381 QualType EnumTy = GetTypeFromParser(
12382 Ty: getTypeName(II, NameLoc: IdentLoc, S, SS, /*isClassName=*/false,
12383 /*HasTrailingDot=*/false,
12384 /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
12385 /*WantNontrivialTypeSourceInfo=*/true),
12386 TInfo: &TSI);
12387 if (EnumTy.isNull()) {
12388 Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
12389 ? diag::err_using_enum_is_dependent
12390 : diag::err_unknown_typename)
12391 << II.getName()
12392 << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
12393 return nullptr;
12394 }
12395
12396 auto *Enum = dyn_cast_if_present<EnumDecl>(Val: EnumTy->getAsTagDecl());
12397 if (!Enum) {
12398 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12399 return nullptr;
12400 }
12401
12402 if (auto *Def = Enum->getDefinition())
12403 Enum = Def;
12404
12405 if (TSI == nullptr)
12406 TSI = Context.getTrivialTypeSourceInfo(T: EnumTy, Loc: IdentLoc);
12407
12408 auto *UD =
12409 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, NameLoc: IdentLoc, EnumType: TSI, ED: Enum);
12410
12411 if (UD)
12412 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12413
12414 return UD;
12415}
12416
12417/// Determine whether a using declaration considers the given
12418/// declarations as "equivalent", e.g., if they are redeclarations of
12419/// the same entity or are both typedefs of the same type.
12420static bool
12421IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12422 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12423 return true;
12424
12425 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(Val: D1))
12426 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(Val: D2))
12427 return Context.hasSameType(T1: TD1->getUnderlyingType(),
12428 T2: TD2->getUnderlyingType());
12429
12430 // Two using_if_exists using-declarations are equivalent if both are
12431 // unresolved.
12432 if (isa<UnresolvedUsingIfExistsDecl>(Val: D1) &&
12433 isa<UnresolvedUsingIfExistsDecl>(Val: D2))
12434 return true;
12435
12436 return false;
12437}
12438
12439
12440/// Determines whether to create a using shadow decl for a particular
12441/// decl, given the set of decls existing prior to this using lookup.
12442bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12443 const LookupResult &Previous,
12444 UsingShadowDecl *&PrevShadow) {
12445 // Diagnose finding a decl which is not from a base class of the
12446 // current class. We do this now because there are cases where this
12447 // function will silently decide not to build a shadow decl, which
12448 // will pre-empt further diagnostics.
12449 //
12450 // We don't need to do this in C++11 because we do the check once on
12451 // the qualifier.
12452 //
12453 // FIXME: diagnose the following if we care enough:
12454 // struct A { int foo; };
12455 // struct B : A { using A::foo; };
12456 // template <class T> struct C : A {};
12457 // template <class T> struct D : C<T> { using B::foo; } // <---
12458 // This is invalid (during instantiation) in C++03 because B::foo
12459 // resolves to the using decl in B, which is not a base class of D<T>.
12460 // We can't diagnose it immediately because C<T> is an unknown
12461 // specialization. The UsingShadowDecl in D<T> then points directly
12462 // to A::foo, which will look well-formed when we instantiate.
12463 // The right solution is to not collapse the shadow-decl chain.
12464 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12465 if (auto *Using = dyn_cast<UsingDecl>(Val: BUD)) {
12466 DeclContext *OrigDC = Orig->getDeclContext();
12467
12468 // Handle enums and anonymous structs.
12469 if (isa<EnumDecl>(Val: OrigDC))
12470 OrigDC = OrigDC->getParent();
12471 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(Val: OrigDC);
12472 while (OrigRec->isAnonymousStructOrUnion())
12473 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12474
12475 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(Base: OrigRec)) {
12476 if (OrigDC == CurContext) {
12477 Diag(Using->getLocation(),
12478 diag::err_using_decl_nested_name_specifier_is_current_class)
12479 << Using->getQualifierLoc().getSourceRange();
12480 Diag(Orig->getLocation(), diag::note_using_decl_target);
12481 Using->setInvalidDecl();
12482 return true;
12483 }
12484
12485 Diag(Using->getQualifierLoc().getBeginLoc(),
12486 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12487 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12488 << Using->getQualifierLoc().getSourceRange();
12489 Diag(Orig->getLocation(), diag::note_using_decl_target);
12490 Using->setInvalidDecl();
12491 return true;
12492 }
12493 }
12494
12495 if (Previous.empty()) return false;
12496
12497 NamedDecl *Target = Orig;
12498 if (isa<UsingShadowDecl>(Val: Target))
12499 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12500
12501 // If the target happens to be one of the previous declarations, we
12502 // don't have a conflict.
12503 //
12504 // FIXME: but we might be increasing its access, in which case we
12505 // should redeclare it.
12506 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12507 bool FoundEquivalentDecl = false;
12508 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12509 I != E; ++I) {
12510 NamedDecl *D = (*I)->getUnderlyingDecl();
12511 // We can have UsingDecls in our Previous results because we use the same
12512 // LookupResult for checking whether the UsingDecl itself is a valid
12513 // redeclaration.
12514 if (isa<UsingDecl>(Val: D) || isa<UsingPackDecl>(Val: D) || isa<UsingEnumDecl>(Val: D))
12515 continue;
12516
12517 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
12518 // C++ [class.mem]p19:
12519 // If T is the name of a class, then [every named member other than
12520 // a non-static data member] shall have a name different from T
12521 if (RD->isInjectedClassName() && !isa<FieldDecl>(Val: Target) &&
12522 !isa<IndirectFieldDecl>(Val: Target) &&
12523 !isa<UnresolvedUsingValueDecl>(Val: Target) &&
12524 DiagnoseClassNameShadow(
12525 DC: CurContext,
12526 Info: DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12527 return true;
12528 }
12529
12530 if (IsEquivalentForUsingDecl(Context, D1: D, D2: Target)) {
12531 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: *I))
12532 PrevShadow = Shadow;
12533 FoundEquivalentDecl = true;
12534 } else if (isEquivalentInternalLinkageDeclaration(A: D, B: Target)) {
12535 // We don't conflict with an existing using shadow decl of an equivalent
12536 // declaration, but we're not a redeclaration of it.
12537 FoundEquivalentDecl = true;
12538 }
12539
12540 if (isVisible(D))
12541 (isa<TagDecl>(Val: D) ? Tag : NonTag) = D;
12542 }
12543
12544 if (FoundEquivalentDecl)
12545 return false;
12546
12547 // Always emit a diagnostic for a mismatch between an unresolved
12548 // using_if_exists and a resolved using declaration in either direction.
12549 if (isa<UnresolvedUsingIfExistsDecl>(Val: Target) !=
12550 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(Val: NonTag))) {
12551 if (!NonTag && !Tag)
12552 return false;
12553 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12554 Diag(Target->getLocation(), diag::note_using_decl_target);
12555 Diag((NonTag ? NonTag : Tag)->getLocation(),
12556 diag::note_using_decl_conflict);
12557 BUD->setInvalidDecl();
12558 return true;
12559 }
12560
12561 if (FunctionDecl *FD = Target->getAsFunction()) {
12562 NamedDecl *OldDecl = nullptr;
12563 switch (CheckOverload(S: nullptr, New: FD, OldDecls: Previous, OldDecl,
12564 /*IsForUsingDecl*/ UseMemberUsingDeclRules: true)) {
12565 case Ovl_Overload:
12566 return false;
12567
12568 case Ovl_NonFunction:
12569 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12570 break;
12571
12572 // We found a decl with the exact signature.
12573 case Ovl_Match:
12574 // If we're in a record, we want to hide the target, so we
12575 // return true (without a diagnostic) to tell the caller not to
12576 // build a shadow decl.
12577 if (CurContext->isRecord())
12578 return true;
12579
12580 // If we're not in a record, this is an error.
12581 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12582 break;
12583 }
12584
12585 Diag(Target->getLocation(), diag::note_using_decl_target);
12586 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12587 BUD->setInvalidDecl();
12588 return true;
12589 }
12590
12591 // Target is not a function.
12592
12593 if (isa<TagDecl>(Val: Target)) {
12594 // No conflict between a tag and a non-tag.
12595 if (!Tag) return false;
12596
12597 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12598 Diag(Target->getLocation(), diag::note_using_decl_target);
12599 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12600 BUD->setInvalidDecl();
12601 return true;
12602 }
12603
12604 // No conflict between a tag and a non-tag.
12605 if (!NonTag) return false;
12606
12607 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12608 Diag(Target->getLocation(), diag::note_using_decl_target);
12609 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12610 BUD->setInvalidDecl();
12611 return true;
12612}
12613
12614/// Determine whether a direct base class is a virtual base class.
12615static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12616 if (!Derived->getNumVBases())
12617 return false;
12618 for (auto &B : Derived->bases())
12619 if (B.getType()->getAsCXXRecordDecl() == Base)
12620 return B.isVirtual();
12621 llvm_unreachable("not a direct base class");
12622}
12623
12624/// Builds a shadow declaration corresponding to a 'using' declaration.
12625UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12626 NamedDecl *Orig,
12627 UsingShadowDecl *PrevDecl) {
12628 // If we resolved to another shadow declaration, just coalesce them.
12629 NamedDecl *Target = Orig;
12630 if (isa<UsingShadowDecl>(Val: Target)) {
12631 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12632 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12633 }
12634
12635 NamedDecl *NonTemplateTarget = Target;
12636 if (auto *TargetTD = dyn_cast<TemplateDecl>(Val: Target))
12637 NonTemplateTarget = TargetTD->getTemplatedDecl();
12638
12639 UsingShadowDecl *Shadow;
12640 if (NonTemplateTarget && isa<CXXConstructorDecl>(Val: NonTemplateTarget)) {
12641 UsingDecl *Using = cast<UsingDecl>(Val: BUD);
12642 bool IsVirtualBase =
12643 isVirtualDirectBase(Derived: cast<CXXRecordDecl>(Val: CurContext),
12644 Base: Using->getQualifier()->getAsRecordDecl());
12645 Shadow = ConstructorUsingShadowDecl::Create(
12646 C&: Context, DC: CurContext, Loc: Using->getLocation(), Using, Target: Orig, IsVirtual: IsVirtualBase);
12647 } else {
12648 Shadow = UsingShadowDecl::Create(C&: Context, DC: CurContext, Loc: BUD->getLocation(),
12649 Name: Target->getDeclName(), Introducer: BUD, Target);
12650 }
12651 BUD->addShadowDecl(S: Shadow);
12652
12653 Shadow->setAccess(BUD->getAccess());
12654 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12655 Shadow->setInvalidDecl();
12656
12657 Shadow->setPreviousDecl(PrevDecl);
12658
12659 if (S)
12660 PushOnScopeChains(Shadow, S);
12661 else
12662 CurContext->addDecl(Shadow);
12663
12664
12665 return Shadow;
12666}
12667
12668/// Hides a using shadow declaration. This is required by the current
12669/// using-decl implementation when a resolvable using declaration in a
12670/// class is followed by a declaration which would hide or override
12671/// one or more of the using decl's targets; for example:
12672///
12673/// struct Base { void foo(int); };
12674/// struct Derived : Base {
12675/// using Base::foo;
12676/// void foo(int);
12677/// };
12678///
12679/// The governing language is C++03 [namespace.udecl]p12:
12680///
12681/// When a using-declaration brings names from a base class into a
12682/// derived class scope, member functions in the derived class
12683/// override and/or hide member functions with the same name and
12684/// parameter types in a base class (rather than conflicting).
12685///
12686/// There are two ways to implement this:
12687/// (1) optimistically create shadow decls when they're not hidden
12688/// by existing declarations, or
12689/// (2) don't create any shadow decls (or at least don't make them
12690/// visible) until we've fully parsed/instantiated the class.
12691/// The problem with (1) is that we might have to retroactively remove
12692/// a shadow decl, which requires several O(n) operations because the
12693/// decl structures are (very reasonably) not designed for removal.
12694/// (2) avoids this but is very fiddly and phase-dependent.
12695void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12696 if (Shadow->getDeclName().getNameKind() ==
12697 DeclarationName::CXXConversionFunctionName)
12698 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12699
12700 // Remove it from the DeclContext...
12701 Shadow->getDeclContext()->removeDecl(Shadow);
12702
12703 // ...and the scope, if applicable...
12704 if (S) {
12705 S->RemoveDecl(Shadow);
12706 IdResolver.RemoveDecl(Shadow);
12707 }
12708
12709 // ...and the using decl.
12710 Shadow->getIntroducer()->removeShadowDecl(S: Shadow);
12711
12712 // TODO: complain somehow if Shadow was used. It shouldn't
12713 // be possible for this to happen, because...?
12714}
12715
12716/// Find the base specifier for a base class with the given type.
12717static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12718 QualType DesiredBase,
12719 bool &AnyDependentBases) {
12720 // Check whether the named type is a direct base class.
12721 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12722 .getUnqualifiedType();
12723 for (auto &Base : Derived->bases()) {
12724 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12725 if (CanonicalDesiredBase == BaseType)
12726 return &Base;
12727 if (BaseType->isDependentType())
12728 AnyDependentBases = true;
12729 }
12730 return nullptr;
12731}
12732
12733namespace {
12734class UsingValidatorCCC final : public CorrectionCandidateCallback {
12735public:
12736 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12737 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12738 : HasTypenameKeyword(HasTypenameKeyword),
12739 IsInstantiation(IsInstantiation), OldNNS(NNS),
12740 RequireMemberOf(RequireMemberOf) {}
12741
12742 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12743 NamedDecl *ND = Candidate.getCorrectionDecl();
12744
12745 // Keywords are not valid here.
12746 if (!ND || isa<NamespaceDecl>(Val: ND))
12747 return false;
12748
12749 // Completely unqualified names are invalid for a 'using' declaration.
12750 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12751 return false;
12752
12753 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12754 // reject.
12755
12756 if (RequireMemberOf) {
12757 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
12758 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12759 // No-one ever wants a using-declaration to name an injected-class-name
12760 // of a base class, unless they're declaring an inheriting constructor.
12761 ASTContext &Ctx = ND->getASTContext();
12762 if (!Ctx.getLangOpts().CPlusPlus11)
12763 return false;
12764 QualType FoundType = Ctx.getRecordType(FoundRecord);
12765
12766 // Check that the injected-class-name is named as a member of its own
12767 // type; we don't want to suggest 'using Derived::Base;', since that
12768 // means something else.
12769 NestedNameSpecifier *Specifier =
12770 Candidate.WillReplaceSpecifier()
12771 ? Candidate.getCorrectionSpecifier()
12772 : OldNNS;
12773 if (!Specifier->getAsType() ||
12774 !Ctx.hasSameType(T1: QualType(Specifier->getAsType(), 0), T2: FoundType))
12775 return false;
12776
12777 // Check that this inheriting constructor declaration actually names a
12778 // direct base class of the current class.
12779 bool AnyDependentBases = false;
12780 if (!findDirectBaseWithType(Derived: RequireMemberOf,
12781 DesiredBase: Ctx.getRecordType(FoundRecord),
12782 AnyDependentBases) &&
12783 !AnyDependentBases)
12784 return false;
12785 } else {
12786 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12787 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(Base: RD))
12788 return false;
12789
12790 // FIXME: Check that the base class member is accessible?
12791 }
12792 } else {
12793 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
12794 if (FoundRecord && FoundRecord->isInjectedClassName())
12795 return false;
12796 }
12797
12798 if (isa<TypeDecl>(Val: ND))
12799 return HasTypenameKeyword || !IsInstantiation;
12800
12801 return !HasTypenameKeyword;
12802 }
12803
12804 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12805 return std::make_unique<UsingValidatorCCC>(args&: *this);
12806 }
12807
12808private:
12809 bool HasTypenameKeyword;
12810 bool IsInstantiation;
12811 NestedNameSpecifier *OldNNS;
12812 CXXRecordDecl *RequireMemberOf;
12813};
12814} // end anonymous namespace
12815
12816/// Remove decls we can't actually see from a lookup being used to declare
12817/// shadow using decls.
12818///
12819/// \param S - The scope of the potential shadow decl
12820/// \param Previous - The lookup of a potential shadow decl's name.
12821void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12822 // It is really dumb that we have to do this.
12823 LookupResult::Filter F = Previous.makeFilter();
12824 while (F.hasNext()) {
12825 NamedDecl *D = F.next();
12826 if (!isDeclInScope(D, Ctx: CurContext, S))
12827 F.erase();
12828 // If we found a local extern declaration that's not ordinarily visible,
12829 // and this declaration is being added to a non-block scope, ignore it.
12830 // We're only checking for scope conflicts here, not also for violations
12831 // of the linkage rules.
12832 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12833 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12834 F.erase();
12835 }
12836 F.done();
12837}
12838
12839/// Builds a using declaration.
12840///
12841/// \param IsInstantiation - Whether this call arises from an
12842/// instantiation of an unresolved using declaration. We treat
12843/// the lookup differently for these declarations.
12844NamedDecl *Sema::BuildUsingDeclaration(
12845 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12846 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12847 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12848 const ParsedAttributesView &AttrList, bool IsInstantiation,
12849 bool IsUsingIfExists) {
12850 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12851 SourceLocation IdentLoc = NameInfo.getLoc();
12852 assert(IdentLoc.isValid() && "Invalid TargetName location.");
12853
12854 // FIXME: We ignore attributes for now.
12855
12856 // For an inheriting constructor declaration, the name of the using
12857 // declaration is the name of a constructor in this class, not in the
12858 // base class.
12859 DeclarationNameInfo UsingName = NameInfo;
12860 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12861 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext))
12862 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12863 Ty: Context.getCanonicalType(T: Context.getRecordType(RD))));
12864
12865 // Do the redeclaration lookup in the current scope.
12866 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12867 ForVisibleRedeclaration);
12868 Previous.setHideTags(false);
12869 if (S) {
12870 LookupName(R&: Previous, S);
12871
12872 FilterUsingLookup(S, Previous);
12873 } else {
12874 assert(IsInstantiation && "no scope in non-instantiation");
12875 if (CurContext->isRecord())
12876 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
12877 else {
12878 // No redeclaration check is needed here; in non-member contexts we
12879 // diagnosed all possible conflicts with other using-declarations when
12880 // building the template:
12881 //
12882 // For a dependent non-type using declaration, the only valid case is
12883 // if we instantiate to a single enumerator. We check for conflicts
12884 // between shadow declarations we introduce, and we check in the template
12885 // definition for conflicts between a non-type using declaration and any
12886 // other declaration, which together covers all cases.
12887 //
12888 // A dependent typename using declaration will never successfully
12889 // instantiate, since it will always name a class member, so we reject
12890 // that in the template definition.
12891 }
12892 }
12893
12894 // Check for invalid redeclarations.
12895 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12896 SS, NameLoc: IdentLoc, Previous))
12897 return nullptr;
12898
12899 // 'using_if_exists' doesn't make sense on an inherited constructor.
12900 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12901 DeclarationName::CXXConstructorName) {
12902 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12903 return nullptr;
12904 }
12905
12906 DeclContext *LookupContext = computeDeclContext(SS);
12907 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12908 if (!LookupContext || EllipsisLoc.isValid()) {
12909 NamedDecl *D;
12910 // Dependent scope, or an unexpanded pack
12911 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword,
12912 SS, NameInfo, NameLoc: IdentLoc))
12913 return nullptr;
12914
12915 if (HasTypenameKeyword) {
12916 // FIXME: not all declaration name kinds are legal here
12917 D = UnresolvedUsingTypenameDecl::Create(C&: Context, DC: CurContext,
12918 UsingLoc, TypenameLoc,
12919 QualifierLoc,
12920 TargetNameLoc: IdentLoc, TargetName: NameInfo.getName(),
12921 EllipsisLoc);
12922 } else {
12923 D = UnresolvedUsingValueDecl::Create(C&: Context, DC: CurContext, UsingLoc,
12924 QualifierLoc, NameInfo, EllipsisLoc);
12925 }
12926 D->setAccess(AS);
12927 CurContext->addDecl(D);
12928 ProcessDeclAttributeList(S, D, AttrList);
12929 return D;
12930 }
12931
12932 auto Build = [&](bool Invalid) {
12933 UsingDecl *UD =
12934 UsingDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, QualifierLoc,
12935 NameInfo: UsingName, HasTypenameKeyword);
12936 UD->setAccess(AS);
12937 CurContext->addDecl(UD);
12938 ProcessDeclAttributeList(S, UD, AttrList);
12939 UD->setInvalidDecl(Invalid);
12940 return UD;
12941 };
12942 auto BuildInvalid = [&]{ return Build(true); };
12943 auto BuildValid = [&]{ return Build(false); };
12944
12945 if (RequireCompleteDeclContext(SS, DC: LookupContext))
12946 return BuildInvalid();
12947
12948 // Look up the target name.
12949 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12950
12951 // Unlike most lookups, we don't always want to hide tag
12952 // declarations: tag names are visible through the using declaration
12953 // even if hidden by ordinary names, *except* in a dependent context
12954 // where they may be used by two-phase lookup.
12955 if (!IsInstantiation)
12956 R.setHideTags(false);
12957
12958 // For the purposes of this lookup, we have a base object type
12959 // equal to that of the current context.
12960 if (CurContext->isRecord()) {
12961 R.setBaseObjectType(
12962 Context.getTypeDeclType(cast<CXXRecordDecl>(Val: CurContext)));
12963 }
12964
12965 LookupQualifiedName(R, LookupCtx: LookupContext);
12966
12967 // Validate the context, now we have a lookup
12968 if (CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, SS, NameInfo,
12969 NameLoc: IdentLoc, R: &R))
12970 return nullptr;
12971
12972 if (R.empty() && IsUsingIfExists)
12973 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Ctx&: Context, DC: CurContext, Loc: UsingLoc,
12974 Name: UsingName.getName()),
12975 AS_public);
12976
12977 // Try to correct typos if possible. If constructor name lookup finds no
12978 // results, that means the named class has no explicit constructors, and we
12979 // suppressed declaring implicit ones (probably because it's dependent or
12980 // invalid).
12981 if (R.empty() &&
12982 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12983 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12984 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12985 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12986 auto *II = NameInfo.getName().getAsIdentifierInfo();
12987 if (getLangOpts().CPlusPlus14 && II && II->isStr(Str: "gets") &&
12988 CurContext->isStdNamespace() &&
12989 isa<TranslationUnitDecl>(Val: LookupContext) &&
12990 getSourceManager().isInSystemHeader(Loc: UsingLoc))
12991 return nullptr;
12992 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12993 dyn_cast<CXXRecordDecl>(Val: CurContext));
12994 if (TypoCorrection Corrected =
12995 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
12996 Mode: CTK_ErrorRecovery)) {
12997 // We reject candidates where DroppedSpecifier == true, hence the
12998 // literal '0' below.
12999 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13000 << NameInfo.getName() << LookupContext << 0
13001 << SS.getRange());
13002
13003 // If we picked a correction with no attached Decl we can't do anything
13004 // useful with it, bail out.
13005 NamedDecl *ND = Corrected.getCorrectionDecl();
13006 if (!ND)
13007 return BuildInvalid();
13008
13009 // If we corrected to an inheriting constructor, handle it as one.
13010 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
13011 if (RD && RD->isInjectedClassName()) {
13012 // The parent of the injected class name is the class itself.
13013 RD = cast<CXXRecordDecl>(RD->getParent());
13014
13015 // Fix up the information we'll use to build the using declaration.
13016 if (Corrected.WillReplaceSpecifier()) {
13017 NestedNameSpecifierLocBuilder Builder;
13018 Builder.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
13019 R: QualifierLoc.getSourceRange());
13020 QualifierLoc = Builder.getWithLocInContext(Context);
13021 }
13022
13023 // In this case, the name we introduce is the name of a derived class
13024 // constructor.
13025 auto *CurClass = cast<CXXRecordDecl>(Val: CurContext);
13026 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13027 Ty: Context.getCanonicalType(T: Context.getRecordType(CurClass))));
13028 UsingName.setNamedTypeInfo(nullptr);
13029 for (auto *Ctor : LookupConstructors(Class: RD))
13030 R.addDecl(D: Ctor);
13031 R.resolveKind();
13032 } else {
13033 // FIXME: Pick up all the declarations if we found an overloaded
13034 // function.
13035 UsingName.setName(ND->getDeclName());
13036 R.addDecl(D: ND);
13037 }
13038 } else {
13039 Diag(IdentLoc, diag::err_no_member)
13040 << NameInfo.getName() << LookupContext << SS.getRange();
13041 return BuildInvalid();
13042 }
13043 }
13044
13045 if (R.isAmbiguous())
13046 return BuildInvalid();
13047
13048 if (HasTypenameKeyword) {
13049 // If we asked for a typename and got a non-type decl, error out.
13050 if (!R.getAsSingle<TypeDecl>() &&
13051 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13052 Diag(IdentLoc, diag::err_using_typename_non_type);
13053 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13054 Diag((*I)->getUnderlyingDecl()->getLocation(),
13055 diag::note_using_decl_target);
13056 return BuildInvalid();
13057 }
13058 } else {
13059 // If we asked for a non-typename and we got a type, error out,
13060 // but only if this is an instantiation of an unresolved using
13061 // decl. Otherwise just silently find the type name.
13062 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13063 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13064 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13065 return BuildInvalid();
13066 }
13067 }
13068
13069 // C++14 [namespace.udecl]p6:
13070 // A using-declaration shall not name a namespace.
13071 if (R.getAsSingle<NamespaceDecl>()) {
13072 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13073 << SS.getRange();
13074 return BuildInvalid();
13075 }
13076
13077 UsingDecl *UD = BuildValid();
13078
13079 // Some additional rules apply to inheriting constructors.
13080 if (UsingName.getName().getNameKind() ==
13081 DeclarationName::CXXConstructorName) {
13082 // Suppress access diagnostics; the access check is instead performed at the
13083 // point of use for an inheriting constructor.
13084 R.suppressDiagnostics();
13085 if (CheckInheritingConstructorUsingDecl(UD))
13086 return UD;
13087 }
13088
13089 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
13090 UsingShadowDecl *PrevDecl = nullptr;
13091 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
13092 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
13093 }
13094
13095 return UD;
13096}
13097
13098NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13099 SourceLocation UsingLoc,
13100 SourceLocation EnumLoc,
13101 SourceLocation NameLoc,
13102 TypeSourceInfo *EnumType,
13103 EnumDecl *ED) {
13104 bool Invalid = false;
13105
13106 if (CurContext->getRedeclContext()->isRecord()) {
13107 /// In class scope, check if this is a duplicate, for better a diagnostic.
13108 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13109 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13110 ForVisibleRedeclaration);
13111
13112 LookupName(R&: Previous, S);
13113
13114 for (NamedDecl *D : Previous)
13115 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13116 if (UED->getEnumDecl() == ED) {
13117 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13118 << SourceRange(EnumLoc, NameLoc);
13119 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13120 Invalid = true;
13121 break;
13122 }
13123 }
13124
13125 if (RequireCompleteEnumDecl(D: ED, L: NameLoc))
13126 Invalid = true;
13127
13128 UsingEnumDecl *UD = UsingEnumDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc,
13129 EnumL: EnumLoc, NameL: NameLoc, EnumType);
13130 UD->setAccess(AS);
13131 CurContext->addDecl(UD);
13132
13133 if (Invalid) {
13134 UD->setInvalidDecl();
13135 return UD;
13136 }
13137
13138 // Create the shadow decls for each enumerator
13139 for (EnumConstantDecl *EC : ED->enumerators()) {
13140 UsingShadowDecl *PrevDecl = nullptr;
13141 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13142 LookupResult Previous(*this, DNI, LookupOrdinaryName,
13143 ForVisibleRedeclaration);
13144 LookupName(R&: Previous, S);
13145 FilterUsingLookup(S, Previous);
13146
13147 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13148 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13149 }
13150
13151 return UD;
13152}
13153
13154NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13155 ArrayRef<NamedDecl *> Expansions) {
13156 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13157 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13158 isa<UsingPackDecl>(InstantiatedFrom));
13159
13160 auto *UPD =
13161 UsingPackDecl::Create(C&: Context, DC: CurContext, InstantiatedFrom, UsingDecls: Expansions);
13162 UPD->setAccess(InstantiatedFrom->getAccess());
13163 CurContext->addDecl(UPD);
13164 return UPD;
13165}
13166
13167/// Additional checks for a using declaration referring to a constructor name.
13168bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13169 assert(!UD->hasTypename() && "expecting a constructor name");
13170
13171 const Type *SourceType = UD->getQualifier()->getAsType();
13172 assert(SourceType &&
13173 "Using decl naming constructor doesn't have type in scope spec.");
13174 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(Val: CurContext);
13175
13176 // Check whether the named type is a direct base class.
13177 bool AnyDependentBases = false;
13178 auto *Base = findDirectBaseWithType(Derived: TargetClass, DesiredBase: QualType(SourceType, 0),
13179 AnyDependentBases);
13180 if (!Base && !AnyDependentBases) {
13181 Diag(UD->getUsingLoc(),
13182 diag::err_using_decl_constructor_not_in_direct_base)
13183 << UD->getNameInfo().getSourceRange()
13184 << QualType(SourceType, 0) << TargetClass;
13185 UD->setInvalidDecl();
13186 return true;
13187 }
13188
13189 if (Base)
13190 Base->setInheritConstructors();
13191
13192 return false;
13193}
13194
13195/// Checks that the given using declaration is not an invalid
13196/// redeclaration. Note that this is checking only for the using decl
13197/// itself, not for any ill-formedness among the UsingShadowDecls.
13198bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13199 bool HasTypenameKeyword,
13200 const CXXScopeSpec &SS,
13201 SourceLocation NameLoc,
13202 const LookupResult &Prev) {
13203 NestedNameSpecifier *Qual = SS.getScopeRep();
13204
13205 // C++03 [namespace.udecl]p8:
13206 // C++0x [namespace.udecl]p10:
13207 // A using-declaration is a declaration and can therefore be used
13208 // repeatedly where (and only where) multiple declarations are
13209 // allowed.
13210 //
13211 // That's in non-member contexts.
13212 if (!CurContext->getRedeclContext()->isRecord()) {
13213 // A dependent qualifier outside a class can only ever resolve to an
13214 // enumeration type. Therefore it conflicts with any other non-type
13215 // declaration in the same scope.
13216 // FIXME: How should we check for dependent type-type conflicts at block
13217 // scope?
13218 if (Qual->isDependent() && !HasTypenameKeyword) {
13219 for (auto *D : Prev) {
13220 if (!isa<TypeDecl>(Val: D) && !isa<UsingDecl>(Val: D) && !isa<UsingPackDecl>(Val: D)) {
13221 bool OldCouldBeEnumerator =
13222 isa<UnresolvedUsingValueDecl>(Val: D) || isa<EnumConstantDecl>(Val: D);
13223 Diag(NameLoc,
13224 OldCouldBeEnumerator ? diag::err_redefinition
13225 : diag::err_redefinition_different_kind)
13226 << Prev.getLookupName();
13227 Diag(D->getLocation(), diag::note_previous_definition);
13228 return true;
13229 }
13230 }
13231 }
13232 return false;
13233 }
13234
13235 const NestedNameSpecifier *CNNS =
13236 Context.getCanonicalNestedNameSpecifier(NNS: Qual);
13237 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13238 NamedDecl *D = *I;
13239
13240 bool DTypename;
13241 NestedNameSpecifier *DQual;
13242 if (UsingDecl *UD = dyn_cast<UsingDecl>(Val: D)) {
13243 DTypename = UD->hasTypename();
13244 DQual = UD->getQualifier();
13245 } else if (UnresolvedUsingValueDecl *UD
13246 = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) {
13247 DTypename = false;
13248 DQual = UD->getQualifier();
13249 } else if (UnresolvedUsingTypenameDecl *UD
13250 = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) {
13251 DTypename = true;
13252 DQual = UD->getQualifier();
13253 } else continue;
13254
13255 // using decls differ if one says 'typename' and the other doesn't.
13256 // FIXME: non-dependent using decls?
13257 if (HasTypenameKeyword != DTypename) continue;
13258
13259 // using decls differ if they name different scopes (but note that
13260 // template instantiation can cause this check to trigger when it
13261 // didn't before instantiation).
13262 if (CNNS != Context.getCanonicalNestedNameSpecifier(NNS: DQual))
13263 continue;
13264
13265 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13266 Diag(D->getLocation(), diag::note_using_decl) << 1;
13267 return true;
13268 }
13269
13270 return false;
13271}
13272
13273/// Checks that the given nested-name qualifier used in a using decl
13274/// in the current context is appropriately related to the current
13275/// scope. If an error is found, diagnoses it and returns true.
13276/// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
13277/// result of that lookup. UD is likewise nullptr, except when we have an
13278/// already-populated UsingDecl whose shadow decls contain the same information
13279/// (i.e. we're instantiating a UsingDecl with non-dependent scope).
13280bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13281 const CXXScopeSpec &SS,
13282 const DeclarationNameInfo &NameInfo,
13283 SourceLocation NameLoc,
13284 const LookupResult *R, const UsingDecl *UD) {
13285 DeclContext *NamedContext = computeDeclContext(SS);
13286 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13287 "resolvable context must have exactly one set of decls");
13288
13289 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13290 // relationship.
13291 bool Cxx20Enumerator = false;
13292 if (NamedContext) {
13293 EnumConstantDecl *EC = nullptr;
13294 if (R)
13295 EC = R->getAsSingle<EnumConstantDecl>();
13296 else if (UD && UD->shadow_size() == 1)
13297 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13298 if (EC)
13299 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13300
13301 if (auto *ED = dyn_cast<EnumDecl>(Val: NamedContext)) {
13302 // C++14 [namespace.udecl]p7:
13303 // A using-declaration shall not name a scoped enumerator.
13304 // C++20 p1099 permits enumerators.
13305 if (EC && R && ED->isScoped())
13306 Diag(SS.getBeginLoc(),
13307 getLangOpts().CPlusPlus20
13308 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13309 : diag::ext_using_decl_scoped_enumerator)
13310 << SS.getRange();
13311
13312 // We want to consider the scope of the enumerator
13313 NamedContext = ED->getDeclContext();
13314 }
13315 }
13316
13317 if (!CurContext->isRecord()) {
13318 // C++03 [namespace.udecl]p3:
13319 // C++0x [namespace.udecl]p8:
13320 // A using-declaration for a class member shall be a member-declaration.
13321 // C++20 [namespace.udecl]p7
13322 // ... other than an enumerator ...
13323
13324 // If we weren't able to compute a valid scope, it might validly be a
13325 // dependent class or enumeration scope. If we have a 'typename' keyword,
13326 // the scope must resolve to a class type.
13327 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13328 : !HasTypename)
13329 return false; // OK
13330
13331 Diag(NameLoc,
13332 Cxx20Enumerator
13333 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13334 : diag::err_using_decl_can_not_refer_to_class_member)
13335 << SS.getRange();
13336
13337 if (Cxx20Enumerator)
13338 return false; // OK
13339
13340 auto *RD = NamedContext
13341 ? cast<CXXRecordDecl>(Val: NamedContext->getRedeclContext())
13342 : nullptr;
13343 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13344 // See if there's a helpful fixit
13345
13346 if (!R) {
13347 // We will have already diagnosed the problem on the template
13348 // definition, Maybe we should do so again?
13349 } else if (R->getAsSingle<TypeDecl>()) {
13350 if (getLangOpts().CPlusPlus11) {
13351 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13352 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13353 << 0 // alias declaration
13354 << FixItHint::CreateInsertion(SS.getBeginLoc(),
13355 NameInfo.getName().getAsString() +
13356 " = ");
13357 } else {
13358 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13359 SourceLocation InsertLoc = getLocForEndOfToken(Loc: NameInfo.getEndLoc());
13360 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13361 << 1 // typedef declaration
13362 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13363 << FixItHint::CreateInsertion(
13364 InsertLoc, " " + NameInfo.getName().getAsString());
13365 }
13366 } else if (R->getAsSingle<VarDecl>()) {
13367 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13368 // repeating the type of the static data member here.
13369 FixItHint FixIt;
13370 if (getLangOpts().CPlusPlus11) {
13371 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13372 FixIt = FixItHint::CreateReplacement(
13373 RemoveRange: UsingLoc, Code: "auto &" + NameInfo.getName().getAsString() + " = ");
13374 }
13375
13376 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13377 << 2 // reference declaration
13378 << FixIt;
13379 } else if (R->getAsSingle<EnumConstantDecl>()) {
13380 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13381 // repeating the type of the enumeration here, and we can't do so if
13382 // the type is anonymous.
13383 FixItHint FixIt;
13384 if (getLangOpts().CPlusPlus11) {
13385 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13386 FixIt = FixItHint::CreateReplacement(
13387 RemoveRange: UsingLoc,
13388 Code: "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13389 }
13390
13391 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13392 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13393 << FixIt;
13394 }
13395 }
13396
13397 return true; // Fail
13398 }
13399
13400 // If the named context is dependent, we can't decide much.
13401 if (!NamedContext) {
13402 // FIXME: in C++0x, we can diagnose if we can prove that the
13403 // nested-name-specifier does not refer to a base class, which is
13404 // still possible in some cases.
13405
13406 // Otherwise we have to conservatively report that things might be
13407 // okay.
13408 return false;
13409 }
13410
13411 // The current scope is a record.
13412 if (!NamedContext->isRecord()) {
13413 // Ideally this would point at the last name in the specifier,
13414 // but we don't have that level of source info.
13415 Diag(SS.getBeginLoc(),
13416 Cxx20Enumerator
13417 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13418 : diag::err_using_decl_nested_name_specifier_is_not_class)
13419 << SS.getScopeRep() << SS.getRange();
13420
13421 if (Cxx20Enumerator)
13422 return false; // OK
13423
13424 return true;
13425 }
13426
13427 if (!NamedContext->isDependentContext() &&
13428 RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec&>(SS), DC: NamedContext))
13429 return true;
13430
13431 if (getLangOpts().CPlusPlus11) {
13432 // C++11 [namespace.udecl]p3:
13433 // In a using-declaration used as a member-declaration, the
13434 // nested-name-specifier shall name a base class of the class
13435 // being defined.
13436
13437 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(
13438 Base: cast<CXXRecordDecl>(Val: NamedContext))) {
13439
13440 if (Cxx20Enumerator) {
13441 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13442 << SS.getRange();
13443 return false;
13444 }
13445
13446 if (CurContext == NamedContext) {
13447 Diag(SS.getBeginLoc(),
13448 diag::err_using_decl_nested_name_specifier_is_current_class)
13449 << SS.getRange();
13450 return !getLangOpts().CPlusPlus20;
13451 }
13452
13453 if (!cast<CXXRecordDecl>(Val: NamedContext)->isInvalidDecl()) {
13454 Diag(SS.getBeginLoc(),
13455 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13456 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13457 << SS.getRange();
13458 }
13459 return true;
13460 }
13461
13462 return false;
13463 }
13464
13465 // C++03 [namespace.udecl]p4:
13466 // A using-declaration used as a member-declaration shall refer
13467 // to a member of a base class of the class being defined [etc.].
13468
13469 // Salient point: SS doesn't have to name a base class as long as
13470 // lookup only finds members from base classes. Therefore we can
13471 // diagnose here only if we can prove that can't happen,
13472 // i.e. if the class hierarchies provably don't intersect.
13473
13474 // TODO: it would be nice if "definitely valid" results were cached
13475 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13476 // need to be repeated.
13477
13478 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
13479 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13480 Bases.insert(Ptr: Base);
13481 return true;
13482 };
13483
13484 // Collect all bases. Return false if we find a dependent base.
13485 if (!cast<CXXRecordDecl>(Val: CurContext)->forallBases(BaseMatches: Collect))
13486 return false;
13487
13488 // Returns true if the base is dependent or is one of the accumulated base
13489 // classes.
13490 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13491 return !Bases.count(Ptr: Base);
13492 };
13493
13494 // Return false if the class has a dependent base or if it or one
13495 // of its bases is present in the base set of the current context.
13496 if (Bases.count(Ptr: cast<CXXRecordDecl>(Val: NamedContext)) ||
13497 !cast<CXXRecordDecl>(Val: NamedContext)->forallBases(BaseMatches: IsNotBase))
13498 return false;
13499
13500 Diag(SS.getRange().getBegin(),
13501 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13502 << SS.getScopeRep()
13503 << cast<CXXRecordDecl>(CurContext)
13504 << SS.getRange();
13505
13506 return true;
13507}
13508
13509Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13510 MultiTemplateParamsArg TemplateParamLists,
13511 SourceLocation UsingLoc, UnqualifiedId &Name,
13512 const ParsedAttributesView &AttrList,
13513 TypeResult Type, Decl *DeclFromDeclSpec) {
13514 // Skip up to the relevant declaration scope.
13515 while (S->isTemplateParamScope())
13516 S = S->getParent();
13517 assert((S->getFlags() & Scope::DeclScope) &&
13518 "got alias-declaration outside of declaration scope");
13519
13520 if (Type.isInvalid())
13521 return nullptr;
13522
13523 bool Invalid = false;
13524 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13525 TypeSourceInfo *TInfo = nullptr;
13526 GetTypeFromParser(Ty: Type.get(), TInfo: &TInfo);
13527
13528 if (DiagnoseClassNameShadow(DC: CurContext, Info: NameInfo))
13529 return nullptr;
13530
13531 if (DiagnoseUnexpandedParameterPack(Loc: Name.StartLocation, T: TInfo,
13532 UPPC: UPPC_DeclarationType)) {
13533 Invalid = true;
13534 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
13535 Loc: TInfo->getTypeLoc().getBeginLoc());
13536 }
13537
13538 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13539 TemplateParamLists.size()
13540 ? forRedeclarationInCurContext()
13541 : ForVisibleRedeclaration);
13542 LookupName(R&: Previous, S);
13543
13544 // Warn about shadowing the name of a template parameter.
13545 if (Previous.isSingleResult() &&
13546 Previous.getFoundDecl()->isTemplateParameter()) {
13547 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13548 Previous.clear();
13549 }
13550
13551 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13552 "name in alias declaration must be an identifier");
13553 TypeAliasDecl *NewTD = TypeAliasDecl::Create(C&: Context, DC: CurContext, StartLoc: UsingLoc,
13554 IdLoc: Name.StartLocation,
13555 Id: Name.Identifier, TInfo);
13556
13557 NewTD->setAccess(AS);
13558
13559 if (Invalid)
13560 NewTD->setInvalidDecl();
13561
13562 ProcessDeclAttributeList(S, NewTD, AttrList);
13563 AddPragmaAttributes(S, NewTD);
13564
13565 CheckTypedefForVariablyModifiedType(S, NewTD);
13566 Invalid |= NewTD->isInvalidDecl();
13567
13568 bool Redeclaration = false;
13569
13570 NamedDecl *NewND;
13571 if (TemplateParamLists.size()) {
13572 TypeAliasTemplateDecl *OldDecl = nullptr;
13573 TemplateParameterList *OldTemplateParams = nullptr;
13574
13575 if (TemplateParamLists.size() != 1) {
13576 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13577 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13578 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13579 }
13580 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13581
13582 // Check that we can declare a template here.
13583 if (CheckTemplateDeclScope(S, TemplateParams))
13584 return nullptr;
13585
13586 // Only consider previous declarations in the same scope.
13587 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13588 /*ExplicitInstantiationOrSpecialization*/AllowInlineNamespace: false);
13589 if (!Previous.empty()) {
13590 Redeclaration = true;
13591
13592 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13593 if (!OldDecl && !Invalid) {
13594 Diag(UsingLoc, diag::err_redefinition_different_kind)
13595 << Name.Identifier;
13596
13597 NamedDecl *OldD = Previous.getRepresentativeDecl();
13598 if (OldD->getLocation().isValid())
13599 Diag(OldD->getLocation(), diag::note_previous_definition);
13600
13601 Invalid = true;
13602 }
13603
13604 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13605 if (TemplateParameterListsAreEqual(TemplateParams,
13606 OldDecl->getTemplateParameters(),
13607 /*Complain=*/true,
13608 TPL_TemplateMatch))
13609 OldTemplateParams =
13610 OldDecl->getMostRecentDecl()->getTemplateParameters();
13611 else
13612 Invalid = true;
13613
13614 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13615 if (!Invalid &&
13616 !Context.hasSameType(OldTD->getUnderlyingType(),
13617 NewTD->getUnderlyingType())) {
13618 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13619 // but we can't reasonably accept it.
13620 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13621 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13622 if (OldTD->getLocation().isValid())
13623 Diag(OldTD->getLocation(), diag::note_previous_definition);
13624 Invalid = true;
13625 }
13626 }
13627 }
13628
13629 // Merge any previous default template arguments into our parameters,
13630 // and check the parameter list.
13631 if (CheckTemplateParameterList(NewParams: TemplateParams, OldParams: OldTemplateParams,
13632 TPC: TPC_TypeAliasTemplate))
13633 return nullptr;
13634
13635 TypeAliasTemplateDecl *NewDecl =
13636 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13637 Name.Identifier, TemplateParams,
13638 NewTD);
13639 NewTD->setDescribedAliasTemplate(NewDecl);
13640
13641 NewDecl->setAccess(AS);
13642
13643 if (Invalid)
13644 NewDecl->setInvalidDecl();
13645 else if (OldDecl) {
13646 NewDecl->setPreviousDecl(OldDecl);
13647 CheckRedeclarationInModule(NewDecl, OldDecl);
13648 }
13649
13650 NewND = NewDecl;
13651 } else {
13652 if (auto *TD = dyn_cast_or_null<TagDecl>(Val: DeclFromDeclSpec)) {
13653 setTagNameForLinkagePurposes(TD, NewTD);
13654 handleTagNumbering(Tag: TD, TagScope: S);
13655 }
13656 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13657 NewND = NewTD;
13658 }
13659
13660 PushOnScopeChains(D: NewND, S);
13661 ActOnDocumentableDecl(NewND);
13662 return NewND;
13663}
13664
13665Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13666 SourceLocation AliasLoc,
13667 IdentifierInfo *Alias, CXXScopeSpec &SS,
13668 SourceLocation IdentLoc,
13669 IdentifierInfo *Ident) {
13670
13671 // Lookup the namespace name.
13672 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13673 LookupParsedName(R, S, SS: &SS);
13674
13675 if (R.isAmbiguous())
13676 return nullptr;
13677
13678 if (R.empty()) {
13679 if (!TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident)) {
13680 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13681 return nullptr;
13682 }
13683 }
13684 assert(!R.isAmbiguous() && !R.empty());
13685 NamedDecl *ND = R.getRepresentativeDecl();
13686
13687 // Check if we have a previous declaration with the same name.
13688 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13689 ForVisibleRedeclaration);
13690 LookupName(R&: PrevR, S);
13691
13692 // Check we're not shadowing a template parameter.
13693 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13694 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13695 PrevR.clear();
13696 }
13697
13698 // Filter out any other lookup result from an enclosing scope.
13699 FilterLookupForScope(R&: PrevR, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13700 /*AllowInlineNamespace*/false);
13701
13702 // Find the previous declaration and check that we can redeclare it.
13703 NamespaceAliasDecl *Prev = nullptr;
13704 if (PrevR.isSingleResult()) {
13705 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13706 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Val: PrevDecl)) {
13707 // We already have an alias with the same name that points to the same
13708 // namespace; check that it matches.
13709 if (AD->getNamespace()->Equals(getNamespaceDecl(D: ND))) {
13710 Prev = AD;
13711 } else if (isVisible(D: PrevDecl)) {
13712 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13713 << Alias;
13714 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13715 << AD->getNamespace();
13716 return nullptr;
13717 }
13718 } else if (isVisible(D: PrevDecl)) {
13719 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13720 ? diag::err_redefinition
13721 : diag::err_redefinition_different_kind;
13722 Diag(Loc: AliasLoc, DiagID) << Alias;
13723 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13724 return nullptr;
13725 }
13726 }
13727
13728 // The use of a nested name specifier may trigger deprecation warnings.
13729 DiagnoseUseOfDecl(D: ND, Locs: IdentLoc);
13730
13731 NamespaceAliasDecl *AliasDecl =
13732 NamespaceAliasDecl::Create(C&: Context, DC: CurContext, NamespaceLoc, AliasLoc,
13733 Alias, QualifierLoc: SS.getWithLocInContext(Context),
13734 IdentLoc, Namespace: ND);
13735 if (Prev)
13736 AliasDecl->setPreviousDecl(Prev);
13737
13738 PushOnScopeChains(AliasDecl, S);
13739 return AliasDecl;
13740}
13741
13742namespace {
13743struct SpecialMemberExceptionSpecInfo
13744 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13745 SourceLocation Loc;
13746 Sema::ImplicitExceptionSpecification ExceptSpec;
13747
13748 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13749 Sema::CXXSpecialMember CSM,
13750 Sema::InheritedConstructorInfo *ICI,
13751 SourceLocation Loc)
13752 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13753
13754 bool visitBase(CXXBaseSpecifier *Base);
13755 bool visitField(FieldDecl *FD);
13756
13757 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13758 unsigned Quals);
13759
13760 void visitSubobjectCall(Subobject Subobj,
13761 Sema::SpecialMemberOverloadResult SMOR);
13762};
13763}
13764
13765bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13766 auto *RT = Base->getType()->getAs<RecordType>();
13767 if (!RT)
13768 return false;
13769
13770 auto *BaseClass = cast<CXXRecordDecl>(Val: RT->getDecl());
13771 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
13772 if (auto *BaseCtor = SMOR.getMethod()) {
13773 visitSubobjectCall(Subobj: Base, SMOR: BaseCtor);
13774 return false;
13775 }
13776
13777 visitClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
13778 return false;
13779}
13780
13781bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13782 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13783 Expr *E = FD->getInClassInitializer();
13784 if (!E)
13785 // FIXME: It's a little wasteful to build and throw away a
13786 // CXXDefaultInitExpr here.
13787 // FIXME: We should have a single context note pointing at Loc, and
13788 // this location should be MD->getLocation() instead, since that's
13789 // the location where we actually use the default init expression.
13790 E = S.BuildCXXDefaultInitExpr(Loc, Field: FD).get();
13791 if (E)
13792 ExceptSpec.CalledExpr(E);
13793 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13794 ->getAs<RecordType>()) {
13795 visitClassSubobject(Class: cast<CXXRecordDecl>(RT->getDecl()), Subobj: FD,
13796 Quals: FD->getType().getCVRQualifiers());
13797 }
13798 return false;
13799}
13800
13801void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13802 Subobject Subobj,
13803 unsigned Quals) {
13804 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13805 bool IsMutable = Field && Field->isMutable();
13806 visitSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable));
13807}
13808
13809void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13810 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13811 // Note, if lookup fails, it doesn't matter what exception specification we
13812 // choose because the special member will be deleted.
13813 if (CXXMethodDecl *MD = SMOR.getMethod())
13814 ExceptSpec.CalledDecl(CallLoc: getSubobjectLoc(Subobj), Method: MD);
13815}
13816
13817bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13818 llvm::APSInt Result;
13819 ExprResult Converted = CheckConvertedConstantExpression(
13820 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13821 ExplicitSpec.setExpr(Converted.get());
13822 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13823 ExplicitSpec.setKind(Result.getBoolValue()
13824 ? ExplicitSpecKind::ResolvedTrue
13825 : ExplicitSpecKind::ResolvedFalse);
13826 return true;
13827 }
13828 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13829 return false;
13830}
13831
13832ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13833 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13834 if (!ExplicitExpr->isTypeDependent())
13835 tryResolveExplicitSpecifier(ExplicitSpec&: ES);
13836 return ES;
13837}
13838
13839static Sema::ImplicitExceptionSpecification
13840ComputeDefaultedSpecialMemberExceptionSpec(
13841 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13842 Sema::InheritedConstructorInfo *ICI) {
13843 ComputingExceptionSpec CES(S, MD, Loc);
13844
13845 CXXRecordDecl *ClassDecl = MD->getParent();
13846
13847 // C++ [except.spec]p14:
13848 // An implicitly declared special member function (Clause 12) shall have an
13849 // exception-specification. [...]
13850 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13851 if (ClassDecl->isInvalidDecl())
13852 return Info.ExceptSpec;
13853
13854 // FIXME: If this diagnostic fires, we're probably missing a check for
13855 // attempting to resolve an exception specification before it's known
13856 // at a higher level.
13857 if (S.RequireCompleteType(MD->getLocation(),
13858 S.Context.getRecordType(ClassDecl),
13859 diag::err_exception_spec_incomplete_type))
13860 return Info.ExceptSpec;
13861
13862 // C++1z [except.spec]p7:
13863 // [Look for exceptions thrown by] a constructor selected [...] to
13864 // initialize a potentially constructed subobject,
13865 // C++1z [except.spec]p8:
13866 // The exception specification for an implicitly-declared destructor, or a
13867 // destructor without a noexcept-specifier, is potentially-throwing if and
13868 // only if any of the destructors for any of its potentially constructed
13869 // subojects is potentially throwing.
13870 // FIXME: We respect the first rule but ignore the "potentially constructed"
13871 // in the second rule to resolve a core issue (no number yet) that would have
13872 // us reject:
13873 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13874 // struct B : A {};
13875 // struct C : B { void f(); };
13876 // ... due to giving B::~B() a non-throwing exception specification.
13877 Info.visit(Bases: Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13878 : Info.VisitAllBases);
13879
13880 return Info.ExceptSpec;
13881}
13882
13883namespace {
13884/// RAII object to register a special member as being currently declared.
13885struct DeclaringSpecialMember {
13886 Sema &S;
13887 Sema::SpecialMemberDecl D;
13888 Sema::ContextRAII SavedContext;
13889 bool WasAlreadyBeingDeclared;
13890
13891 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13892 : S(S), D(RD, CSM), SavedContext(S, RD) {
13893 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(Ptr: D).second;
13894 if (WasAlreadyBeingDeclared)
13895 // This almost never happens, but if it does, ensure that our cache
13896 // doesn't contain a stale result.
13897 S.SpecialMemberCache.clear();
13898 else {
13899 // Register a note to be produced if we encounter an error while
13900 // declaring the special member.
13901 Sema::CodeSynthesisContext Ctx;
13902 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13903 // FIXME: We don't have a location to use here. Using the class's
13904 // location maintains the fiction that we declare all special members
13905 // with the class, but (1) it's not clear that lying about that helps our
13906 // users understand what's going on, and (2) there may be outer contexts
13907 // on the stack (some of which are relevant) and printing them exposes
13908 // our lies.
13909 Ctx.PointOfInstantiation = RD->getLocation();
13910 Ctx.Entity = RD;
13911 Ctx.SpecialMember = CSM;
13912 S.pushCodeSynthesisContext(Ctx);
13913 }
13914 }
13915 ~DeclaringSpecialMember() {
13916 if (!WasAlreadyBeingDeclared) {
13917 S.SpecialMembersBeingDeclared.erase(Ptr: D);
13918 S.popCodeSynthesisContext();
13919 }
13920 }
13921
13922 /// Are we already trying to declare this special member?
13923 bool isAlreadyBeingDeclared() const {
13924 return WasAlreadyBeingDeclared;
13925 }
13926};
13927}
13928
13929void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13930 // Look up any existing declarations, but don't trigger declaration of all
13931 // implicit special members with this name.
13932 DeclarationName Name = FD->getDeclName();
13933 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13934 ForExternalRedeclaration);
13935 for (auto *D : FD->getParent()->lookup(Name))
13936 if (auto *Acceptable = R.getAcceptableDecl(D))
13937 R.addDecl(Acceptable);
13938 R.resolveKind();
13939 R.suppressDiagnostics();
13940
13941 CheckFunctionDeclaration(S, NewFD: FD, Previous&: R, /*IsMemberSpecialization*/ false,
13942 DeclIsDefn: FD->isThisDeclarationADefinition());
13943}
13944
13945void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13946 QualType ResultTy,
13947 ArrayRef<QualType> Args) {
13948 // Build an exception specification pointing back at this constructor.
13949 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(S&: *this, MD: SpecialMem);
13950
13951 LangAS AS = getDefaultCXXMethodAddrSpace();
13952 if (AS != LangAS::Default) {
13953 EPI.TypeQuals.addAddressSpace(space: AS);
13954 }
13955
13956 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13957 SpecialMem->setType(QT);
13958
13959 // During template instantiation of implicit special member functions we need
13960 // a reliable TypeSourceInfo for the function prototype in order to allow
13961 // functions to be substituted.
13962 if (inTemplateInstantiation() &&
13963 cast<CXXRecordDecl>(Val: SpecialMem->getParent())->isLambda()) {
13964 TypeSourceInfo *TSI =
13965 Context.getTrivialTypeSourceInfo(T: SpecialMem->getType());
13966 SpecialMem->setTypeSourceInfo(TSI);
13967 }
13968}
13969
13970CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13971 CXXRecordDecl *ClassDecl) {
13972 // C++ [class.ctor]p5:
13973 // A default constructor for a class X is a constructor of class X
13974 // that can be called without an argument. If there is no
13975 // user-declared constructor for class X, a default constructor is
13976 // implicitly declared. An implicitly-declared default constructor
13977 // is an inline public member of its class.
13978 assert(ClassDecl->needsImplicitDefaultConstructor() &&
13979 "Should not build implicit default constructor!");
13980
13981 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13982 if (DSM.isAlreadyBeingDeclared())
13983 return nullptr;
13984
13985 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl,
13986 CSM: CXXDefaultConstructor,
13987 ConstArg: false);
13988
13989 // Create the actual constructor declaration.
13990 CanQualType ClassType
13991 = Context.getCanonicalType(T: Context.getTypeDeclType(ClassDecl));
13992 SourceLocation ClassLoc = ClassDecl->getLocation();
13993 DeclarationName Name
13994 = Context.DeclarationNames.getCXXConstructorName(Ty: ClassType);
13995 DeclarationNameInfo NameInfo(Name, ClassLoc);
13996 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13997 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, /*Type*/ T: QualType(),
13998 /*TInfo=*/nullptr, ES: ExplicitSpecifier(),
13999 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14000 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14001 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14002 : ConstexprSpecKind::Unspecified);
14003 DefaultCon->setAccess(AS_public);
14004 DefaultCon->setDefaulted();
14005
14006 setupImplicitSpecialMemberType(SpecialMem: DefaultCon, ResultTy: Context.VoidTy, Args: std::nullopt);
14007
14008 if (getLangOpts().CUDA)
14009 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
14010 DefaultCon,
14011 /* ConstRHS */ false,
14012 /* Diagnose */ false);
14013
14014 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14015 // constructors is easy to compute.
14016 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14017
14018 // Note that we have declared this constructor.
14019 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14020
14021 Scope *S = getScopeForContext(ClassDecl);
14022 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
14023
14024 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
14025 SetDeclDeleted(DefaultCon, ClassLoc);
14026
14027 if (S)
14028 PushOnScopeChains(DefaultCon, S, false);
14029 ClassDecl->addDecl(DefaultCon);
14030
14031 return DefaultCon;
14032}
14033
14034void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14035 CXXConstructorDecl *Constructor) {
14036 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14037 !Constructor->doesThisDeclarationHaveABody() &&
14038 !Constructor->isDeleted()) &&
14039 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14040 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14041 return;
14042
14043 CXXRecordDecl *ClassDecl = Constructor->getParent();
14044 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14045 if (ClassDecl->isInvalidDecl()) {
14046 return;
14047 }
14048
14049 SynthesizedFunctionScope Scope(*this, Constructor);
14050
14051 // The exception specification is needed because we are defining the
14052 // function.
14053 ResolveExceptionSpec(Loc: CurrentLocation,
14054 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14055 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14056
14057 // Add a context note for diagnostics produced after this point.
14058 Scope.addContextNote(UseLoc: CurrentLocation);
14059
14060 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14061 Constructor->setInvalidDecl();
14062 return;
14063 }
14064
14065 SourceLocation Loc = Constructor->getEndLoc().isValid()
14066 ? Constructor->getEndLoc()
14067 : Constructor->getLocation();
14068 Constructor->setBody(new (Context) CompoundStmt(Loc));
14069 Constructor->markUsed(Context);
14070
14071 if (ASTMutationListener *L = getASTMutationListener()) {
14072 L->CompletedImplicitDefinition(Constructor);
14073 }
14074
14075 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14076}
14077
14078void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14079 // Perform any delayed checks on exception specifications.
14080 CheckDelayedMemberExceptionSpecs();
14081}
14082
14083/// Find or create the fake constructor we synthesize to model constructing an
14084/// object of a derived class via a constructor of a base class.
14085CXXConstructorDecl *
14086Sema::findInheritingConstructor(SourceLocation Loc,
14087 CXXConstructorDecl *BaseCtor,
14088 ConstructorUsingShadowDecl *Shadow) {
14089 CXXRecordDecl *Derived = Shadow->getParent();
14090 SourceLocation UsingLoc = Shadow->getLocation();
14091
14092 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14093 // For now we use the name of the base class constructor as a member of the
14094 // derived class to indicate a (fake) inherited constructor name.
14095 DeclarationName Name = BaseCtor->getDeclName();
14096
14097 // Check to see if we already have a fake constructor for this inherited
14098 // constructor call.
14099 for (NamedDecl *Ctor : Derived->lookup(Name))
14100 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
14101 ->getInheritedConstructor()
14102 .getConstructor(),
14103 BaseCtor))
14104 return cast<CXXConstructorDecl>(Ctor);
14105
14106 DeclarationNameInfo NameInfo(Name, UsingLoc);
14107 TypeSourceInfo *TInfo =
14108 Context.getTrivialTypeSourceInfo(T: BaseCtor->getType(), Loc: UsingLoc);
14109 FunctionProtoTypeLoc ProtoLoc =
14110 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14111
14112 // Check the inherited constructor is valid and find the list of base classes
14113 // from which it was inherited.
14114 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14115
14116 bool Constexpr =
14117 BaseCtor->isConstexpr() &&
14118 defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: Derived, CSM: CXXDefaultConstructor,
14119 ConstArg: false, InheritedCtor: BaseCtor, Inherited: &ICI);
14120
14121 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14122 C&: Context, RD: Derived, StartLoc: UsingLoc, NameInfo, T: TInfo->getType(), TInfo,
14123 ES: BaseCtor->getExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14124 /*isInline=*/true,
14125 /*isImplicitlyDeclared=*/true,
14126 ConstexprKind: Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14127 Inherited: InheritedConstructor(Shadow, BaseCtor),
14128 TrailingRequiresClause: BaseCtor->getTrailingRequiresClause());
14129 if (Shadow->isInvalidDecl())
14130 DerivedCtor->setInvalidDecl();
14131
14132 // Build an unevaluated exception specification for this fake constructor.
14133 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14134 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14135 EPI.ExceptionSpec.Type = EST_Unevaluated;
14136 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14137 DerivedCtor->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
14138 Args: FPT->getParamTypes(), EPI));
14139
14140 // Build the parameter declarations.
14141 SmallVector<ParmVarDecl *, 16> ParamDecls;
14142 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14143 TypeSourceInfo *TInfo =
14144 Context.getTrivialTypeSourceInfo(T: FPT->getParamType(i: I), Loc: UsingLoc);
14145 ParmVarDecl *PD = ParmVarDecl::Create(
14146 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14147 FPT->getParamType(i: I), TInfo, SC_None, /*DefArg=*/nullptr);
14148 PD->setScopeInfo(scopeDepth: 0, parameterIndex: I);
14149 PD->setImplicit();
14150 // Ensure attributes are propagated onto parameters (this matters for
14151 // format, pass_object_size, ...).
14152 mergeDeclAttributes(New: PD, Old: BaseCtor->getParamDecl(I));
14153 ParamDecls.push_back(Elt: PD);
14154 ProtoLoc.setParam(I, PD);
14155 }
14156
14157 // Set up the new constructor.
14158 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14159 DerivedCtor->setAccess(BaseCtor->getAccess());
14160 DerivedCtor->setParams(ParamDecls);
14161 Derived->addDecl(DerivedCtor);
14162
14163 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
14164 SetDeclDeleted(DerivedCtor, UsingLoc);
14165
14166 return DerivedCtor;
14167}
14168
14169void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14170 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14171 Ctor->getInheritedConstructor().getShadowDecl());
14172 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
14173 /*Diagnose*/true);
14174}
14175
14176void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14177 CXXConstructorDecl *Constructor) {
14178 CXXRecordDecl *ClassDecl = Constructor->getParent();
14179 assert(Constructor->getInheritedConstructor() &&
14180 !Constructor->doesThisDeclarationHaveABody() &&
14181 !Constructor->isDeleted());
14182 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14183 return;
14184
14185 // Initializations are performed "as if by a defaulted default constructor",
14186 // so enter the appropriate scope.
14187 SynthesizedFunctionScope Scope(*this, Constructor);
14188
14189 // The exception specification is needed because we are defining the
14190 // function.
14191 ResolveExceptionSpec(Loc: CurrentLocation,
14192 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14193 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14194
14195 // Add a context note for diagnostics produced after this point.
14196 Scope.addContextNote(UseLoc: CurrentLocation);
14197
14198 ConstructorUsingShadowDecl *Shadow =
14199 Constructor->getInheritedConstructor().getShadowDecl();
14200 CXXConstructorDecl *InheritedCtor =
14201 Constructor->getInheritedConstructor().getConstructor();
14202
14203 // [class.inhctor.init]p1:
14204 // initialization proceeds as if a defaulted default constructor is used to
14205 // initialize the D object and each base class subobject from which the
14206 // constructor was inherited
14207
14208 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14209 CXXRecordDecl *RD = Shadow->getParent();
14210 SourceLocation InitLoc = Shadow->getLocation();
14211
14212 // Build explicit initializers for all base classes from which the
14213 // constructor was inherited.
14214 SmallVector<CXXCtorInitializer*, 8> Inits;
14215 for (bool VBase : {false, true}) {
14216 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14217 if (B.isVirtual() != VBase)
14218 continue;
14219
14220 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14221 if (!BaseRD)
14222 continue;
14223
14224 auto BaseCtor = ICI.findConstructorForBase(Base: BaseRD, Ctor: InheritedCtor);
14225 if (!BaseCtor.first)
14226 continue;
14227
14228 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14229 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14230 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14231
14232 auto *TInfo = Context.getTrivialTypeSourceInfo(T: B.getType(), Loc: InitLoc);
14233 Inits.push_back(Elt: new (Context) CXXCtorInitializer(
14234 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14235 SourceLocation()));
14236 }
14237 }
14238
14239 // We now proceed as if for a defaulted default constructor, with the relevant
14240 // initializers replaced.
14241
14242 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Initializers: Inits)) {
14243 Constructor->setInvalidDecl();
14244 return;
14245 }
14246
14247 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14248 Constructor->markUsed(Context);
14249
14250 if (ASTMutationListener *L = getASTMutationListener()) {
14251 L->CompletedImplicitDefinition(Constructor);
14252 }
14253
14254 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14255}
14256
14257CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14258 // C++ [class.dtor]p2:
14259 // If a class has no user-declared destructor, a destructor is
14260 // declared implicitly. An implicitly-declared destructor is an
14261 // inline public member of its class.
14262 assert(ClassDecl->needsImplicitDestructor());
14263
14264 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
14265 if (DSM.isAlreadyBeingDeclared())
14266 return nullptr;
14267
14268 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl,
14269 CSM: CXXDestructor,
14270 ConstArg: false);
14271
14272 // Create the actual destructor declaration.
14273 CanQualType ClassType
14274 = Context.getCanonicalType(T: Context.getTypeDeclType(ClassDecl));
14275 SourceLocation ClassLoc = ClassDecl->getLocation();
14276 DeclarationName Name
14277 = Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
14278 DeclarationNameInfo NameInfo(Name, ClassLoc);
14279 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14280 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), TInfo: nullptr,
14281 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14282 /*isInline=*/true,
14283 /*isImplicitlyDeclared=*/true,
14284 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14285 : ConstexprSpecKind::Unspecified);
14286 Destructor->setAccess(AS_public);
14287 Destructor->setDefaulted();
14288
14289 setupImplicitSpecialMemberType(SpecialMem: Destructor, ResultTy: Context.VoidTy, Args: std::nullopt);
14290
14291 if (getLangOpts().CUDA)
14292 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
14293 Destructor,
14294 /* ConstRHS */ false,
14295 /* Diagnose */ false);
14296
14297 // We don't need to use SpecialMemberIsTrivial here; triviality for
14298 // destructors is easy to compute.
14299 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14300 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14301 ClassDecl->hasTrivialDestructorForCall());
14302
14303 // Note that we have declared this destructor.
14304 ++getASTContext().NumImplicitDestructorsDeclared;
14305
14306 Scope *S = getScopeForContext(ClassDecl);
14307 CheckImplicitSpecialMemberDeclaration(S, Destructor);
14308
14309 // We can't check whether an implicit destructor is deleted before we complete
14310 // the definition of the class, because its validity depends on the alignment
14311 // of the class. We'll check this from ActOnFields once the class is complete.
14312 if (ClassDecl->isCompleteDefinition() &&
14313 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
14314 SetDeclDeleted(Destructor, ClassLoc);
14315
14316 // Introduce this destructor into its scope.
14317 if (S)
14318 PushOnScopeChains(Destructor, S, false);
14319 ClassDecl->addDecl(Destructor);
14320
14321 return Destructor;
14322}
14323
14324void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14325 CXXDestructorDecl *Destructor) {
14326 assert((Destructor->isDefaulted() &&
14327 !Destructor->doesThisDeclarationHaveABody() &&
14328 !Destructor->isDeleted()) &&
14329 "DefineImplicitDestructor - call it for implicit default dtor");
14330 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14331 return;
14332
14333 CXXRecordDecl *ClassDecl = Destructor->getParent();
14334 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14335
14336 SynthesizedFunctionScope Scope(*this, Destructor);
14337
14338 // The exception specification is needed because we are defining the
14339 // function.
14340 ResolveExceptionSpec(Loc: CurrentLocation,
14341 FPT: Destructor->getType()->castAs<FunctionProtoType>());
14342 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14343
14344 // Add a context note for diagnostics produced after this point.
14345 Scope.addContextNote(UseLoc: CurrentLocation);
14346
14347 MarkBaseAndMemberDestructorsReferenced(Location: Destructor->getLocation(),
14348 ClassDecl: Destructor->getParent());
14349
14350 if (CheckDestructor(Destructor)) {
14351 Destructor->setInvalidDecl();
14352 return;
14353 }
14354
14355 SourceLocation Loc = Destructor->getEndLoc().isValid()
14356 ? Destructor->getEndLoc()
14357 : Destructor->getLocation();
14358 Destructor->setBody(new (Context) CompoundStmt(Loc));
14359 Destructor->markUsed(Context);
14360
14361 if (ASTMutationListener *L = getASTMutationListener()) {
14362 L->CompletedImplicitDefinition(Destructor);
14363 }
14364}
14365
14366void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14367 CXXDestructorDecl *Destructor) {
14368 if (Destructor->isInvalidDecl())
14369 return;
14370
14371 CXXRecordDecl *ClassDecl = Destructor->getParent();
14372 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14373 "implicit complete dtors unneeded outside MS ABI");
14374 assert(ClassDecl->getNumVBases() > 0 &&
14375 "complete dtor only exists for classes with vbases");
14376
14377 SynthesizedFunctionScope Scope(*this, Destructor);
14378
14379 // Add a context note for diagnostics produced after this point.
14380 Scope.addContextNote(UseLoc: CurrentLocation);
14381
14382 MarkVirtualBaseDestructorsReferenced(Location: Destructor->getLocation(), ClassDecl);
14383}
14384
14385/// Perform any semantic analysis which needs to be delayed until all
14386/// pending class member declarations have been parsed.
14387void Sema::ActOnFinishCXXMemberDecls() {
14388 // If the context is an invalid C++ class, just suppress these checks.
14389 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
14390 if (Record->isInvalidDecl()) {
14391 DelayedOverridingExceptionSpecChecks.clear();
14392 DelayedEquivalentExceptionSpecChecks.clear();
14393 return;
14394 }
14395 checkForMultipleExportedDefaultConstructors(S&: *this, Class: Record);
14396 }
14397}
14398
14399void Sema::ActOnFinishCXXNonNestedClass() {
14400 referenceDLLExportedClassMethods();
14401
14402 if (!DelayedDllExportMemberFunctions.empty()) {
14403 SmallVector<CXXMethodDecl*, 4> WorkList;
14404 std::swap(LHS&: DelayedDllExportMemberFunctions, RHS&: WorkList);
14405 for (CXXMethodDecl *M : WorkList) {
14406 DefineDefaultedFunction(*this, M, M->getLocation());
14407
14408 // Pass the method to the consumer to get emitted. This is not necessary
14409 // for explicit instantiation definitions, as they will get emitted
14410 // anyway.
14411 if (M->getParent()->getTemplateSpecializationKind() !=
14412 TSK_ExplicitInstantiationDefinition)
14413 ActOnFinishInlineFunctionDef(M);
14414 }
14415 }
14416}
14417
14418void Sema::referenceDLLExportedClassMethods() {
14419 if (!DelayedDllExportClasses.empty()) {
14420 // Calling ReferenceDllExportedMembers might cause the current function to
14421 // be called again, so use a local copy of DelayedDllExportClasses.
14422 SmallVector<CXXRecordDecl *, 4> WorkList;
14423 std::swap(LHS&: DelayedDllExportClasses, RHS&: WorkList);
14424 for (CXXRecordDecl *Class : WorkList)
14425 ReferenceDllExportedMembers(S&: *this, Class);
14426 }
14427}
14428
14429void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14430 assert(getLangOpts().CPlusPlus11 &&
14431 "adjusting dtor exception specs was introduced in c++11");
14432
14433 if (Destructor->isDependentContext())
14434 return;
14435
14436 // C++11 [class.dtor]p3:
14437 // A declaration of a destructor that does not have an exception-
14438 // specification is implicitly considered to have the same exception-
14439 // specification as an implicit declaration.
14440 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14441 if (DtorType->hasExceptionSpec())
14442 return;
14443
14444 // Replace the destructor's type, building off the existing one. Fortunately,
14445 // the only thing of interest in the destructor type is its extended info.
14446 // The return and arguments are fixed.
14447 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14448 EPI.ExceptionSpec.Type = EST_Unevaluated;
14449 EPI.ExceptionSpec.SourceDecl = Destructor;
14450 Destructor->setType(
14451 Context.getFunctionType(ResultTy: Context.VoidTy, Args: std::nullopt, EPI));
14452
14453 // FIXME: If the destructor has a body that could throw, and the newly created
14454 // spec doesn't allow exceptions, we should emit a warning, because this
14455 // change in behavior can break conforming C++03 programs at runtime.
14456 // However, we don't have a body or an exception specification yet, so it
14457 // needs to be done somewhere else.
14458}
14459
14460namespace {
14461/// An abstract base class for all helper classes used in building the
14462// copy/move operators. These classes serve as factory functions and help us
14463// avoid using the same Expr* in the AST twice.
14464class ExprBuilder {
14465 ExprBuilder(const ExprBuilder&) = delete;
14466 ExprBuilder &operator=(const ExprBuilder&) = delete;
14467
14468protected:
14469 static Expr *assertNotNull(Expr *E) {
14470 assert(E && "Expression construction must not fail.");
14471 return E;
14472 }
14473
14474public:
14475 ExprBuilder() {}
14476 virtual ~ExprBuilder() {}
14477
14478 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14479};
14480
14481class RefBuilder: public ExprBuilder {
14482 VarDecl *Var;
14483 QualType VarType;
14484
14485public:
14486 Expr *build(Sema &S, SourceLocation Loc) const override {
14487 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14488 }
14489
14490 RefBuilder(VarDecl *Var, QualType VarType)
14491 : Var(Var), VarType(VarType) {}
14492};
14493
14494class ThisBuilder: public ExprBuilder {
14495public:
14496 Expr *build(Sema &S, SourceLocation Loc) const override {
14497 return assertNotNull(E: S.ActOnCXXThis(loc: Loc).getAs<Expr>());
14498 }
14499};
14500
14501class CastBuilder: public ExprBuilder {
14502 const ExprBuilder &Builder;
14503 QualType Type;
14504 ExprValueKind Kind;
14505 const CXXCastPath &Path;
14506
14507public:
14508 Expr *build(Sema &S, SourceLocation Loc) const override {
14509 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14510 CK_UncheckedDerivedToBase, Kind,
14511 &Path).get());
14512 }
14513
14514 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14515 const CXXCastPath &Path)
14516 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14517};
14518
14519class DerefBuilder: public ExprBuilder {
14520 const ExprBuilder &Builder;
14521
14522public:
14523 Expr *build(Sema &S, SourceLocation Loc) const override {
14524 return assertNotNull(
14525 E: S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: Builder.build(S, Loc)).get());
14526 }
14527
14528 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14529};
14530
14531class MemberBuilder: public ExprBuilder {
14532 const ExprBuilder &Builder;
14533 QualType Type;
14534 CXXScopeSpec SS;
14535 bool IsArrow;
14536 LookupResult &MemberLookup;
14537
14538public:
14539 Expr *build(Sema &S, SourceLocation Loc) const override {
14540 return assertNotNull(S.BuildMemberReferenceExpr(
14541 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14542 nullptr, MemberLookup, nullptr, nullptr).get());
14543 }
14544
14545 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14546 LookupResult &MemberLookup)
14547 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14548 MemberLookup(MemberLookup) {}
14549};
14550
14551class MoveCastBuilder: public ExprBuilder {
14552 const ExprBuilder &Builder;
14553
14554public:
14555 Expr *build(Sema &S, SourceLocation Loc) const override {
14556 return assertNotNull(E: CastForMoving(SemaRef&: S, E: Builder.build(S, Loc)));
14557 }
14558
14559 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14560};
14561
14562class LvalueConvBuilder: public ExprBuilder {
14563 const ExprBuilder &Builder;
14564
14565public:
14566 Expr *build(Sema &S, SourceLocation Loc) const override {
14567 return assertNotNull(
14568 E: S.DefaultLvalueConversion(E: Builder.build(S, Loc)).get());
14569 }
14570
14571 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14572};
14573
14574class SubscriptBuilder: public ExprBuilder {
14575 const ExprBuilder &Base;
14576 const ExprBuilder &Index;
14577
14578public:
14579 Expr *build(Sema &S, SourceLocation Loc) const override {
14580 return assertNotNull(E: S.CreateBuiltinArraySubscriptExpr(
14581 Base: Base.build(S, Loc), LLoc: Loc, Idx: Index.build(S, Loc), RLoc: Loc).get());
14582 }
14583
14584 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14585 : Base(Base), Index(Index) {}
14586};
14587
14588} // end anonymous namespace
14589
14590/// When generating a defaulted copy or move assignment operator, if a field
14591/// should be copied with __builtin_memcpy rather than via explicit assignments,
14592/// do so. This optimization only applies for arrays of scalars, and for arrays
14593/// of class type where the selected copy/move-assignment operator is trivial.
14594static StmtResult
14595buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14596 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14597 // Compute the size of the memory buffer to be copied.
14598 QualType SizeType = S.Context.getSizeType();
14599 llvm::APInt Size(S.Context.getTypeSize(T: SizeType),
14600 S.Context.getTypeSizeInChars(T).getQuantity());
14601
14602 // Take the address of the field references for "from" and "to". We
14603 // directly construct UnaryOperators here because semantic analysis
14604 // does not permit us to take the address of an xvalue.
14605 Expr *From = FromB.build(S, Loc);
14606 From = UnaryOperator::Create(
14607 C: S.Context, input: From, opc: UO_AddrOf, type: S.Context.getPointerType(T: From->getType()),
14608 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14609 Expr *To = ToB.build(S, Loc);
14610 To = UnaryOperator::Create(
14611 C: S.Context, input: To, opc: UO_AddrOf, type: S.Context.getPointerType(T: To->getType()),
14612 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14613
14614 const Type *E = T->getBaseElementTypeUnsafe();
14615 bool NeedsCollectableMemCpy =
14616 E->isRecordType() &&
14617 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14618
14619 // Create a reference to the __builtin_objc_memmove_collectable function
14620 StringRef MemCpyName = NeedsCollectableMemCpy ?
14621 "__builtin_objc_memmove_collectable" :
14622 "__builtin_memcpy";
14623 LookupResult R(S, &S.Context.Idents.get(Name: MemCpyName), Loc,
14624 Sema::LookupOrdinaryName);
14625 S.LookupName(R, S: S.TUScope, AllowBuiltinCreation: true);
14626
14627 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14628 if (!MemCpy)
14629 // Something went horribly wrong earlier, and we will have complained
14630 // about it.
14631 return StmtError();
14632
14633 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14634 VK_PRValue, Loc, nullptr);
14635 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14636
14637 Expr *CallArgs[] = {
14638 To, From, IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc)
14639 };
14640 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14641 Loc, CallArgs, Loc);
14642
14643 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14644 return Call.getAs<Stmt>();
14645}
14646
14647/// Builds a statement that copies/moves the given entity from \p From to
14648/// \c To.
14649///
14650/// This routine is used to copy/move the members of a class with an
14651/// implicitly-declared copy/move assignment operator. When the entities being
14652/// copied are arrays, this routine builds for loops to copy them.
14653///
14654/// \param S The Sema object used for type-checking.
14655///
14656/// \param Loc The location where the implicit copy/move is being generated.
14657///
14658/// \param T The type of the expressions being copied/moved. Both expressions
14659/// must have this type.
14660///
14661/// \param To The expression we are copying/moving to.
14662///
14663/// \param From The expression we are copying/moving from.
14664///
14665/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14666/// Otherwise, it's a non-static member subobject.
14667///
14668/// \param Copying Whether we're copying or moving.
14669///
14670/// \param Depth Internal parameter recording the depth of the recursion.
14671///
14672/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14673/// if a memcpy should be used instead.
14674static StmtResult
14675buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14676 const ExprBuilder &To, const ExprBuilder &From,
14677 bool CopyingBaseSubobject, bool Copying,
14678 unsigned Depth = 0) {
14679 // C++11 [class.copy]p28:
14680 // Each subobject is assigned in the manner appropriate to its type:
14681 //
14682 // - if the subobject is of class type, as if by a call to operator= with
14683 // the subobject as the object expression and the corresponding
14684 // subobject of x as a single function argument (as if by explicit
14685 // qualification; that is, ignoring any possible virtual overriding
14686 // functions in more derived classes);
14687 //
14688 // C++03 [class.copy]p13:
14689 // - if the subobject is of class type, the copy assignment operator for
14690 // the class is used (as if by explicit qualification; that is,
14691 // ignoring any possible virtual overriding functions in more derived
14692 // classes);
14693 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14694 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: RecordTy->getDecl());
14695
14696 // Look for operator=.
14697 DeclarationName Name
14698 = S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
14699 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14700 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14701
14702 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14703 // operator.
14704 if (!S.getLangOpts().CPlusPlus11) {
14705 LookupResult::Filter F = OpLookup.makeFilter();
14706 while (F.hasNext()) {
14707 NamedDecl *D = F.next();
14708 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D))
14709 if (Method->isCopyAssignmentOperator() ||
14710 (!Copying && Method->isMoveAssignmentOperator()))
14711 continue;
14712
14713 F.erase();
14714 }
14715 F.done();
14716 }
14717
14718 // Suppress the protected check (C++ [class.protected]) for each of the
14719 // assignment operators we found. This strange dance is required when
14720 // we're assigning via a base classes's copy-assignment operator. To
14721 // ensure that we're getting the right base class subobject (without
14722 // ambiguities), we need to cast "this" to that subobject type; to
14723 // ensure that we don't go through the virtual call mechanism, we need
14724 // to qualify the operator= name with the base class (see below). However,
14725 // this means that if the base class has a protected copy assignment
14726 // operator, the protected member access check will fail. So, we
14727 // rewrite "protected" access to "public" access in this case, since we
14728 // know by construction that we're calling from a derived class.
14729 if (CopyingBaseSubobject) {
14730 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14731 L != LEnd; ++L) {
14732 if (L.getAccess() == AS_protected)
14733 L.setAccess(AS_public);
14734 }
14735 }
14736
14737 // Create the nested-name-specifier that will be used to qualify the
14738 // reference to operator=; this is required to suppress the virtual
14739 // call mechanism.
14740 CXXScopeSpec SS;
14741 const Type *CanonicalT = S.Context.getCanonicalType(T: T.getTypePtr());
14742 SS.MakeTrivial(Context&: S.Context,
14743 Qualifier: NestedNameSpecifier::Create(Context: S.Context, Prefix: nullptr, Template: false,
14744 T: CanonicalT),
14745 R: Loc);
14746
14747 // Create the reference to operator=.
14748 ExprResult OpEqualRef
14749 = S.BuildMemberReferenceExpr(Base: To.build(S, Loc), BaseType: T, OpLoc: Loc, /*IsArrow=*/false,
14750 SS, /*TemplateKWLoc=*/SourceLocation(),
14751 /*FirstQualifierInScope=*/nullptr,
14752 R&: OpLookup,
14753 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14754 /*SuppressQualifierCheck=*/true);
14755 if (OpEqualRef.isInvalid())
14756 return StmtError();
14757
14758 // Build the call to the assignment operator.
14759
14760 Expr *FromInst = From.build(S, Loc);
14761 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/S: nullptr,
14762 MemExpr: OpEqualRef.getAs<Expr>(),
14763 LParenLoc: Loc, Args: FromInst, RParenLoc: Loc);
14764 if (Call.isInvalid())
14765 return StmtError();
14766
14767 // If we built a call to a trivial 'operator=' while copying an array,
14768 // bail out. We'll replace the whole shebang with a memcpy.
14769 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Val: Call.get());
14770 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14771 return StmtResult((Stmt*)nullptr);
14772
14773 // Convert to an expression-statement, and clean up any produced
14774 // temporaries.
14775 return S.ActOnExprStmt(Arg: Call);
14776 }
14777
14778 // - if the subobject is of scalar type, the built-in assignment
14779 // operator is used.
14780 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14781 if (!ArrayTy) {
14782 ExprResult Assignment = S.CreateBuiltinBinOp(
14783 OpLoc: Loc, Opc: BO_Assign, LHSExpr: To.build(S, Loc), RHSExpr: From.build(S, Loc));
14784 if (Assignment.isInvalid())
14785 return StmtError();
14786 return S.ActOnExprStmt(Arg: Assignment);
14787 }
14788
14789 // - if the subobject is an array, each element is assigned, in the
14790 // manner appropriate to the element type;
14791
14792 // Construct a loop over the array bounds, e.g.,
14793 //
14794 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14795 //
14796 // that will copy each of the array elements.
14797 QualType SizeType = S.Context.getSizeType();
14798
14799 // Create the iteration variable.
14800 IdentifierInfo *IterationVarName = nullptr;
14801 {
14802 SmallString<8> Str;
14803 llvm::raw_svector_ostream OS(Str);
14804 OS << "__i" << Depth;
14805 IterationVarName = &S.Context.Idents.get(Name: OS.str());
14806 }
14807 VarDecl *IterationVar = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc,
14808 Id: IterationVarName, T: SizeType,
14809 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc),
14810 S: SC_None);
14811
14812 // Initialize the iteration variable to zero.
14813 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
14814 IterationVar->setInit(IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
14815
14816 // Creates a reference to the iteration variable.
14817 RefBuilder IterationVarRef(IterationVar, SizeType);
14818 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14819
14820 // Create the DeclStmt that holds the iteration variable.
14821 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14822
14823 // Subscript the "from" and "to" expressions with the iteration variable.
14824 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14825 MoveCastBuilder FromIndexMove(FromIndexCopy);
14826 const ExprBuilder *FromIndex;
14827 if (Copying)
14828 FromIndex = &FromIndexCopy;
14829 else
14830 FromIndex = &FromIndexMove;
14831
14832 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14833
14834 // Build the copy/move for an individual element of the array.
14835 StmtResult Copy =
14836 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14837 ToIndex, *FromIndex, CopyingBaseSubobject,
14838 Copying, Depth + 1);
14839 // Bail out if copying fails or if we determined that we should use memcpy.
14840 if (Copy.isInvalid() || !Copy.get())
14841 return Copy;
14842
14843 // Create the comparison against the array bound.
14844 llvm::APInt Upper
14845 = ArrayTy->getSize().zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
14846 Expr *Comparison = BinaryOperator::Create(
14847 C: S.Context, lhs: IterationVarRefRVal.build(S, Loc),
14848 rhs: IntegerLiteral::Create(C: S.Context, V: Upper, type: SizeType, l: Loc), opc: BO_NE,
14849 ResTy: S.Context.BoolTy, VK: VK_PRValue, OK: OK_Ordinary, opLoc: Loc,
14850 FPFeatures: S.CurFPFeatureOverrides());
14851
14852 // Create the pre-increment of the iteration variable. We can determine
14853 // whether the increment will overflow based on the value of the array
14854 // bound.
14855 Expr *Increment = UnaryOperator::Create(
14856 C: S.Context, input: IterationVarRef.build(S, Loc), opc: UO_PreInc, type: SizeType, VK: VK_LValue,
14857 OK: OK_Ordinary, l: Loc, CanOverflow: Upper.isMaxValue(), FPFeatures: S.CurFPFeatureOverrides());
14858
14859 // Construct the loop that copies all elements of this array.
14860 return S.ActOnForStmt(
14861 ForLoc: Loc, LParenLoc: Loc, First: InitStmt,
14862 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Comparison, CK: Sema::ConditionKind::Boolean),
14863 Third: S.MakeFullDiscardedValueExpr(Arg: Increment), RParenLoc: Loc, Body: Copy.get());
14864}
14865
14866static StmtResult
14867buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14868 const ExprBuilder &To, const ExprBuilder &From,
14869 bool CopyingBaseSubobject, bool Copying) {
14870 // Maybe we should use a memcpy?
14871 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14872 T.isTriviallyCopyableType(Context: S.Context))
14873 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
14874
14875 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14876 CopyingBaseSubobject,
14877 Copying, Depth: 0));
14878
14879 // If we ended up picking a trivial assignment operator for an array of a
14880 // non-trivially-copyable class type, just emit a memcpy.
14881 if (!Result.isInvalid() && !Result.get())
14882 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
14883
14884 return Result;
14885}
14886
14887CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14888 // Note: The following rules are largely analoguous to the copy
14889 // constructor rules. Note that virtual bases are not taken into account
14890 // for determining the argument type of the operator. Note also that
14891 // operators taking an object instead of a reference are allowed.
14892 assert(ClassDecl->needsImplicitCopyAssignment());
14893
14894 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14895 if (DSM.isAlreadyBeingDeclared())
14896 return nullptr;
14897
14898 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14899 ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
14900 NamedType: ArgType, OwnedTagDecl: nullptr);
14901 LangAS AS = getDefaultCXXMethodAddrSpace();
14902 if (AS != LangAS::Default)
14903 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
14904 QualType RetType = Context.getLValueReferenceType(T: ArgType);
14905 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14906 if (Const)
14907 ArgType = ArgType.withConst();
14908
14909 ArgType = Context.getLValueReferenceType(T: ArgType);
14910
14911 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl,
14912 CSM: CXXCopyAssignment,
14913 ConstArg: Const);
14914
14915 // An implicitly-declared copy assignment operator is an inline public
14916 // member of its class.
14917 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
14918 SourceLocation ClassLoc = ClassDecl->getLocation();
14919 DeclarationNameInfo NameInfo(Name, ClassLoc);
14920 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14921 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
14922 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
14923 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14924 /*isInline=*/true,
14925 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14926 EndLocation: SourceLocation());
14927 CopyAssignment->setAccess(AS_public);
14928 CopyAssignment->setDefaulted();
14929 CopyAssignment->setImplicit();
14930
14931 setupImplicitSpecialMemberType(SpecialMem: CopyAssignment, ResultTy: RetType, Args: ArgType);
14932
14933 if (getLangOpts().CUDA)
14934 inferCUDATargetForImplicitSpecialMember(ClassDecl, CSM: CXXCopyAssignment,
14935 MemberDecl: CopyAssignment,
14936 /* ConstRHS */ Const,
14937 /* Diagnose */ false);
14938
14939 // Add the parameter to the operator.
14940 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14941 ClassLoc, ClassLoc,
14942 /*Id=*/nullptr, ArgType,
14943 /*TInfo=*/nullptr, SC_None,
14944 nullptr);
14945 CopyAssignment->setParams(FromParam);
14946
14947 CopyAssignment->setTrivial(
14948 ClassDecl->needsOverloadResolutionForCopyAssignment()
14949 ? SpecialMemberIsTrivial(MD: CopyAssignment, CSM: CXXCopyAssignment)
14950 : ClassDecl->hasTrivialCopyAssignment());
14951
14952 // Note that we have added this copy-assignment operator.
14953 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14954
14955 Scope *S = getScopeForContext(ClassDecl);
14956 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14957
14958 if (ShouldDeleteSpecialMember(MD: CopyAssignment, CSM: CXXCopyAssignment)) {
14959 ClassDecl->setImplicitCopyAssignmentIsDeleted();
14960 SetDeclDeleted(CopyAssignment, ClassLoc);
14961 }
14962
14963 if (S)
14964 PushOnScopeChains(CopyAssignment, S, false);
14965 ClassDecl->addDecl(CopyAssignment);
14966
14967 return CopyAssignment;
14968}
14969
14970/// Diagnose an implicit copy operation for a class which is odr-used, but
14971/// which is deprecated because the class has a user-declared copy constructor,
14972/// copy assignment operator, or destructor.
14973static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14974 assert(CopyOp->isImplicit());
14975
14976 CXXRecordDecl *RD = CopyOp->getParent();
14977 CXXMethodDecl *UserDeclaredOperation = nullptr;
14978
14979 if (RD->hasUserDeclaredDestructor()) {
14980 UserDeclaredOperation = RD->getDestructor();
14981 } else if (!isa<CXXConstructorDecl>(Val: CopyOp) &&
14982 RD->hasUserDeclaredCopyConstructor()) {
14983 // Find any user-declared copy constructor.
14984 for (auto *I : RD->ctors()) {
14985 if (I->isCopyConstructor()) {
14986 UserDeclaredOperation = I;
14987 break;
14988 }
14989 }
14990 assert(UserDeclaredOperation);
14991 } else if (isa<CXXConstructorDecl>(Val: CopyOp) &&
14992 RD->hasUserDeclaredCopyAssignment()) {
14993 // Find any user-declared move assignment operator.
14994 for (auto *I : RD->methods()) {
14995 if (I->isCopyAssignmentOperator()) {
14996 UserDeclaredOperation = I;
14997 break;
14998 }
14999 }
15000 assert(UserDeclaredOperation);
15001 }
15002
15003 if (UserDeclaredOperation) {
15004 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15005 bool UDOIsDestructor = isa<CXXDestructorDecl>(Val: UserDeclaredOperation);
15006 bool IsCopyAssignment = !isa<CXXConstructorDecl>(Val: CopyOp);
15007 unsigned DiagID =
15008 (UDOIsUserProvided && UDOIsDestructor)
15009 ? diag::warn_deprecated_copy_with_user_provided_dtor
15010 : (UDOIsUserProvided && !UDOIsDestructor)
15011 ? diag::warn_deprecated_copy_with_user_provided_copy
15012 : (!UDOIsUserProvided && UDOIsDestructor)
15013 ? diag::warn_deprecated_copy_with_dtor
15014 : diag::warn_deprecated_copy;
15015 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15016 << RD << IsCopyAssignment;
15017 }
15018}
15019
15020void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15021 CXXMethodDecl *CopyAssignOperator) {
15022 assert((CopyAssignOperator->isDefaulted() &&
15023 CopyAssignOperator->isOverloadedOperator() &&
15024 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15025 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15026 !CopyAssignOperator->isDeleted()) &&
15027 "DefineImplicitCopyAssignment called for wrong function");
15028 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15029 return;
15030
15031 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15032 if (ClassDecl->isInvalidDecl()) {
15033 CopyAssignOperator->setInvalidDecl();
15034 return;
15035 }
15036
15037 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15038
15039 // The exception specification is needed because we are defining the
15040 // function.
15041 ResolveExceptionSpec(Loc: CurrentLocation,
15042 FPT: CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15043
15044 // Add a context note for diagnostics produced after this point.
15045 Scope.addContextNote(UseLoc: CurrentLocation);
15046
15047 // C++11 [class.copy]p18:
15048 // The [definition of an implicitly declared copy assignment operator] is
15049 // deprecated if the class has a user-declared copy constructor or a
15050 // user-declared destructor.
15051 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15052 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyAssignOperator);
15053
15054 // C++0x [class.copy]p30:
15055 // The implicitly-defined or explicitly-defaulted copy assignment operator
15056 // for a non-union class X performs memberwise copy assignment of its
15057 // subobjects. The direct base classes of X are assigned first, in the
15058 // order of their declaration in the base-specifier-list, and then the
15059 // immediate non-static data members of X are assigned, in the order in
15060 // which they were declared in the class definition.
15061
15062 // The statements that form the synthesized function body.
15063 SmallVector<Stmt*, 8> Statements;
15064
15065 // The parameter for the "other" object, which we are copying from.
15066 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15067 Qualifiers OtherQuals = Other->getType().getQualifiers();
15068 QualType OtherRefType = Other->getType();
15069 if (OtherRefType->isLValueReferenceType()) {
15070 OtherRefType = OtherRefType->getPointeeType();
15071 OtherQuals = OtherRefType.getQualifiers();
15072 }
15073
15074 // Our location for everything implicitly-generated.
15075 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15076 ? CopyAssignOperator->getEndLoc()
15077 : CopyAssignOperator->getLocation();
15078
15079 // Builds a DeclRefExpr for the "other" object.
15080 RefBuilder OtherRef(Other, OtherRefType);
15081
15082 // Builds the function object parameter.
15083 std::optional<ThisBuilder> This;
15084 std::optional<DerefBuilder> DerefThis;
15085 std::optional<RefBuilder> ExplicitObject;
15086 bool IsArrow = false;
15087 QualType ObjectType;
15088 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15089 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15090 if (ObjectType->isReferenceType())
15091 ObjectType = ObjectType->getPointeeType();
15092 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15093 } else {
15094 ObjectType = getCurrentThisType();
15095 This.emplace();
15096 DerefThis.emplace(args&: *This);
15097 IsArrow = !LangOpts.HLSL;
15098 }
15099 ExprBuilder &ObjectParameter =
15100 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15101 : static_cast<ExprBuilder &>(*This);
15102
15103 // Assign base classes.
15104 bool Invalid = false;
15105 for (auto &Base : ClassDecl->bases()) {
15106 // Form the assignment:
15107 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15108 QualType BaseType = Base.getType().getUnqualifiedType();
15109 if (!BaseType->isRecordType()) {
15110 Invalid = true;
15111 continue;
15112 }
15113
15114 CXXCastPath BasePath;
15115 BasePath.push_back(Elt: &Base);
15116
15117 // Construct the "from" expression, which is an implicit cast to the
15118 // appropriately-qualified base type.
15119 CastBuilder From(OtherRef, Context.getQualifiedType(T: BaseType, Qs: OtherQuals),
15120 VK_LValue, BasePath);
15121
15122 // Dereference "this".
15123 CastBuilder To(
15124 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15125 : static_cast<ExprBuilder &>(*DerefThis),
15126 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15127 VK_LValue, BasePath);
15128
15129 // Build the copy.
15130 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15131 To, From,
15132 /*CopyingBaseSubobject=*/true,
15133 /*Copying=*/true);
15134 if (Copy.isInvalid()) {
15135 CopyAssignOperator->setInvalidDecl();
15136 return;
15137 }
15138
15139 // Success! Record the copy.
15140 Statements.push_back(Copy.getAs<Expr>());
15141 }
15142
15143 // Assign non-static members.
15144 for (auto *Field : ClassDecl->fields()) {
15145 // FIXME: We should form some kind of AST representation for the implied
15146 // memcpy in a union copy operation.
15147 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15148 continue;
15149
15150 if (Field->isInvalidDecl()) {
15151 Invalid = true;
15152 continue;
15153 }
15154
15155 // Check for members of reference type; we can't copy those.
15156 if (Field->getType()->isReferenceType()) {
15157 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15158 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15159 Diag(Field->getLocation(), diag::note_declared_at);
15160 Invalid = true;
15161 continue;
15162 }
15163
15164 // Check for members of const-qualified, non-class type.
15165 QualType BaseType = Context.getBaseElementType(Field->getType());
15166 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15167 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15168 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15169 Diag(Field->getLocation(), diag::note_declared_at);
15170 Invalid = true;
15171 continue;
15172 }
15173
15174 // Suppress assigning zero-width bitfields.
15175 if (Field->isZeroLengthBitField(Context))
15176 continue;
15177
15178 QualType FieldType = Field->getType().getNonReferenceType();
15179 if (FieldType->isIncompleteArrayType()) {
15180 assert(ClassDecl->hasFlexibleArrayMember() &&
15181 "Incomplete array type is not valid");
15182 continue;
15183 }
15184
15185 // Build references to the field in the object we're copying from and to.
15186 CXXScopeSpec SS; // Intentionally empty
15187 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15188 LookupMemberName);
15189 MemberLookup.addDecl(Field);
15190 MemberLookup.resolveKind();
15191
15192 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15193 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15194 // Build the copy of this field.
15195 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15196 To, From,
15197 /*CopyingBaseSubobject=*/false,
15198 /*Copying=*/true);
15199 if (Copy.isInvalid()) {
15200 CopyAssignOperator->setInvalidDecl();
15201 return;
15202 }
15203
15204 // Success! Record the copy.
15205 Statements.push_back(Copy.getAs<Stmt>());
15206 }
15207
15208 if (!Invalid) {
15209 // Add a "return *this;"
15210 Expr *ThisExpr =
15211 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15212 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15213 : static_cast<ExprBuilder &>(*DerefThis))
15214 .build(*this, Loc);
15215 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15216 if (Return.isInvalid())
15217 Invalid = true;
15218 else
15219 Statements.push_back(Elt: Return.getAs<Stmt>());
15220 }
15221
15222 if (Invalid) {
15223 CopyAssignOperator->setInvalidDecl();
15224 return;
15225 }
15226
15227 StmtResult Body;
15228 {
15229 CompoundScopeRAII CompoundScope(*this);
15230 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15231 /*isStmtExpr=*/false);
15232 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15233 }
15234 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15235 CopyAssignOperator->markUsed(Context);
15236
15237 if (ASTMutationListener *L = getASTMutationListener()) {
15238 L->CompletedImplicitDefinition(CopyAssignOperator);
15239 }
15240}
15241
15242CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15243 assert(ClassDecl->needsImplicitMoveAssignment());
15244
15245 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
15246 if (DSM.isAlreadyBeingDeclared())
15247 return nullptr;
15248
15249 // Note: The following rules are largely analoguous to the move
15250 // constructor rules.
15251
15252 QualType ArgType = Context.getTypeDeclType(ClassDecl);
15253 ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
15254 NamedType: ArgType, OwnedTagDecl: nullptr);
15255 LangAS AS = getDefaultCXXMethodAddrSpace();
15256 if (AS != LangAS::Default)
15257 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15258 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15259 ArgType = Context.getRValueReferenceType(T: ArgType);
15260
15261 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl,
15262 CSM: CXXMoveAssignment,
15263 ConstArg: false);
15264
15265 // An implicitly-declared move assignment operator is an inline public
15266 // member of its class.
15267 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15268 SourceLocation ClassLoc = ClassDecl->getLocation();
15269 DeclarationNameInfo NameInfo(Name, ClassLoc);
15270 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15271 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15272 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15273 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15274 /*isInline=*/true,
15275 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15276 EndLocation: SourceLocation());
15277 MoveAssignment->setAccess(AS_public);
15278 MoveAssignment->setDefaulted();
15279 MoveAssignment->setImplicit();
15280
15281 setupImplicitSpecialMemberType(SpecialMem: MoveAssignment, ResultTy: RetType, Args: ArgType);
15282
15283 if (getLangOpts().CUDA)
15284 inferCUDATargetForImplicitSpecialMember(ClassDecl, CSM: CXXMoveAssignment,
15285 MemberDecl: MoveAssignment,
15286 /* ConstRHS */ false,
15287 /* Diagnose */ false);
15288
15289 // Add the parameter to the operator.
15290 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
15291 ClassLoc, ClassLoc,
15292 /*Id=*/nullptr, ArgType,
15293 /*TInfo=*/nullptr, SC_None,
15294 nullptr);
15295 MoveAssignment->setParams(FromParam);
15296
15297 MoveAssignment->setTrivial(
15298 ClassDecl->needsOverloadResolutionForMoveAssignment()
15299 ? SpecialMemberIsTrivial(MD: MoveAssignment, CSM: CXXMoveAssignment)
15300 : ClassDecl->hasTrivialMoveAssignment());
15301
15302 // Note that we have added this copy-assignment operator.
15303 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15304
15305 Scope *S = getScopeForContext(ClassDecl);
15306 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
15307
15308 if (ShouldDeleteSpecialMember(MD: MoveAssignment, CSM: CXXMoveAssignment)) {
15309 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15310 SetDeclDeleted(MoveAssignment, ClassLoc);
15311 }
15312
15313 if (S)
15314 PushOnScopeChains(MoveAssignment, S, false);
15315 ClassDecl->addDecl(MoveAssignment);
15316
15317 return MoveAssignment;
15318}
15319
15320/// Check if we're implicitly defining a move assignment operator for a class
15321/// with virtual bases. Such a move assignment might move-assign the virtual
15322/// base multiple times.
15323static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15324 SourceLocation CurrentLocation) {
15325 assert(!Class->isDependentContext() && "should not define dependent move");
15326
15327 // Only a virtual base could get implicitly move-assigned multiple times.
15328 // Only a non-trivial move assignment can observe this. We only want to
15329 // diagnose if we implicitly define an assignment operator that assigns
15330 // two base classes, both of which move-assign the same virtual base.
15331 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15332 Class->getNumBases() < 2)
15333 return;
15334
15335 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15336 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15337 VBaseMap VBases;
15338
15339 for (auto &BI : Class->bases()) {
15340 Worklist.push_back(Elt: &BI);
15341 while (!Worklist.empty()) {
15342 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15343 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15344
15345 // If the base has no non-trivial move assignment operators,
15346 // we don't care about moves from it.
15347 if (!Base->hasNonTrivialMoveAssignment())
15348 continue;
15349
15350 // If there's nothing virtual here, skip it.
15351 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15352 continue;
15353
15354 // If we're not actually going to call a move assignment for this base,
15355 // or the selected move assignment is trivial, skip it.
15356 Sema::SpecialMemberOverloadResult SMOR =
15357 S.LookupSpecialMember(D: Base, SM: Sema::CXXMoveAssignment,
15358 /*ConstArg*/false, /*VolatileArg*/false,
15359 /*RValueThis*/true, /*ConstThis*/false,
15360 /*VolatileThis*/false);
15361 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15362 !SMOR.getMethod()->isMoveAssignmentOperator())
15363 continue;
15364
15365 if (BaseSpec->isVirtual()) {
15366 // We're going to move-assign this virtual base, and its move
15367 // assignment operator is not trivial. If this can happen for
15368 // multiple distinct direct bases of Class, diagnose it. (If it
15369 // only happens in one base, we'll diagnose it when synthesizing
15370 // that base class's move assignment operator.)
15371 CXXBaseSpecifier *&Existing =
15372 VBases.insert(KV: std::make_pair(x: Base->getCanonicalDecl(), y: &BI))
15373 .first->second;
15374 if (Existing && Existing != &BI) {
15375 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15376 << Class << Base;
15377 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15378 << (Base->getCanonicalDecl() ==
15379 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15380 << Base << Existing->getType() << Existing->getSourceRange();
15381 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15382 << (Base->getCanonicalDecl() ==
15383 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15384 << Base << BI.getType() << BaseSpec->getSourceRange();
15385
15386 // Only diagnose each vbase once.
15387 Existing = nullptr;
15388 }
15389 } else {
15390 // Only walk over bases that have defaulted move assignment operators.
15391 // We assume that any user-provided move assignment operator handles
15392 // the multiple-moves-of-vbase case itself somehow.
15393 if (!SMOR.getMethod()->isDefaulted())
15394 continue;
15395
15396 // We're going to move the base classes of Base. Add them to the list.
15397 llvm::append_range(C&: Worklist, R: llvm::make_pointer_range(Range: Base->bases()));
15398 }
15399 }
15400 }
15401}
15402
15403void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15404 CXXMethodDecl *MoveAssignOperator) {
15405 assert((MoveAssignOperator->isDefaulted() &&
15406 MoveAssignOperator->isOverloadedOperator() &&
15407 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15408 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15409 !MoveAssignOperator->isDeleted()) &&
15410 "DefineImplicitMoveAssignment called for wrong function");
15411 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15412 return;
15413
15414 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15415 if (ClassDecl->isInvalidDecl()) {
15416 MoveAssignOperator->setInvalidDecl();
15417 return;
15418 }
15419
15420 // C++0x [class.copy]p28:
15421 // The implicitly-defined or move assignment operator for a non-union class
15422 // X performs memberwise move assignment of its subobjects. The direct base
15423 // classes of X are assigned first, in the order of their declaration in the
15424 // base-specifier-list, and then the immediate non-static data members of X
15425 // are assigned, in the order in which they were declared in the class
15426 // definition.
15427
15428 // Issue a warning if our implicit move assignment operator will move
15429 // from a virtual base more than once.
15430 checkMoveAssignmentForRepeatedMove(S&: *this, Class: ClassDecl, CurrentLocation);
15431
15432 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15433
15434 // The exception specification is needed because we are defining the
15435 // function.
15436 ResolveExceptionSpec(Loc: CurrentLocation,
15437 FPT: MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15438
15439 // Add a context note for diagnostics produced after this point.
15440 Scope.addContextNote(UseLoc: CurrentLocation);
15441
15442 // The statements that form the synthesized function body.
15443 SmallVector<Stmt*, 8> Statements;
15444
15445 // The parameter for the "other" object, which we are move from.
15446 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15447 QualType OtherRefType =
15448 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15449
15450 // Our location for everything implicitly-generated.
15451 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15452 ? MoveAssignOperator->getEndLoc()
15453 : MoveAssignOperator->getLocation();
15454
15455 // Builds a reference to the "other" object.
15456 RefBuilder OtherRef(Other, OtherRefType);
15457 // Cast to rvalue.
15458 MoveCastBuilder MoveOther(OtherRef);
15459
15460 // Builds the function object parameter.
15461 std::optional<ThisBuilder> This;
15462 std::optional<DerefBuilder> DerefThis;
15463 std::optional<RefBuilder> ExplicitObject;
15464 QualType ObjectType;
15465 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15466 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15467 if (ObjectType->isReferenceType())
15468 ObjectType = ObjectType->getPointeeType();
15469 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15470 } else {
15471 ObjectType = getCurrentThisType();
15472 This.emplace();
15473 DerefThis.emplace(args&: *This);
15474 }
15475 ExprBuilder &ObjectParameter =
15476 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15477
15478 // Assign base classes.
15479 bool Invalid = false;
15480 for (auto &Base : ClassDecl->bases()) {
15481 // C++11 [class.copy]p28:
15482 // It is unspecified whether subobjects representing virtual base classes
15483 // are assigned more than once by the implicitly-defined copy assignment
15484 // operator.
15485 // FIXME: Do not assign to a vbase that will be assigned by some other base
15486 // class. For a move-assignment, this can result in the vbase being moved
15487 // multiple times.
15488
15489 // Form the assignment:
15490 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15491 QualType BaseType = Base.getType().getUnqualifiedType();
15492 if (!BaseType->isRecordType()) {
15493 Invalid = true;
15494 continue;
15495 }
15496
15497 CXXCastPath BasePath;
15498 BasePath.push_back(Elt: &Base);
15499
15500 // Construct the "from" expression, which is an implicit cast to the
15501 // appropriately-qualified base type.
15502 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15503
15504 // Implicitly cast "this" to the appropriately-qualified base type.
15505 // Dereference "this".
15506 CastBuilder To(
15507 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15508 : static_cast<ExprBuilder &>(*DerefThis),
15509 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15510 VK_LValue, BasePath);
15511
15512 // Build the move.
15513 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15514 To, From,
15515 /*CopyingBaseSubobject=*/true,
15516 /*Copying=*/false);
15517 if (Move.isInvalid()) {
15518 MoveAssignOperator->setInvalidDecl();
15519 return;
15520 }
15521
15522 // Success! Record the move.
15523 Statements.push_back(Move.getAs<Expr>());
15524 }
15525
15526 // Assign non-static members.
15527 for (auto *Field : ClassDecl->fields()) {
15528 // FIXME: We should form some kind of AST representation for the implied
15529 // memcpy in a union copy operation.
15530 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15531 continue;
15532
15533 if (Field->isInvalidDecl()) {
15534 Invalid = true;
15535 continue;
15536 }
15537
15538 // Check for members of reference type; we can't move those.
15539 if (Field->getType()->isReferenceType()) {
15540 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15541 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15542 Diag(Field->getLocation(), diag::note_declared_at);
15543 Invalid = true;
15544 continue;
15545 }
15546
15547 // Check for members of const-qualified, non-class type.
15548 QualType BaseType = Context.getBaseElementType(Field->getType());
15549 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15550 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15551 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15552 Diag(Field->getLocation(), diag::note_declared_at);
15553 Invalid = true;
15554 continue;
15555 }
15556
15557 // Suppress assigning zero-width bitfields.
15558 if (Field->isZeroLengthBitField(Context))
15559 continue;
15560
15561 QualType FieldType = Field->getType().getNonReferenceType();
15562 if (FieldType->isIncompleteArrayType()) {
15563 assert(ClassDecl->hasFlexibleArrayMember() &&
15564 "Incomplete array type is not valid");
15565 continue;
15566 }
15567
15568 // Build references to the field in the object we're copying from and to.
15569 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15570 LookupMemberName);
15571 MemberLookup.addDecl(Field);
15572 MemberLookup.resolveKind();
15573 MemberBuilder From(MoveOther, OtherRefType,
15574 /*IsArrow=*/false, MemberLookup);
15575 MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject,
15576 MemberLookup);
15577
15578 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15579 "Member reference with rvalue base must be rvalue except for reference "
15580 "members, which aren't allowed for move assignment.");
15581
15582 // Build the move of this field.
15583 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15584 To, From,
15585 /*CopyingBaseSubobject=*/false,
15586 /*Copying=*/false);
15587 if (Move.isInvalid()) {
15588 MoveAssignOperator->setInvalidDecl();
15589 return;
15590 }
15591
15592 // Success! Record the copy.
15593 Statements.push_back(Move.getAs<Stmt>());
15594 }
15595
15596 if (!Invalid) {
15597 // Add a "return *this;"
15598 Expr *ThisExpr =
15599 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15600 : static_cast<ExprBuilder &>(*DerefThis))
15601 .build(S&: *this, Loc);
15602
15603 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15604 if (Return.isInvalid())
15605 Invalid = true;
15606 else
15607 Statements.push_back(Elt: Return.getAs<Stmt>());
15608 }
15609
15610 if (Invalid) {
15611 MoveAssignOperator->setInvalidDecl();
15612 return;
15613 }
15614
15615 StmtResult Body;
15616 {
15617 CompoundScopeRAII CompoundScope(*this);
15618 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15619 /*isStmtExpr=*/false);
15620 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15621 }
15622 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15623 MoveAssignOperator->markUsed(Context);
15624
15625 if (ASTMutationListener *L = getASTMutationListener()) {
15626 L->CompletedImplicitDefinition(MoveAssignOperator);
15627 }
15628}
15629
15630CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15631 CXXRecordDecl *ClassDecl) {
15632 // C++ [class.copy]p4:
15633 // If the class definition does not explicitly declare a copy
15634 // constructor, one is declared implicitly.
15635 assert(ClassDecl->needsImplicitCopyConstructor());
15636
15637 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15638 if (DSM.isAlreadyBeingDeclared())
15639 return nullptr;
15640
15641 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15642 QualType ArgType = ClassType;
15643 ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
15644 NamedType: ArgType, OwnedTagDecl: nullptr);
15645 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15646 if (Const)
15647 ArgType = ArgType.withConst();
15648
15649 LangAS AS = getDefaultCXXMethodAddrSpace();
15650 if (AS != LangAS::Default)
15651 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15652
15653 ArgType = Context.getLValueReferenceType(T: ArgType);
15654
15655 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl,
15656 CSM: CXXCopyConstructor,
15657 ConstArg: Const);
15658
15659 DeclarationName Name
15660 = Context.DeclarationNames.getCXXConstructorName(
15661 Ty: Context.getCanonicalType(T: ClassType));
15662 SourceLocation ClassLoc = ClassDecl->getLocation();
15663 DeclarationNameInfo NameInfo(Name, ClassLoc);
15664
15665 // An implicitly-declared copy constructor is an inline public
15666 // member of its class.
15667 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15668 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
15669 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15670 /*isInline=*/true,
15671 /*isImplicitlyDeclared=*/true,
15672 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
15673 : ConstexprSpecKind::Unspecified);
15674 CopyConstructor->setAccess(AS_public);
15675 CopyConstructor->setDefaulted();
15676
15677 setupImplicitSpecialMemberType(SpecialMem: CopyConstructor, ResultTy: Context.VoidTy, Args: ArgType);
15678
15679 if (getLangOpts().CUDA)
15680 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15681 CopyConstructor,
15682 /* ConstRHS */ Const,
15683 /* Diagnose */ false);
15684
15685 // During template instantiation of special member functions we need a
15686 // reliable TypeSourceInfo for the parameter types in order to allow functions
15687 // to be substituted.
15688 TypeSourceInfo *TSI = nullptr;
15689 if (inTemplateInstantiation() && ClassDecl->isLambda())
15690 TSI = Context.getTrivialTypeSourceInfo(T: ArgType);
15691
15692 // Add the parameter to the constructor.
15693 ParmVarDecl *FromParam =
15694 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15695 /*IdentifierInfo=*/nullptr, ArgType,
15696 /*TInfo=*/TSI, SC_None, nullptr);
15697 CopyConstructor->setParams(FromParam);
15698
15699 CopyConstructor->setTrivial(
15700 ClassDecl->needsOverloadResolutionForCopyConstructor()
15701 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15702 : ClassDecl->hasTrivialCopyConstructor());
15703
15704 CopyConstructor->setTrivialForCall(
15705 ClassDecl->hasAttr<TrivialABIAttr>() ||
15706 (ClassDecl->needsOverloadResolutionForCopyConstructor()
15707 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15708 TAH_ConsiderTrivialABI)
15709 : ClassDecl->hasTrivialCopyConstructorForCall()));
15710
15711 // Note that we have declared this constructor.
15712 ++getASTContext().NumImplicitCopyConstructorsDeclared;
15713
15714 Scope *S = getScopeForContext(ClassDecl);
15715 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15716
15717 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15718 ClassDecl->setImplicitCopyConstructorIsDeleted();
15719 SetDeclDeleted(CopyConstructor, ClassLoc);
15720 }
15721
15722 if (S)
15723 PushOnScopeChains(CopyConstructor, S, false);
15724 ClassDecl->addDecl(CopyConstructor);
15725
15726 return CopyConstructor;
15727}
15728
15729void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15730 CXXConstructorDecl *CopyConstructor) {
15731 assert((CopyConstructor->isDefaulted() &&
15732 CopyConstructor->isCopyConstructor() &&
15733 !CopyConstructor->doesThisDeclarationHaveABody() &&
15734 !CopyConstructor->isDeleted()) &&
15735 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15736 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15737 return;
15738
15739 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15740 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15741
15742 SynthesizedFunctionScope Scope(*this, CopyConstructor);
15743
15744 // The exception specification is needed because we are defining the
15745 // function.
15746 ResolveExceptionSpec(Loc: CurrentLocation,
15747 FPT: CopyConstructor->getType()->castAs<FunctionProtoType>());
15748 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
15749
15750 // Add a context note for diagnostics produced after this point.
15751 Scope.addContextNote(UseLoc: CurrentLocation);
15752
15753 // C++11 [class.copy]p7:
15754 // The [definition of an implicitly declared copy constructor] is
15755 // deprecated if the class has a user-declared copy assignment operator
15756 // or a user-declared destructor.
15757 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15758 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15759
15760 if (SetCtorInitializers(Constructor: CopyConstructor, /*AnyErrors=*/false)) {
15761 CopyConstructor->setInvalidDecl();
15762 } else {
15763 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15764 ? CopyConstructor->getEndLoc()
15765 : CopyConstructor->getLocation();
15766 Sema::CompoundScopeRAII CompoundScope(*this);
15767 CopyConstructor->setBody(
15768 ActOnCompoundStmt(L: Loc, R: Loc, Elts: std::nullopt, /*isStmtExpr=*/false)
15769 .getAs<Stmt>());
15770 CopyConstructor->markUsed(Context);
15771 }
15772
15773 if (ASTMutationListener *L = getASTMutationListener()) {
15774 L->CompletedImplicitDefinition(CopyConstructor);
15775 }
15776}
15777
15778CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15779 CXXRecordDecl *ClassDecl) {
15780 assert(ClassDecl->needsImplicitMoveConstructor());
15781
15782 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15783 if (DSM.isAlreadyBeingDeclared())
15784 return nullptr;
15785
15786 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15787
15788 QualType ArgType = ClassType;
15789 ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr,
15790 NamedType: ArgType, OwnedTagDecl: nullptr);
15791 LangAS AS = getDefaultCXXMethodAddrSpace();
15792 if (AS != LangAS::Default)
15793 ArgType = Context.getAddrSpaceQualType(T: ClassType, AddressSpace: AS);
15794 ArgType = Context.getRValueReferenceType(T: ArgType);
15795
15796 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl,
15797 CSM: CXXMoveConstructor,
15798 ConstArg: false);
15799
15800 DeclarationName Name
15801 = Context.DeclarationNames.getCXXConstructorName(
15802 Ty: Context.getCanonicalType(T: ClassType));
15803 SourceLocation ClassLoc = ClassDecl->getLocation();
15804 DeclarationNameInfo NameInfo(Name, ClassLoc);
15805
15806 // C++11 [class.copy]p11:
15807 // An implicitly-declared copy/move constructor is an inline public
15808 // member of its class.
15809 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15810 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
15811 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15812 /*isInline=*/true,
15813 /*isImplicitlyDeclared=*/true,
15814 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
15815 : ConstexprSpecKind::Unspecified);
15816 MoveConstructor->setAccess(AS_public);
15817 MoveConstructor->setDefaulted();
15818
15819 setupImplicitSpecialMemberType(SpecialMem: MoveConstructor, ResultTy: Context.VoidTy, Args: ArgType);
15820
15821 if (getLangOpts().CUDA)
15822 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15823 MoveConstructor,
15824 /* ConstRHS */ false,
15825 /* Diagnose */ false);
15826
15827 // Add the parameter to the constructor.
15828 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15829 ClassLoc, ClassLoc,
15830 /*IdentifierInfo=*/nullptr,
15831 ArgType, /*TInfo=*/nullptr,
15832 SC_None, nullptr);
15833 MoveConstructor->setParams(FromParam);
15834
15835 MoveConstructor->setTrivial(
15836 ClassDecl->needsOverloadResolutionForMoveConstructor()
15837 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15838 : ClassDecl->hasTrivialMoveConstructor());
15839
15840 MoveConstructor->setTrivialForCall(
15841 ClassDecl->hasAttr<TrivialABIAttr>() ||
15842 (ClassDecl->needsOverloadResolutionForMoveConstructor()
15843 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15844 TAH_ConsiderTrivialABI)
15845 : ClassDecl->hasTrivialMoveConstructorForCall()));
15846
15847 // Note that we have declared this constructor.
15848 ++getASTContext().NumImplicitMoveConstructorsDeclared;
15849
15850 Scope *S = getScopeForContext(ClassDecl);
15851 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15852
15853 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15854 ClassDecl->setImplicitMoveConstructorIsDeleted();
15855 SetDeclDeleted(MoveConstructor, ClassLoc);
15856 }
15857
15858 if (S)
15859 PushOnScopeChains(MoveConstructor, S, false);
15860 ClassDecl->addDecl(MoveConstructor);
15861
15862 return MoveConstructor;
15863}
15864
15865void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15866 CXXConstructorDecl *MoveConstructor) {
15867 assert((MoveConstructor->isDefaulted() &&
15868 MoveConstructor->isMoveConstructor() &&
15869 !MoveConstructor->doesThisDeclarationHaveABody() &&
15870 !MoveConstructor->isDeleted()) &&
15871 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15872 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15873 return;
15874
15875 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15876 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15877
15878 SynthesizedFunctionScope Scope(*this, MoveConstructor);
15879
15880 // The exception specification is needed because we are defining the
15881 // function.
15882 ResolveExceptionSpec(Loc: CurrentLocation,
15883 FPT: MoveConstructor->getType()->castAs<FunctionProtoType>());
15884 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
15885
15886 // Add a context note for diagnostics produced after this point.
15887 Scope.addContextNote(UseLoc: CurrentLocation);
15888
15889 if (SetCtorInitializers(Constructor: MoveConstructor, /*AnyErrors=*/false)) {
15890 MoveConstructor->setInvalidDecl();
15891 } else {
15892 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15893 ? MoveConstructor->getEndLoc()
15894 : MoveConstructor->getLocation();
15895 Sema::CompoundScopeRAII CompoundScope(*this);
15896 MoveConstructor->setBody(
15897 ActOnCompoundStmt(L: Loc, R: Loc, Elts: std::nullopt, /*isStmtExpr=*/false)
15898 .getAs<Stmt>());
15899 MoveConstructor->markUsed(Context);
15900 }
15901
15902 if (ASTMutationListener *L = getASTMutationListener()) {
15903 L->CompletedImplicitDefinition(MoveConstructor);
15904 }
15905}
15906
15907bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15908 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD);
15909}
15910
15911void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15912 SourceLocation CurrentLocation,
15913 CXXConversionDecl *Conv) {
15914 SynthesizedFunctionScope Scope(*this, Conv);
15915 assert(!Conv->getReturnType()->isUndeducedType());
15916
15917 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15918 CallingConv CC =
15919 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15920
15921 CXXRecordDecl *Lambda = Conv->getParent();
15922 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15923 FunctionDecl *Invoker =
15924 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
15925 ? CallOp
15926 : Lambda->getLambdaStaticInvoker(CC);
15927
15928 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15929 CallOp = InstantiateFunctionDeclaration(
15930 FTD: CallOp->getDescribedFunctionTemplate(), Args: TemplateArgs, Loc: CurrentLocation);
15931 if (!CallOp)
15932 return;
15933
15934 if (CallOp != Invoker) {
15935 Invoker = InstantiateFunctionDeclaration(
15936 FTD: Invoker->getDescribedFunctionTemplate(), Args: TemplateArgs,
15937 Loc: CurrentLocation);
15938 if (!Invoker)
15939 return;
15940 }
15941 }
15942
15943 if (CallOp->isInvalidDecl())
15944 return;
15945
15946 // Mark the call operator referenced (and add to pending instantiations
15947 // if necessary).
15948 // For both the conversion and static-invoker template specializations
15949 // we construct their body's in this function, so no need to add them
15950 // to the PendingInstantiations.
15951 MarkFunctionReferenced(Loc: CurrentLocation, Func: CallOp);
15952
15953 if (Invoker != CallOp) {
15954 // Fill in the __invoke function with a dummy implementation. IR generation
15955 // will fill in the actual details. Update its type in case it contained
15956 // an 'auto'.
15957 Invoker->markUsed(Context);
15958 Invoker->setReferenced();
15959 Invoker->setType(Conv->getReturnType()->getPointeeType());
15960 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15961 }
15962
15963 // Construct the body of the conversion function { return __invoke; }.
15964 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15965 Conv->getLocation());
15966 assert(FunctionRef && "Can't refer to __invoke function?");
15967 Stmt *Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: FunctionRef).get();
15968 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: Return, FPFeatures: FPOptionsOverride(),
15969 LB: Conv->getLocation(), RB: Conv->getLocation()));
15970 Conv->markUsed(Context);
15971 Conv->setReferenced();
15972
15973 if (ASTMutationListener *L = getASTMutationListener()) {
15974 L->CompletedImplicitDefinition(Conv);
15975 if (Invoker != CallOp)
15976 L->CompletedImplicitDefinition(D: Invoker);
15977 }
15978}
15979
15980void Sema::DefineImplicitLambdaToBlockPointerConversion(
15981 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15982 assert(!Conv->getParent()->isGenericLambda());
15983
15984 SynthesizedFunctionScope Scope(*this, Conv);
15985
15986 // Copy-initialize the lambda object as needed to capture it.
15987 Expr *This = ActOnCXXThis(loc: CurrentLocation).get();
15988 Expr *DerefThis =CreateBuiltinUnaryOp(OpLoc: CurrentLocation, Opc: UO_Deref, InputExpr: This).get();
15989
15990 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15991 ConvLocation: Conv->getLocation(),
15992 Conv, Src: DerefThis);
15993
15994 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15995 // behavior. Note that only the general conversion function does this
15996 // (since it's unusable otherwise); in the case where we inline the
15997 // block literal, it has block literal lifetime semantics.
15998 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15999 BuildBlock = ImplicitCastExpr::Create(
16000 Context, T: BuildBlock.get()->getType(), Kind: CK_CopyAndAutoreleaseBlockObject,
16001 Operand: BuildBlock.get(), BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
16002
16003 if (BuildBlock.isInvalid()) {
16004 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16005 Conv->setInvalidDecl();
16006 return;
16007 }
16008
16009 // Create the return statement that returns the block from the conversion
16010 // function.
16011 StmtResult Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: BuildBlock.get());
16012 if (Return.isInvalid()) {
16013 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16014 Conv->setInvalidDecl();
16015 return;
16016 }
16017
16018 // Set the body of the conversion function.
16019 Stmt *ReturnS = Return.get();
16020 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: ReturnS, FPFeatures: FPOptionsOverride(),
16021 LB: Conv->getLocation(), RB: Conv->getLocation()));
16022 Conv->markUsed(Context);
16023
16024 // We're done; notify the mutation listener, if any.
16025 if (ASTMutationListener *L = getASTMutationListener()) {
16026 L->CompletedImplicitDefinition(Conv);
16027 }
16028}
16029
16030/// Determine whether the given list arguments contains exactly one
16031/// "real" (non-default) argument.
16032static bool hasOneRealArgument(MultiExprArg Args) {
16033 switch (Args.size()) {
16034 case 0:
16035 return false;
16036
16037 default:
16038 if (!Args[1]->isDefaultArgument())
16039 return false;
16040
16041 [[fallthrough]];
16042 case 1:
16043 return !Args[0]->isDefaultArgument();
16044 }
16045
16046 return false;
16047}
16048
16049ExprResult Sema::BuildCXXConstructExpr(
16050 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16051 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16052 bool HadMultipleCandidates, bool IsListInitialization,
16053 bool IsStdInitListInitialization, bool RequiresZeroInit,
16054 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16055 bool Elidable = false;
16056
16057 // C++0x [class.copy]p34:
16058 // When certain criteria are met, an implementation is allowed to
16059 // omit the copy/move construction of a class object, even if the
16060 // copy/move constructor and/or destructor for the object have
16061 // side effects. [...]
16062 // - when a temporary class object that has not been bound to a
16063 // reference (12.2) would be copied/moved to a class object
16064 // with the same cv-unqualified type, the copy/move operation
16065 // can be omitted by constructing the temporary object
16066 // directly into the target of the omitted copy/move
16067 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16068 // FIXME: Converting constructors should also be accepted.
16069 // But to fix this, the logic that digs down into a CXXConstructExpr
16070 // to find the source object needs to handle it.
16071 // Right now it assumes the source object is passed directly as the
16072 // first argument.
16073 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(Args: ExprArgs)) {
16074 Expr *SubExpr = ExprArgs[0];
16075 // FIXME: Per above, this is also incorrect if we want to accept
16076 // converting constructors, as isTemporaryObject will
16077 // reject temporaries with different type from the
16078 // CXXRecord itself.
16079 Elidable = SubExpr->isTemporaryObject(
16080 Ctx&: Context, TempTy: cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
16081 }
16082
16083 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16084 FoundDecl, Constructor,
16085 Elidable, Exprs: ExprArgs, HadMultipleCandidates,
16086 IsListInitialization,
16087 IsStdInitListInitialization, RequiresZeroInit,
16088 ConstructKind, ParenRange);
16089}
16090
16091ExprResult Sema::BuildCXXConstructExpr(
16092 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16093 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16094 bool HadMultipleCandidates, bool IsListInitialization,
16095 bool IsStdInitListInitialization, bool RequiresZeroInit,
16096 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16097 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl)) {
16098 Constructor = findInheritingConstructor(Loc: ConstructLoc, BaseCtor: Constructor, Shadow);
16099 // The only way to get here is if we did overlaod resolution to find the
16100 // shadow decl, so we don't need to worry about re-checking the trailing
16101 // requires clause.
16102 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16103 return ExprError();
16104 }
16105
16106 return BuildCXXConstructExpr(
16107 ConstructLoc, DeclInitType, Constructor, Elidable, Exprs: ExprArgs,
16108 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16109 RequiresZeroInit, ConstructKind, ParenRange);
16110}
16111
16112/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16113/// including handling of its default argument expressions.
16114ExprResult Sema::BuildCXXConstructExpr(
16115 SourceLocation ConstructLoc, QualType DeclInitType,
16116 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16117 bool HadMultipleCandidates, bool IsListInitialization,
16118 bool IsStdInitListInitialization, bool RequiresZeroInit,
16119 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16120 assert(declaresSameEntity(
16121 Constructor->getParent(),
16122 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16123 "given constructor for wrong type");
16124 MarkFunctionReferenced(ConstructLoc, Constructor);
16125 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
16126 return ExprError();
16127
16128 return CheckForImmediateInvocation(
16129 CXXConstructExpr::Create(
16130 Ctx: Context, Ty: DeclInitType, Loc: ConstructLoc, Ctor: Constructor, Elidable, Args: ExprArgs,
16131 HadMultipleCandidates, ListInitialization: IsListInitialization,
16132 StdInitListInitialization: IsStdInitListInitialization, ZeroInitialization: RequiresZeroInit,
16133 ConstructKind: static_cast<CXXConstructionKind>(ConstructKind), ParenOrBraceRange: ParenRange),
16134 Constructor);
16135}
16136
16137void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
16138 if (VD->isInvalidDecl()) return;
16139 // If initializing the variable failed, don't also diagnose problems with
16140 // the destructor, they're likely related.
16141 if (VD->getInit() && VD->getInit()->containsErrors())
16142 return;
16143
16144 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Record->getDecl());
16145 if (ClassDecl->isInvalidDecl()) return;
16146 if (ClassDecl->hasIrrelevantDestructor()) return;
16147 if (ClassDecl->isDependentContext()) return;
16148
16149 if (VD->isNoDestroy(getASTContext()))
16150 return;
16151
16152 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
16153 // The result of `LookupDestructor` might be nullptr if the destructor is
16154 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16155 // will not be selected by `CXXRecordDecl::getDestructor()`.
16156 if (!Destructor)
16157 return;
16158 // If this is an array, we'll require the destructor during initialization, so
16159 // we can skip over this. We still want to emit exit-time destructor warnings
16160 // though.
16161 if (!VD->getType()->isArrayType()) {
16162 MarkFunctionReferenced(Loc: VD->getLocation(), Func: Destructor);
16163 CheckDestructorAccess(VD->getLocation(), Destructor,
16164 PDiag(diag::err_access_dtor_var)
16165 << VD->getDeclName() << VD->getType());
16166 DiagnoseUseOfDecl(D: Destructor, Locs: VD->getLocation());
16167 }
16168
16169 if (Destructor->isTrivial()) return;
16170
16171 // If the destructor is constexpr, check whether the variable has constant
16172 // destruction now.
16173 if (Destructor->isConstexpr()) {
16174 bool HasConstantInit = false;
16175 if (VD->getInit() && !VD->getInit()->isValueDependent())
16176 HasConstantInit = VD->evaluateValue();
16177 SmallVector<PartialDiagnosticAt, 8> Notes;
16178 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16179 HasConstantInit) {
16180 Diag(VD->getLocation(),
16181 diag::err_constexpr_var_requires_const_destruction) << VD;
16182 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16183 Diag(Loc: Notes[I].first, PD: Notes[I].second);
16184 }
16185 }
16186
16187 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Ctx: Context))
16188 return;
16189
16190 // Emit warning for non-trivial dtor in global scope (a real global,
16191 // class-static, function-static).
16192 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16193
16194 // TODO: this should be re-enabled for static locals by !CXAAtExit
16195 if (!VD->isStaticLocal())
16196 Diag(VD->getLocation(), diag::warn_global_destructor);
16197}
16198
16199/// Given a constructor and the set of arguments provided for the
16200/// constructor, convert the arguments and add any required default arguments
16201/// to form a proper call to this constructor.
16202///
16203/// \returns true if an error occurred, false otherwise.
16204bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16205 QualType DeclInitType, MultiExprArg ArgsPtr,
16206 SourceLocation Loc,
16207 SmallVectorImpl<Expr *> &ConvertedArgs,
16208 bool AllowExplicit,
16209 bool IsListInitialization) {
16210 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16211 unsigned NumArgs = ArgsPtr.size();
16212 Expr **Args = ArgsPtr.data();
16213
16214 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16215 unsigned NumParams = Proto->getNumParams();
16216
16217 // If too few arguments are available, we'll fill in the rest with defaults.
16218 if (NumArgs < NumParams)
16219 ConvertedArgs.reserve(N: NumParams);
16220 else
16221 ConvertedArgs.reserve(N: NumArgs);
16222
16223 VariadicCallType CallType =
16224 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16225 SmallVector<Expr *, 8> AllArgs;
16226 bool Invalid = GatherArgumentsForCall(
16227 CallLoc: Loc, FDecl: Constructor, Proto: Proto, FirstParam: 0, Args: llvm::ArrayRef(Args, NumArgs), AllArgs,
16228 CallType, AllowExplicit, IsListInitialization);
16229 ConvertedArgs.append(in_start: AllArgs.begin(), in_end: AllArgs.end());
16230
16231 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16232
16233 CheckConstructorCall(FDecl: Constructor, ThisType: DeclInitType,
16234 Args: llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto: Proto,
16235 Loc);
16236
16237 return Invalid;
16238}
16239
16240static inline bool
16241CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16242 const FunctionDecl *FnDecl) {
16243 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16244 if (isa<NamespaceDecl>(Val: DC)) {
16245 return SemaRef.Diag(FnDecl->getLocation(),
16246 diag::err_operator_new_delete_declared_in_namespace)
16247 << FnDecl->getDeclName();
16248 }
16249
16250 if (isa<TranslationUnitDecl>(Val: DC) &&
16251 FnDecl->getStorageClass() == SC_Static) {
16252 return SemaRef.Diag(FnDecl->getLocation(),
16253 diag::err_operator_new_delete_declared_static)
16254 << FnDecl->getDeclName();
16255 }
16256
16257 return false;
16258}
16259
16260static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16261 const PointerType *PtrTy) {
16262 auto &Ctx = SemaRef.Context;
16263 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16264 PtrQuals.removeAddressSpace();
16265 return Ctx.getPointerType(T: Ctx.getCanonicalType(T: Ctx.getQualifiedType(
16266 T: PtrTy->getPointeeType().getUnqualifiedType(), Qs: PtrQuals)));
16267}
16268
16269static inline bool
16270CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
16271 CanQualType ExpectedResultType,
16272 CanQualType ExpectedFirstParamType,
16273 unsigned DependentParamTypeDiag,
16274 unsigned InvalidParamTypeDiag) {
16275 QualType ResultType =
16276 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16277
16278 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16279 // The operator is valid on any address space for OpenCL.
16280 // Drop address space from actual and expected result types.
16281 if (const auto *PtrTy = ResultType->getAs<PointerType>())
16282 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16283
16284 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16285 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16286 }
16287
16288 // Check that the result type is what we expect.
16289 if (SemaRef.Context.getCanonicalType(T: ResultType) != ExpectedResultType) {
16290 // Reject even if the type is dependent; an operator delete function is
16291 // required to have a non-dependent result type.
16292 return SemaRef.Diag(
16293 FnDecl->getLocation(),
16294 ResultType->isDependentType()
16295 ? diag::err_operator_new_delete_dependent_result_type
16296 : diag::err_operator_new_delete_invalid_result_type)
16297 << FnDecl->getDeclName() << ExpectedResultType;
16298 }
16299
16300 // A function template must have at least 2 parameters.
16301 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16302 return SemaRef.Diag(FnDecl->getLocation(),
16303 diag::err_operator_new_delete_template_too_few_parameters)
16304 << FnDecl->getDeclName();
16305
16306 // The function decl must have at least 1 parameter.
16307 if (FnDecl->getNumParams() == 0)
16308 return SemaRef.Diag(FnDecl->getLocation(),
16309 diag::err_operator_new_delete_too_few_parameters)
16310 << FnDecl->getDeclName();
16311
16312 QualType FirstParamType = FnDecl->getParamDecl(i: 0)->getType();
16313 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16314 // The operator is valid on any address space for OpenCL.
16315 // Drop address space from actual and expected first parameter types.
16316 if (const auto *PtrTy =
16317 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16318 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16319
16320 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16321 ExpectedFirstParamType =
16322 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16323 }
16324
16325 // Check that the first parameter type is what we expect.
16326 if (SemaRef.Context.getCanonicalType(T: FirstParamType).getUnqualifiedType() !=
16327 ExpectedFirstParamType) {
16328 // The first parameter type is not allowed to be dependent. As a tentative
16329 // DR resolution, we allow a dependent parameter type if it is the right
16330 // type anyway, to allow destroying operator delete in class templates.
16331 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16332 ? DependentParamTypeDiag
16333 : InvalidParamTypeDiag)
16334 << FnDecl->getDeclName() << ExpectedFirstParamType;
16335 }
16336
16337 return false;
16338}
16339
16340static bool
16341CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
16342 // C++ [basic.stc.dynamic.allocation]p1:
16343 // A program is ill-formed if an allocation function is declared in a
16344 // namespace scope other than global scope or declared static in global
16345 // scope.
16346 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16347 return true;
16348
16349 CanQualType SizeTy =
16350 SemaRef.Context.getCanonicalType(T: SemaRef.Context.getSizeType());
16351
16352 // C++ [basic.stc.dynamic.allocation]p1:
16353 // The return type shall be void*. The first parameter shall have type
16354 // std::size_t.
16355 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
16356 SizeTy,
16357 diag::err_operator_new_dependent_param_type,
16358 diag::err_operator_new_param_type))
16359 return true;
16360
16361 // C++ [basic.stc.dynamic.allocation]p1:
16362 // The first parameter shall not have an associated default argument.
16363 if (FnDecl->getParamDecl(0)->hasDefaultArg())
16364 return SemaRef.Diag(FnDecl->getLocation(),
16365 diag::err_operator_new_default_arg)
16366 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16367
16368 return false;
16369}
16370
16371static bool
16372CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16373 // C++ [basic.stc.dynamic.deallocation]p1:
16374 // A program is ill-formed if deallocation functions are declared in a
16375 // namespace scope other than global scope or declared static in global
16376 // scope.
16377 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16378 return true;
16379
16380 auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl);
16381
16382 // C++ P0722:
16383 // Within a class C, the first parameter of a destroying operator delete
16384 // shall be of type C *. The first parameter of any other deallocation
16385 // function shall be of type void *.
16386 CanQualType ExpectedFirstParamType =
16387 MD && MD->isDestroyingOperatorDelete()
16388 ? SemaRef.Context.getCanonicalType(T: SemaRef.Context.getPointerType(
16389 T: SemaRef.Context.getRecordType(MD->getParent())))
16390 : SemaRef.Context.VoidPtrTy;
16391
16392 // C++ [basic.stc.dynamic.deallocation]p2:
16393 // Each deallocation function shall return void
16394 if (CheckOperatorNewDeleteTypes(
16395 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16396 diag::err_operator_delete_dependent_param_type,
16397 diag::err_operator_delete_param_type))
16398 return true;
16399
16400 // C++ P0722:
16401 // A destroying operator delete shall be a usual deallocation function.
16402 if (MD && !MD->getParent()->isDependentContext() &&
16403 MD->isDestroyingOperatorDelete() &&
16404 !SemaRef.isUsualDeallocationFunction(FD: MD)) {
16405 SemaRef.Diag(MD->getLocation(),
16406 diag::err_destroying_operator_delete_not_usual);
16407 return true;
16408 }
16409
16410 return false;
16411}
16412
16413/// CheckOverloadedOperatorDeclaration - Check whether the declaration
16414/// of this overloaded operator is well-formed. If so, returns false;
16415/// otherwise, emits appropriate diagnostics and returns true.
16416bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16417 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16418 "Expected an overloaded operator declaration");
16419
16420 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16421
16422 // C++ [over.oper]p5:
16423 // The allocation and deallocation functions, operator new,
16424 // operator new[], operator delete and operator delete[], are
16425 // described completely in 3.7.3. The attributes and restrictions
16426 // found in the rest of this subclause do not apply to them unless
16427 // explicitly stated in 3.7.3.
16428 if (Op == OO_Delete || Op == OO_Array_Delete)
16429 return CheckOperatorDeleteDeclaration(SemaRef&: *this, FnDecl);
16430
16431 if (Op == OO_New || Op == OO_Array_New)
16432 return CheckOperatorNewDeclaration(SemaRef&: *this, FnDecl);
16433
16434 // C++ [over.oper]p7:
16435 // An operator function shall either be a member function or
16436 // be a non-member function and have at least one parameter
16437 // whose type is a class, a reference to a class, an enumeration,
16438 // or a reference to an enumeration.
16439 // Note: Before C++23, a member function could not be static. The only member
16440 // function allowed to be static is the call operator function.
16441 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
16442 if (MethodDecl->isStatic()) {
16443 if (Op == OO_Call || Op == OO_Subscript)
16444 Diag(FnDecl->getLocation(),
16445 (LangOpts.CPlusPlus23
16446 ? diag::warn_cxx20_compat_operator_overload_static
16447 : diag::ext_operator_overload_static))
16448 << FnDecl;
16449 else
16450 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16451 << FnDecl;
16452 }
16453 } else {
16454 bool ClassOrEnumParam = false;
16455 for (auto *Param : FnDecl->parameters()) {
16456 QualType ParamType = Param->getType().getNonReferenceType();
16457 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16458 ParamType->isEnumeralType()) {
16459 ClassOrEnumParam = true;
16460 break;
16461 }
16462 }
16463
16464 if (!ClassOrEnumParam)
16465 return Diag(FnDecl->getLocation(),
16466 diag::err_operator_overload_needs_class_or_enum)
16467 << FnDecl->getDeclName();
16468 }
16469
16470 // C++ [over.oper]p8:
16471 // An operator function cannot have default arguments (8.3.6),
16472 // except where explicitly stated below.
16473 //
16474 // Only the function-call operator (C++ [over.call]p1) and the subscript
16475 // operator (CWG2507) allow default arguments.
16476 if (Op != OO_Call) {
16477 ParmVarDecl *FirstDefaultedParam = nullptr;
16478 for (auto *Param : FnDecl->parameters()) {
16479 if (Param->hasDefaultArg()) {
16480 FirstDefaultedParam = Param;
16481 break;
16482 }
16483 }
16484 if (FirstDefaultedParam) {
16485 if (Op == OO_Subscript) {
16486 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16487 ? diag::ext_subscript_overload
16488 : diag::error_subscript_overload)
16489 << FnDecl->getDeclName() << 1
16490 << FirstDefaultedParam->getDefaultArgRange();
16491 } else {
16492 return Diag(FirstDefaultedParam->getLocation(),
16493 diag::err_operator_overload_default_arg)
16494 << FnDecl->getDeclName()
16495 << FirstDefaultedParam->getDefaultArgRange();
16496 }
16497 }
16498 }
16499
16500 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16501 { false, false, false }
16502#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16503 , { Unary, Binary, MemberOnly }
16504#include "clang/Basic/OperatorKinds.def"
16505 };
16506
16507 bool CanBeUnaryOperator = OperatorUses[Op][0];
16508 bool CanBeBinaryOperator = OperatorUses[Op][1];
16509 bool MustBeMemberOperator = OperatorUses[Op][2];
16510
16511 // C++ [over.oper]p8:
16512 // [...] Operator functions cannot have more or fewer parameters
16513 // than the number required for the corresponding operator, as
16514 // described in the rest of this subclause.
16515 unsigned NumParams = FnDecl->getNumParams() +
16516 (isa<CXXMethodDecl>(Val: FnDecl) &&
16517 !FnDecl->hasCXXExplicitFunctionObjectParameter()
16518 ? 1
16519 : 0);
16520 if (Op != OO_Call && Op != OO_Subscript &&
16521 ((NumParams == 1 && !CanBeUnaryOperator) ||
16522 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16523 (NumParams > 2))) {
16524 // We have the wrong number of parameters.
16525 unsigned ErrorKind;
16526 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16527 ErrorKind = 2; // 2 -> unary or binary.
16528 } else if (CanBeUnaryOperator) {
16529 ErrorKind = 0; // 0 -> unary
16530 } else {
16531 assert(CanBeBinaryOperator &&
16532 "All non-call overloaded operators are unary or binary!");
16533 ErrorKind = 1; // 1 -> binary
16534 }
16535 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16536 << FnDecl->getDeclName() << NumParams << ErrorKind;
16537 }
16538
16539 if (Op == OO_Subscript && NumParams != 2) {
16540 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16541 ? diag::ext_subscript_overload
16542 : diag::error_subscript_overload)
16543 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16544 }
16545
16546 // Overloaded operators other than operator() and operator[] cannot be
16547 // variadic.
16548 if (Op != OO_Call &&
16549 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16550 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16551 << FnDecl->getDeclName();
16552 }
16553
16554 // Some operators must be member functions.
16555 if (MustBeMemberOperator && !isa<CXXMethodDecl>(Val: FnDecl)) {
16556 return Diag(FnDecl->getLocation(),
16557 diag::err_operator_overload_must_be_member)
16558 << FnDecl->getDeclName();
16559 }
16560
16561 // C++ [over.inc]p1:
16562 // The user-defined function called operator++ implements the
16563 // prefix and postfix ++ operator. If this function is a member
16564 // function with no parameters, or a non-member function with one
16565 // parameter of class or enumeration type, it defines the prefix
16566 // increment operator ++ for objects of that type. If the function
16567 // is a member function with one parameter (which shall be of type
16568 // int) or a non-member function with two parameters (the second
16569 // of which shall be of type int), it defines the postfix
16570 // increment operator ++ for objects of that type.
16571 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16572 ParmVarDecl *LastParam = FnDecl->getParamDecl(i: FnDecl->getNumParams() - 1);
16573 QualType ParamType = LastParam->getType();
16574
16575 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16576 !ParamType->isDependentType())
16577 return Diag(LastParam->getLocation(),
16578 diag::err_operator_overload_post_incdec_must_be_int)
16579 << LastParam->getType() << (Op == OO_MinusMinus);
16580 }
16581
16582 return false;
16583}
16584
16585static bool
16586checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16587 FunctionTemplateDecl *TpDecl) {
16588 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16589
16590 // Must have one or two template parameters.
16591 if (TemplateParams->size() == 1) {
16592 NonTypeTemplateParmDecl *PmDecl =
16593 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 0));
16594
16595 // The template parameter must be a char parameter pack.
16596 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16597 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16598 return false;
16599
16600 // C++20 [over.literal]p5:
16601 // A string literal operator template is a literal operator template
16602 // whose template-parameter-list comprises a single non-type
16603 // template-parameter of class type.
16604 //
16605 // As a DR resolution, we also allow placeholders for deduced class
16606 // template specializations.
16607 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16608 !PmDecl->isTemplateParameterPack() &&
16609 (PmDecl->getType()->isRecordType() ||
16610 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16611 return false;
16612 } else if (TemplateParams->size() == 2) {
16613 TemplateTypeParmDecl *PmType =
16614 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: 0));
16615 NonTypeTemplateParmDecl *PmArgs =
16616 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 1));
16617
16618 // The second template parameter must be a parameter pack with the
16619 // first template parameter as its type.
16620 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16621 PmArgs->isTemplateParameterPack()) {
16622 const TemplateTypeParmType *TArgs =
16623 PmArgs->getType()->getAs<TemplateTypeParmType>();
16624 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16625 TArgs->getIndex() == PmType->getIndex()) {
16626 if (!SemaRef.inTemplateInstantiation())
16627 SemaRef.Diag(TpDecl->getLocation(),
16628 diag::ext_string_literal_operator_template);
16629 return false;
16630 }
16631 }
16632 }
16633
16634 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16635 diag::err_literal_operator_template)
16636 << TpDecl->getTemplateParameters()->getSourceRange();
16637 return true;
16638}
16639
16640/// CheckLiteralOperatorDeclaration - Check whether the declaration
16641/// of this literal operator function is well-formed. If so, returns
16642/// false; otherwise, emits appropriate diagnostics and returns true.
16643bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16644 if (isa<CXXMethodDecl>(Val: FnDecl)) {
16645 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16646 << FnDecl->getDeclName();
16647 return true;
16648 }
16649
16650 if (FnDecl->isExternC()) {
16651 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16652 if (const LinkageSpecDecl *LSD =
16653 FnDecl->getDeclContext()->getExternCContext())
16654 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16655 return true;
16656 }
16657
16658 // This might be the definition of a literal operator template.
16659 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16660
16661 // This might be a specialization of a literal operator template.
16662 if (!TpDecl)
16663 TpDecl = FnDecl->getPrimaryTemplate();
16664
16665 // template <char...> type operator "" name() and
16666 // template <class T, T...> type operator "" name() are the only valid
16667 // template signatures, and the only valid signatures with no parameters.
16668 //
16669 // C++20 also allows template <SomeClass T> type operator "" name().
16670 if (TpDecl) {
16671 if (FnDecl->param_size() != 0) {
16672 Diag(FnDecl->getLocation(),
16673 diag::err_literal_operator_template_with_params);
16674 return true;
16675 }
16676
16677 if (checkLiteralOperatorTemplateParameterList(SemaRef&: *this, TpDecl))
16678 return true;
16679
16680 } else if (FnDecl->param_size() == 1) {
16681 const ParmVarDecl *Param = FnDecl->getParamDecl(i: 0);
16682
16683 QualType ParamType = Param->getType().getUnqualifiedType();
16684
16685 // Only unsigned long long int, long double, any character type, and const
16686 // char * are allowed as the only parameters.
16687 if (ParamType->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
16688 ParamType->isSpecificBuiltinType(K: BuiltinType::LongDouble) ||
16689 Context.hasSameType(ParamType, Context.CharTy) ||
16690 Context.hasSameType(ParamType, Context.WideCharTy) ||
16691 Context.hasSameType(ParamType, Context.Char8Ty) ||
16692 Context.hasSameType(ParamType, Context.Char16Ty) ||
16693 Context.hasSameType(ParamType, Context.Char32Ty)) {
16694 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16695 QualType InnerType = Ptr->getPointeeType();
16696
16697 // Pointer parameter must be a const char *.
16698 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16699 Context.CharTy) &&
16700 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16701 Diag(Param->getSourceRange().getBegin(),
16702 diag::err_literal_operator_param)
16703 << ParamType << "'const char *'" << Param->getSourceRange();
16704 return true;
16705 }
16706
16707 } else if (ParamType->isRealFloatingType()) {
16708 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16709 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16710 return true;
16711
16712 } else if (ParamType->isIntegerType()) {
16713 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16714 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16715 return true;
16716
16717 } else {
16718 Diag(Param->getSourceRange().getBegin(),
16719 diag::err_literal_operator_invalid_param)
16720 << ParamType << Param->getSourceRange();
16721 return true;
16722 }
16723
16724 } else if (FnDecl->param_size() == 2) {
16725 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16726
16727 // First, verify that the first parameter is correct.
16728
16729 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16730
16731 // Two parameter function must have a pointer to const as a
16732 // first parameter; let's strip those qualifiers.
16733 const PointerType *PT = FirstParamType->getAs<PointerType>();
16734
16735 if (!PT) {
16736 Diag((*Param)->getSourceRange().getBegin(),
16737 diag::err_literal_operator_param)
16738 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16739 return true;
16740 }
16741
16742 QualType PointeeType = PT->getPointeeType();
16743 // First parameter must be const
16744 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16745 Diag((*Param)->getSourceRange().getBegin(),
16746 diag::err_literal_operator_param)
16747 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16748 return true;
16749 }
16750
16751 QualType InnerType = PointeeType.getUnqualifiedType();
16752 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16753 // const char32_t* are allowed as the first parameter to a two-parameter
16754 // function
16755 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16756 Context.hasSameType(InnerType, Context.WideCharTy) ||
16757 Context.hasSameType(InnerType, Context.Char8Ty) ||
16758 Context.hasSameType(InnerType, Context.Char16Ty) ||
16759 Context.hasSameType(InnerType, Context.Char32Ty))) {
16760 Diag((*Param)->getSourceRange().getBegin(),
16761 diag::err_literal_operator_param)
16762 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16763 return true;
16764 }
16765
16766 // Move on to the second and final parameter.
16767 ++Param;
16768
16769 // The second parameter must be a std::size_t.
16770 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16771 if (!Context.hasSameType(T1: SecondParamType, T2: Context.getSizeType())) {
16772 Diag((*Param)->getSourceRange().getBegin(),
16773 diag::err_literal_operator_param)
16774 << SecondParamType << Context.getSizeType()
16775 << (*Param)->getSourceRange();
16776 return true;
16777 }
16778 } else {
16779 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16780 return true;
16781 }
16782
16783 // Parameters are good.
16784
16785 // A parameter-declaration-clause containing a default argument is not
16786 // equivalent to any of the permitted forms.
16787 for (auto *Param : FnDecl->parameters()) {
16788 if (Param->hasDefaultArg()) {
16789 Diag(Param->getDefaultArgRange().getBegin(),
16790 diag::err_literal_operator_default_argument)
16791 << Param->getDefaultArgRange();
16792 break;
16793 }
16794 }
16795
16796 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16797 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
16798 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
16799 !getSourceManager().isInSystemHeader(Loc: FnDecl->getLocation())) {
16800 // C++23 [usrlit.suffix]p1:
16801 // Literal suffix identifiers that do not start with an underscore are
16802 // reserved for future standardization. Literal suffix identifiers that
16803 // contain a double underscore __ are reserved for use by C++
16804 // implementations.
16805 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16806 << static_cast<int>(Status)
16807 << StringLiteralParser::isValidUDSuffix(getLangOpts(), II->getName());
16808 }
16809
16810 return false;
16811}
16812
16813/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16814/// linkage specification, including the language and (if present)
16815/// the '{'. ExternLoc is the location of the 'extern', Lang is the
16816/// language string literal. LBraceLoc, if valid, provides the location of
16817/// the '{' brace. Otherwise, this linkage specification does not
16818/// have any braces.
16819Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16820 Expr *LangStr,
16821 SourceLocation LBraceLoc) {
16822 StringLiteral *Lit = cast<StringLiteral>(Val: LangStr);
16823 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16824
16825 StringRef Lang = Lit->getString();
16826 LinkageSpecLanguageIDs Language;
16827 if (Lang == "C")
16828 Language = LinkageSpecLanguageIDs::C;
16829 else if (Lang == "C++")
16830 Language = LinkageSpecLanguageIDs::CXX;
16831 else {
16832 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16833 << LangStr->getSourceRange();
16834 return nullptr;
16835 }
16836
16837 // FIXME: Add all the various semantics of linkage specifications
16838
16839 LinkageSpecDecl *D = LinkageSpecDecl::Create(C&: Context, DC: CurContext, ExternLoc,
16840 LangLoc: LangStr->getExprLoc(), Lang: Language,
16841 HasBraces: LBraceLoc.isValid());
16842
16843 /// C++ [module.unit]p7.2.3
16844 /// - Otherwise, if the declaration
16845 /// - ...
16846 /// - ...
16847 /// - appears within a linkage-specification,
16848 /// it is attached to the global module.
16849 ///
16850 /// If the declaration is already in global module fragment, we don't
16851 /// need to attach it again.
16852 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16853 Module *GlobalModule = PushImplicitGlobalModuleFragment(BeginLoc: ExternLoc);
16854 D->setLocalOwningModule(GlobalModule);
16855 }
16856
16857 CurContext->addDecl(D);
16858 PushDeclContext(S, D);
16859 return D;
16860}
16861
16862/// ActOnFinishLinkageSpecification - Complete the definition of
16863/// the C++ linkage specification LinkageSpec. If RBraceLoc is
16864/// valid, it's the position of the closing '}' brace in a linkage
16865/// specification that uses braces.
16866Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16867 Decl *LinkageSpec,
16868 SourceLocation RBraceLoc) {
16869 if (RBraceLoc.isValid()) {
16870 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(Val: LinkageSpec);
16871 LSDecl->setRBraceLoc(RBraceLoc);
16872 }
16873
16874 // If the current module doesn't has Parent, it implies that the
16875 // LinkageSpec isn't in the module created by itself. So we don't
16876 // need to pop it.
16877 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16878 getCurrentModule()->isImplicitGlobalModule() &&
16879 getCurrentModule()->Parent)
16880 PopImplicitGlobalModuleFragment();
16881
16882 PopDeclContext();
16883 return LinkageSpec;
16884}
16885
16886Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16887 const ParsedAttributesView &AttrList,
16888 SourceLocation SemiLoc) {
16889 Decl *ED = EmptyDecl::Create(C&: Context, DC: CurContext, L: SemiLoc);
16890 // Attribute declarations appertain to empty declaration so we handle
16891 // them here.
16892 ProcessDeclAttributeList(S, D: ED, AttrList);
16893
16894 CurContext->addDecl(D: ED);
16895 return ED;
16896}
16897
16898/// Perform semantic analysis for the variable declaration that
16899/// occurs within a C++ catch clause, returning the newly-created
16900/// variable.
16901VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16902 TypeSourceInfo *TInfo,
16903 SourceLocation StartLoc,
16904 SourceLocation Loc,
16905 IdentifierInfo *Name) {
16906 bool Invalid = false;
16907 QualType ExDeclType = TInfo->getType();
16908
16909 // Arrays and functions decay.
16910 if (ExDeclType->isArrayType())
16911 ExDeclType = Context.getArrayDecayedType(T: ExDeclType);
16912 else if (ExDeclType->isFunctionType())
16913 ExDeclType = Context.getPointerType(T: ExDeclType);
16914
16915 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16916 // The exception-declaration shall not denote a pointer or reference to an
16917 // incomplete type, other than [cv] void*.
16918 // N2844 forbids rvalue references.
16919 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16920 Diag(Loc, diag::err_catch_rvalue_ref);
16921 Invalid = true;
16922 }
16923
16924 if (ExDeclType->isVariablyModifiedType()) {
16925 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16926 Invalid = true;
16927 }
16928
16929 QualType BaseType = ExDeclType;
16930 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16931 unsigned DK = diag::err_catch_incomplete;
16932 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16933 BaseType = Ptr->getPointeeType();
16934 Mode = 1;
16935 DK = diag::err_catch_incomplete_ptr;
16936 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16937 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16938 BaseType = Ref->getPointeeType();
16939 Mode = 2;
16940 DK = diag::err_catch_incomplete_ref;
16941 }
16942 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16943 !BaseType->isDependentType() && RequireCompleteType(Loc, T: BaseType, DiagID: DK))
16944 Invalid = true;
16945
16946 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16947 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16948 Invalid = true;
16949 }
16950
16951 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16952 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16953 Invalid = true;
16954 }
16955
16956 if (!Invalid && !ExDeclType->isDependentType() &&
16957 RequireNonAbstractType(Loc, ExDeclType,
16958 diag::err_abstract_type_in_decl,
16959 AbstractVariableType))
16960 Invalid = true;
16961
16962 // Only the non-fragile NeXT runtime currently supports C++ catches
16963 // of ObjC types, and no runtime supports catching ObjC types by value.
16964 if (!Invalid && getLangOpts().ObjC) {
16965 QualType T = ExDeclType;
16966 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16967 T = RT->getPointeeType();
16968
16969 if (T->isObjCObjectType()) {
16970 Diag(Loc, diag::err_objc_object_catch);
16971 Invalid = true;
16972 } else if (T->isObjCObjectPointerType()) {
16973 // FIXME: should this be a test for macosx-fragile specifically?
16974 if (getLangOpts().ObjCRuntime.isFragile())
16975 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16976 }
16977 }
16978
16979 VarDecl *ExDecl = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: Loc, Id: Name,
16980 T: ExDeclType, TInfo, S: SC_None);
16981 ExDecl->setExceptionVariable(true);
16982
16983 // In ARC, infer 'retaining' for variables of retainable type.
16984 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16985 Invalid = true;
16986
16987 if (!Invalid && !ExDeclType->isDependentType()) {
16988 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16989 // Insulate this from anything else we might currently be parsing.
16990 EnterExpressionEvaluationContext scope(
16991 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16992
16993 // C++ [except.handle]p16:
16994 // The object declared in an exception-declaration or, if the
16995 // exception-declaration does not specify a name, a temporary (12.2) is
16996 // copy-initialized (8.5) from the exception object. [...]
16997 // The object is destroyed when the handler exits, after the destruction
16998 // of any automatic objects initialized within the handler.
16999 //
17000 // We just pretend to initialize the object with itself, then make sure
17001 // it can be destroyed later.
17002 QualType initType = Context.getExceptionObjectType(T: ExDeclType);
17003
17004 InitializedEntity entity =
17005 InitializedEntity::InitializeVariable(Var: ExDecl);
17006 InitializationKind initKind =
17007 InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation());
17008
17009 Expr *opaqueValue =
17010 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17011 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17012 ExprResult result = sequence.Perform(S&: *this, Entity: entity, Kind: initKind, Args: opaqueValue);
17013 if (result.isInvalid())
17014 Invalid = true;
17015 else {
17016 // If the constructor used was non-trivial, set this as the
17017 // "initializer".
17018 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17019 if (!construct->getConstructor()->isTrivial()) {
17020 Expr *init = MaybeCreateExprWithCleanups(construct);
17021 ExDecl->setInit(init);
17022 }
17023
17024 // And make sure it's destructable.
17025 FinalizeVarWithDestructor(VD: ExDecl, Record: recordType);
17026 }
17027 }
17028 }
17029
17030 if (Invalid)
17031 ExDecl->setInvalidDecl();
17032
17033 return ExDecl;
17034}
17035
17036/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
17037/// handler.
17038Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17039 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17040 bool Invalid = D.isInvalidType();
17041
17042 // Check for unexpanded parameter packs.
17043 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
17044 UPPC: UPPC_ExceptionType)) {
17045 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
17046 Loc: D.getIdentifierLoc());
17047 Invalid = true;
17048 }
17049
17050 IdentifierInfo *II = D.getIdentifier();
17051 if (NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: D.getIdentifierLoc(),
17052 NameKind: LookupOrdinaryName,
17053 Redecl: ForVisibleRedeclaration)) {
17054 // The scope should be freshly made just for us. There is just no way
17055 // it contains any previous declaration, except for function parameters in
17056 // a function-try-block's catch statement.
17057 assert(!S->isDeclScope(PrevDecl));
17058 if (isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
17059 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17060 << D.getIdentifier();
17061 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17062 Invalid = true;
17063 } else if (PrevDecl->isTemplateParameter())
17064 // Maybe we will complain about the shadowed template parameter.
17065 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17066 }
17067
17068 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17069 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17070 << D.getCXXScopeSpec().getRange();
17071 Invalid = true;
17072 }
17073
17074 VarDecl *ExDecl = BuildExceptionDeclaration(
17075 S, TInfo, StartLoc: D.getBeginLoc(), Loc: D.getIdentifierLoc(), Name: D.getIdentifier());
17076 if (Invalid)
17077 ExDecl->setInvalidDecl();
17078
17079 // Add the exception declaration into this scope.
17080 if (II)
17081 PushOnScopeChains(ExDecl, S);
17082 else
17083 CurContext->addDecl(ExDecl);
17084
17085 ProcessDeclAttributes(S, ExDecl, D);
17086 return ExDecl;
17087}
17088
17089Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17090 Expr *AssertExpr,
17091 Expr *AssertMessageExpr,
17092 SourceLocation RParenLoc) {
17093 if (DiagnoseUnexpandedParameterPack(E: AssertExpr, UPPC: UPPC_StaticAssertExpression))
17094 return nullptr;
17095
17096 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17097 AssertMessageExpr, RParenLoc, Failed: false);
17098}
17099
17100static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17101 switch (BTK) {
17102 case BuiltinType::Char_S:
17103 case BuiltinType::Char_U:
17104 break;
17105 case BuiltinType::Char8:
17106 OS << "u8";
17107 break;
17108 case BuiltinType::Char16:
17109 OS << 'u';
17110 break;
17111 case BuiltinType::Char32:
17112 OS << 'U';
17113 break;
17114 case BuiltinType::WChar_S:
17115 case BuiltinType::WChar_U:
17116 OS << 'L';
17117 break;
17118 default:
17119 llvm_unreachable("Non-character type");
17120 }
17121}
17122
17123/// Convert character's value, interpreted as a code unit, to a string.
17124/// The value needs to be zero-extended to 32-bits.
17125/// FIXME: This assumes Unicode literal encodings
17126static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17127 unsigned TyWidth,
17128 SmallVectorImpl<char> &Str) {
17129 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17130 char *Ptr = Arr;
17131 BuiltinType::Kind K = BTy->getKind();
17132 llvm::raw_svector_ostream OS(Str);
17133
17134 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17135 // other types.
17136 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17137 K == BuiltinType::Char8 || Value <= 0x7F) {
17138 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Value);
17139 if (!Escaped.empty())
17140 EscapeStringForDiagnostic(Str: Escaped, OutStr&: Str);
17141 else
17142 OS << static_cast<char>(Value);
17143 return;
17144 }
17145
17146 switch (K) {
17147 case BuiltinType::Char16:
17148 case BuiltinType::Char32:
17149 case BuiltinType::WChar_S:
17150 case BuiltinType::WChar_U: {
17151 if (llvm::ConvertCodePointToUTF8(Source: Value, ResultPtr&: Ptr))
17152 EscapeStringForDiagnostic(Str: StringRef(Arr, Ptr - Arr), OutStr&: Str);
17153 else
17154 OS << "\\x"
17155 << llvm::format_hex_no_prefix(N: Value, Width: TyWidth / 4, /*Upper=*/true);
17156 break;
17157 }
17158 default:
17159 llvm_unreachable("Non-character type is passed");
17160 }
17161}
17162
17163/// Convert \V to a string we can present to the user in a diagnostic
17164/// \T is the type of the expression that has been evaluated into \V
17165static bool ConvertAPValueToString(const APValue &V, QualType T,
17166 SmallVectorImpl<char> &Str,
17167 ASTContext &Context) {
17168 if (!V.hasValue())
17169 return false;
17170
17171 switch (V.getKind()) {
17172 case APValue::ValueKind::Int:
17173 if (T->isBooleanType()) {
17174 // Bools are reduced to ints during evaluation, but for
17175 // diagnostic purposes we want to print them as
17176 // true or false.
17177 int64_t BoolValue = V.getInt().getExtValue();
17178 assert((BoolValue == 0 || BoolValue == 1) &&
17179 "Bool type, but value is not 0 or 1");
17180 llvm::raw_svector_ostream OS(Str);
17181 OS << (BoolValue ? "true" : "false");
17182 } else {
17183 llvm::raw_svector_ostream OS(Str);
17184 // Same is true for chars.
17185 // We want to print the character representation for textual types
17186 const auto *BTy = T->getAs<BuiltinType>();
17187 if (BTy) {
17188 switch (BTy->getKind()) {
17189 case BuiltinType::Char_S:
17190 case BuiltinType::Char_U:
17191 case BuiltinType::Char8:
17192 case BuiltinType::Char16:
17193 case BuiltinType::Char32:
17194 case BuiltinType::WChar_S:
17195 case BuiltinType::WChar_U: {
17196 unsigned TyWidth = Context.getIntWidth(T);
17197 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17198 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17199 WriteCharTypePrefix(BTK: BTy->getKind(), OS);
17200 OS << '\'';
17201 WriteCharValueForDiagnostic(Value: CodeUnit, BTy, TyWidth, Str);
17202 OS << "' (0x"
17203 << llvm::format_hex_no_prefix(N: CodeUnit, /*Width=*/2,
17204 /*Upper=*/true)
17205 << ", " << V.getInt() << ')';
17206 return true;
17207 }
17208 default:
17209 break;
17210 }
17211 }
17212 V.getInt().toString(Str);
17213 }
17214
17215 break;
17216
17217 case APValue::ValueKind::Float:
17218 V.getFloat().toString(Str);
17219 break;
17220
17221 case APValue::ValueKind::LValue:
17222 if (V.isNullPointer()) {
17223 llvm::raw_svector_ostream OS(Str);
17224 OS << "nullptr";
17225 } else
17226 return false;
17227 break;
17228
17229 case APValue::ValueKind::ComplexFloat: {
17230 llvm::raw_svector_ostream OS(Str);
17231 OS << '(';
17232 V.getComplexFloatReal().toString(Str);
17233 OS << " + ";
17234 V.getComplexFloatImag().toString(Str);
17235 OS << "i)";
17236 } break;
17237
17238 case APValue::ValueKind::ComplexInt: {
17239 llvm::raw_svector_ostream OS(Str);
17240 OS << '(';
17241 V.getComplexIntReal().toString(Str);
17242 OS << " + ";
17243 V.getComplexIntImag().toString(Str);
17244 OS << "i)";
17245 } break;
17246
17247 default:
17248 return false;
17249 }
17250
17251 return true;
17252}
17253
17254/// Some Expression types are not useful to print notes about,
17255/// e.g. literals and values that have already been expanded
17256/// before such as int-valued template parameters.
17257static bool UsefulToPrintExpr(const Expr *E) {
17258 E = E->IgnoreParenImpCasts();
17259 // Literals are pretty easy for humans to understand.
17260 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17261 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(Val: E))
17262 return false;
17263
17264 // These have been substituted from template parameters
17265 // and appear as literals in the static assert error.
17266 if (isa<SubstNonTypeTemplateParmExpr>(Val: E))
17267 return false;
17268
17269 // -5 is also simple to understand.
17270 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E))
17271 return UsefulToPrintExpr(E: UnaryOp->getSubExpr());
17272
17273 // Only print nested arithmetic operators.
17274 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E))
17275 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17276 BO->isBitwiseOp());
17277
17278 return true;
17279}
17280
17281/// Try to print more useful information about a failed static_assert
17282/// with expression \E
17283void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17284 if (const auto *Op = dyn_cast<BinaryOperator>(Val: E);
17285 Op && Op->getOpcode() != BO_LOr) {
17286 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17287 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17288
17289 // Ignore comparisons of boolean expressions with a boolean literal.
17290 if ((isa<CXXBoolLiteralExpr>(Val: LHS) && RHS->getType()->isBooleanType()) ||
17291 (isa<CXXBoolLiteralExpr>(Val: RHS) && LHS->getType()->isBooleanType()))
17292 return;
17293
17294 // Don't print obvious expressions.
17295 if (!UsefulToPrintExpr(E: LHS) && !UsefulToPrintExpr(E: RHS))
17296 return;
17297
17298 struct {
17299 const clang::Expr *Cond;
17300 Expr::EvalResult Result;
17301 SmallString<12> ValueString;
17302 bool Print;
17303 } DiagSide[2] = {{.Cond: LHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false},
17304 {.Cond: RHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}};
17305 for (unsigned I = 0; I < 2; I++) {
17306 const Expr *Side = DiagSide[I].Cond;
17307
17308 Side->EvaluateAsRValue(Result&: DiagSide[I].Result, Ctx: Context, InConstantContext: true);
17309
17310 DiagSide[I].Print =
17311 ConvertAPValueToString(V: DiagSide[I].Result.Val, T: Side->getType(),
17312 Str&: DiagSide[I].ValueString, Context);
17313 }
17314 if (DiagSide[0].Print && DiagSide[1].Print) {
17315 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17316 << DiagSide[0].ValueString << Op->getOpcodeStr()
17317 << DiagSide[1].ValueString << Op->getSourceRange();
17318 }
17319 }
17320}
17321
17322bool Sema::EvaluateStaticAssertMessageAsString(Expr *Message,
17323 std::string &Result,
17324 ASTContext &Ctx,
17325 bool ErrorOnInvalidMessage) {
17326 assert(Message);
17327 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17328 "can't evaluate a dependant static assert message");
17329
17330 if (const auto *SL = dyn_cast<StringLiteral>(Val: Message)) {
17331 assert(SL->isUnevaluated() && "expected an unevaluated string");
17332 Result.assign(first: SL->getString().begin(), last: SL->getString().end());
17333 return true;
17334 }
17335
17336 SourceLocation Loc = Message->getBeginLoc();
17337 QualType T = Message->getType().getNonReferenceType();
17338 auto *RD = T->getAsCXXRecordDecl();
17339 if (!RD) {
17340 Diag(Loc, diag::err_static_assert_invalid_message);
17341 return false;
17342 }
17343
17344 auto FindMember = [&](StringRef Member, bool &Empty,
17345 bool Diag = false) -> std::optional<LookupResult> {
17346 DeclarationName DN = PP.getIdentifierInfo(Name: Member);
17347 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17348 LookupQualifiedName(MemberLookup, RD);
17349 Empty = MemberLookup.empty();
17350 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17351 OverloadCandidateSet::CSK_Normal);
17352 if (MemberLookup.empty())
17353 return std::nullopt;
17354 return std::move(MemberLookup);
17355 };
17356
17357 bool SizeNotFound, DataNotFound;
17358 std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17359 std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17360 if (SizeNotFound || DataNotFound) {
17361 Diag(Loc, diag::err_static_assert_missing_member_function)
17362 << ((SizeNotFound && DataNotFound) ? 2
17363 : SizeNotFound ? 0
17364 : 1);
17365 return false;
17366 }
17367
17368 if (!SizeMember || !DataMember) {
17369 if (!SizeMember)
17370 FindMember("size", SizeNotFound, /*Diag=*/true);
17371 if (!DataMember)
17372 FindMember("data", DataNotFound, /*Diag=*/true);
17373 return false;
17374 }
17375
17376 auto BuildExpr = [&](LookupResult &LR) {
17377 ExprResult Res = BuildMemberReferenceExpr(
17378 Message, Message->getType(), Message->getBeginLoc(), false,
17379 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17380 if (Res.isInvalid())
17381 return ExprError();
17382 Res = BuildCallExpr(S: nullptr, Fn: Res.get(), LParenLoc: Loc, ArgExprs: std::nullopt, RParenLoc: Loc, ExecConfig: nullptr,
17383 IsExecConfig: false, AllowRecovery: true);
17384 if (Res.isInvalid())
17385 return ExprError();
17386 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17387 return ExprError();
17388 return TemporaryMaterializationConversion(Res.get());
17389 };
17390
17391 ExprResult SizeE = BuildExpr(*SizeMember);
17392 ExprResult DataE = BuildExpr(*DataMember);
17393
17394 QualType SizeT = Context.getSizeType();
17395 QualType ConstCharPtr =
17396 Context.getPointerType(Context.getConstType(T: Context.CharTy));
17397
17398 ExprResult EvaluatedSize =
17399 SizeE.isInvalid() ? ExprError()
17400 : BuildConvertedConstantExpression(
17401 From: SizeE.get(), T: SizeT, CCE: CCEK_StaticAssertMessageSize);
17402 if (EvaluatedSize.isInvalid()) {
17403 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17404 return false;
17405 }
17406
17407 ExprResult EvaluatedData =
17408 DataE.isInvalid()
17409 ? ExprError()
17410 : BuildConvertedConstantExpression(From: DataE.get(), T: ConstCharPtr,
17411 CCE: CCEK_StaticAssertMessageData);
17412 if (EvaluatedData.isInvalid()) {
17413 Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17414 return false;
17415 }
17416
17417 if (!ErrorOnInvalidMessage &&
17418 Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17419 return true;
17420
17421 Expr::EvalResult Status;
17422 SmallVector<PartialDiagnosticAt, 8> Notes;
17423 Status.Diag = &Notes;
17424 if (!Message->EvaluateCharRangeAsString(Result, SizeExpression: EvaluatedSize.get(),
17425 PtrExpression: EvaluatedData.get(), Ctx, Status) ||
17426 !Notes.empty()) {
17427 Diag(Message->getBeginLoc(),
17428 ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17429 : diag::warn_static_assert_message_constexpr);
17430 for (const auto &Note : Notes)
17431 Diag(Loc: Note.first, PD: Note.second);
17432 return !ErrorOnInvalidMessage;
17433 }
17434 return true;
17435}
17436
17437Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17438 Expr *AssertExpr, Expr *AssertMessage,
17439 SourceLocation RParenLoc,
17440 bool Failed) {
17441 assert(AssertExpr != nullptr && "Expected non-null condition");
17442 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17443 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17444 !AssertMessage->isValueDependent())) &&
17445 !Failed) {
17446 // In a static_assert-declaration, the constant-expression shall be a
17447 // constant expression that can be contextually converted to bool.
17448 ExprResult Converted = PerformContextuallyConvertToBool(From: AssertExpr);
17449 if (Converted.isInvalid())
17450 Failed = true;
17451
17452 ExprResult FullAssertExpr =
17453 ActOnFinishFullExpr(Expr: Converted.get(), CC: StaticAssertLoc,
17454 /*DiscardedValue*/ false,
17455 /*IsConstexpr*/ true);
17456 if (FullAssertExpr.isInvalid())
17457 Failed = true;
17458 else
17459 AssertExpr = FullAssertExpr.get();
17460
17461 llvm::APSInt Cond;
17462 Expr *BaseExpr = AssertExpr;
17463 AllowFoldKind FoldKind = NoFold;
17464
17465 if (!getLangOpts().CPlusPlus) {
17466 // In C mode, allow folding as an extension for better compatibility with
17467 // C++ in terms of expressions like static_assert("test") or
17468 // static_assert(nullptr).
17469 FoldKind = AllowFold;
17470 }
17471
17472 if (!Failed && VerifyIntegerConstantExpression(
17473 BaseExpr, &Cond,
17474 diag::err_static_assert_expression_is_not_constant,
17475 FoldKind).isInvalid())
17476 Failed = true;
17477
17478 // If the static_assert passes, only verify that
17479 // the message is grammatically valid without evaluating it.
17480 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17481 std::string Str;
17482 EvaluateStaticAssertMessageAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
17483 /*ErrorOnInvalidMessage=*/false);
17484 }
17485
17486 // CWG2518
17487 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17488 // template definition, the declaration has no effect.
17489 bool InTemplateDefinition =
17490 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17491
17492 if (!Failed && !Cond && !InTemplateDefinition) {
17493 SmallString<256> MsgBuffer;
17494 llvm::raw_svector_ostream Msg(MsgBuffer);
17495 bool HasMessage = AssertMessage;
17496 if (AssertMessage) {
17497 std::string Str;
17498 HasMessage =
17499 EvaluateStaticAssertMessageAsString(
17500 Message: AssertMessage, Result&: Str, Ctx&: Context, /*ErrorOnInvalidMessage=*/true) ||
17501 !Str.empty();
17502 Msg << Str;
17503 }
17504 Expr *InnerCond = nullptr;
17505 std::string InnerCondDescription;
17506 std::tie(args&: InnerCond, args&: InnerCondDescription) =
17507 findFailedBooleanCondition(Cond: Converted.get());
17508 if (InnerCond && isa<ConceptSpecializationExpr>(Val: InnerCond)) {
17509 // Drill down into concept specialization expressions to see why they
17510 // weren't satisfied.
17511 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17512 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17513 ConstraintSatisfaction Satisfaction;
17514 if (!CheckConstraintSatisfaction(ConstraintExpr: InnerCond, Satisfaction))
17515 DiagnoseUnsatisfiedConstraint(Satisfaction);
17516 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(Val: InnerCond)
17517 && !isa<IntegerLiteral>(Val: InnerCond)) {
17518 Diag(InnerCond->getBeginLoc(),
17519 diag::err_static_assert_requirement_failed)
17520 << InnerCondDescription << !HasMessage << Msg.str()
17521 << InnerCond->getSourceRange();
17522 DiagnoseStaticAssertDetails(E: InnerCond);
17523 } else {
17524 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17525 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17526 PrintContextStack();
17527 }
17528 Failed = true;
17529 }
17530 } else {
17531 ExprResult FullAssertExpr = ActOnFinishFullExpr(Expr: AssertExpr, CC: StaticAssertLoc,
17532 /*DiscardedValue*/false,
17533 /*IsConstexpr*/true);
17534 if (FullAssertExpr.isInvalid())
17535 Failed = true;
17536 else
17537 AssertExpr = FullAssertExpr.get();
17538 }
17539
17540 Decl *Decl = StaticAssertDecl::Create(C&: Context, DC: CurContext, StaticAssertLoc,
17541 AssertExpr, Message: AssertMessage, RParenLoc,
17542 Failed);
17543
17544 CurContext->addDecl(D: Decl);
17545 return Decl;
17546}
17547
17548/// Handle a friend tag declaration where the scope specifier was
17549/// templated.
17550DeclResult Sema::ActOnTemplatedFriendTag(
17551 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17552 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17553 const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
17554 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17555
17556 bool IsMemberSpecialization = false;
17557 bool Invalid = false;
17558
17559 if (TemplateParameterList *TemplateParams =
17560 MatchTemplateParametersToScopeSpecifier(
17561 DeclStartLoc: TagLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TempParamLists, /*friend*/ IsFriend: true,
17562 IsMemberSpecialization, Invalid)) {
17563 if (TemplateParams->size() > 0) {
17564 // This is a declaration of a class template.
17565 if (Invalid)
17566 return true;
17567
17568 return CheckClassTemplate(S, TagSpec, TUK: TUK_Friend, KWLoc: TagLoc, SS, Name,
17569 NameLoc, Attr, TemplateParams, AS: AS_public,
17570 /*ModulePrivateLoc=*/SourceLocation(),
17571 FriendLoc, NumOuterTemplateParamLists: TempParamLists.size() - 1,
17572 OuterTemplateParamLists: TempParamLists.data()).get();
17573 } else {
17574 // The "template<>" header is extraneous.
17575 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17576 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17577 IsMemberSpecialization = true;
17578 }
17579 }
17580
17581 if (Invalid) return true;
17582
17583 bool isAllExplicitSpecializations = true;
17584 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17585 if (TempParamLists[I]->size()) {
17586 isAllExplicitSpecializations = false;
17587 break;
17588 }
17589 }
17590
17591 // FIXME: don't ignore attributes.
17592
17593 // If it's explicit specializations all the way down, just forget
17594 // about the template header and build an appropriate non-templated
17595 // friend. TODO: for source fidelity, remember the headers.
17596 if (isAllExplicitSpecializations) {
17597 if (SS.isEmpty()) {
17598 bool Owned = false;
17599 bool IsDependent = false;
17600 return ActOnTag(S, TagSpec, TUK: TUK_Friend, KWLoc: TagLoc, SS, Name, NameLoc, Attr,
17601 AS: AS_public,
17602 /*ModulePrivateLoc=*/SourceLocation(),
17603 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent,
17604 /*ScopedEnumKWLoc=*/SourceLocation(),
17605 /*ScopedEnumUsesClassTag=*/false,
17606 /*UnderlyingType=*/TypeResult(),
17607 /*IsTypeSpecifier=*/false,
17608 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17609 }
17610
17611 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
17612 ElaboratedTypeKeyword Keyword
17613 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
17614 QualType T = CheckTypenameType(Keyword, KeywordLoc: TagLoc, QualifierLoc,
17615 II: *Name, IILoc: NameLoc);
17616 if (T.isNull())
17617 return true;
17618
17619 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17620 if (isa<DependentNameType>(Val: T)) {
17621 DependentNameTypeLoc TL =
17622 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17623 TL.setElaboratedKeywordLoc(TagLoc);
17624 TL.setQualifierLoc(QualifierLoc);
17625 TL.setNameLoc(NameLoc);
17626 } else {
17627 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
17628 TL.setElaboratedKeywordLoc(TagLoc);
17629 TL.setQualifierLoc(QualifierLoc);
17630 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17631 }
17632
17633 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc,
17634 Friend_: TSI, FriendL: FriendLoc, FriendTypeTPLists: TempParamLists);
17635 Friend->setAccess(AS_public);
17636 CurContext->addDecl(Friend);
17637 return Friend;
17638 }
17639
17640 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17641
17642
17643
17644 // Handle the case of a templated-scope friend class. e.g.
17645 // template <class T> class A<T>::B;
17646 // FIXME: we don't support these right now.
17647 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17648 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17649 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
17650 QualType T = Context.getDependentNameType(Keyword: ETK, NNS: SS.getScopeRep(), Name);
17651 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17652 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17653 TL.setElaboratedKeywordLoc(TagLoc);
17654 TL.setQualifierLoc(SS.getWithLocInContext(Context));
17655 TL.setNameLoc(NameLoc);
17656
17657 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc,
17658 Friend_: TSI, FriendL: FriendLoc, FriendTypeTPLists: TempParamLists);
17659 Friend->setAccess(AS_public);
17660 Friend->setUnsupportedFriend(true);
17661 CurContext->addDecl(Friend);
17662 return Friend;
17663}
17664
17665/// Handle a friend type declaration. This works in tandem with
17666/// ActOnTag.
17667///
17668/// Notes on friend class templates:
17669///
17670/// We generally treat friend class declarations as if they were
17671/// declaring a class. So, for example, the elaborated type specifier
17672/// in a friend declaration is required to obey the restrictions of a
17673/// class-head (i.e. no typedefs in the scope chain), template
17674/// parameters are required to match up with simple template-ids, &c.
17675/// However, unlike when declaring a template specialization, it's
17676/// okay to refer to a template specialization without an empty
17677/// template parameter declaration, e.g.
17678/// friend class A<T>::B<unsigned>;
17679/// We permit this as a special case; if there are any template
17680/// parameters present at all, require proper matching, i.e.
17681/// template <> template \<class T> friend class A<int>::B;
17682Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
17683 MultiTemplateParamsArg TempParams) {
17684 SourceLocation Loc = DS.getBeginLoc();
17685 SourceLocation FriendLoc = DS.getFriendSpecLoc();
17686
17687 assert(DS.isFriendSpecified());
17688 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17689
17690 // C++ [class.friend]p3:
17691 // A friend declaration that does not declare a function shall have one of
17692 // the following forms:
17693 // friend elaborated-type-specifier ;
17694 // friend simple-type-specifier ;
17695 // friend typename-specifier ;
17696 //
17697 // If the friend keyword isn't first, or if the declarations has any type
17698 // qualifiers, then the declaration doesn't have that form.
17699 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
17700 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
17701 if (DS.getTypeQualifiers()) {
17702 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
17703 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17704 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
17705 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17706 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
17707 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17708 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
17709 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17710 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
17711 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17712 }
17713
17714 // Try to convert the decl specifier to a type. This works for
17715 // friend templates because ActOnTag never produces a ClassTemplateDecl
17716 // for a TUK_Friend.
17717 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17718 DeclaratorContext::Member);
17719 TypeSourceInfo *TSI = GetTypeForDeclarator(D&: TheDeclarator);
17720 QualType T = TSI->getType();
17721 if (TheDeclarator.isInvalidType())
17722 return nullptr;
17723
17724 if (DiagnoseUnexpandedParameterPack(Loc, T: TSI, UPPC: UPPC_FriendDeclaration))
17725 return nullptr;
17726
17727 if (!T->isElaboratedTypeSpecifier()) {
17728 if (TempParams.size()) {
17729 // C++23 [dcl.pre]p5:
17730 // In a simple-declaration, the optional init-declarator-list can be
17731 // omitted only when declaring a class or enumeration, that is, when
17732 // the decl-specifier-seq contains either a class-specifier, an
17733 // elaborated-type-specifier with a class-key, or an enum-specifier.
17734 //
17735 // The declaration of a template-declaration or explicit-specialization
17736 // is never a member-declaration, so this must be a simple-declaration
17737 // with no init-declarator-list. Therefore, this is ill-formed.
17738 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
17739 return nullptr;
17740 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
17741 SmallString<16> InsertionText(" ");
17742 InsertionText += RD->getKindName();
17743
17744 Diag(Loc, getLangOpts().CPlusPlus11
17745 ? diag::warn_cxx98_compat_unelaborated_friend_type
17746 : diag::ext_unelaborated_friend_type)
17747 << (unsigned)RD->getTagKind() << T
17748 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
17749 InsertionText);
17750 } else {
17751 Diag(FriendLoc, getLangOpts().CPlusPlus11
17752 ? diag::warn_cxx98_compat_nonclass_type_friend
17753 : diag::ext_nonclass_type_friend)
17754 << T << DS.getSourceRange();
17755 }
17756 }
17757
17758 // C++98 [class.friend]p1: A friend of a class is a function
17759 // or class that is not a member of the class . . .
17760 // This is fixed in DR77, which just barely didn't make the C++03
17761 // deadline. It's also a very silly restriction that seriously
17762 // affects inner classes and which nobody else seems to implement;
17763 // thus we never diagnose it, not even in -pedantic.
17764 //
17765 // But note that we could warn about it: it's always useless to
17766 // friend one of your own members (it's not, however, worthless to
17767 // friend a member of an arbitrary specialization of your template).
17768
17769 Decl *D;
17770 if (!TempParams.empty())
17771 D = FriendTemplateDecl::Create(Context, DC: CurContext, Loc, Params: TempParams, Friend: TSI,
17772 FriendLoc);
17773 else
17774 D = FriendDecl::Create(C&: Context, DC: CurContext, L: TSI->getTypeLoc().getBeginLoc(),
17775 Friend_: TSI, FriendL: FriendLoc);
17776
17777 if (!D)
17778 return nullptr;
17779
17780 D->setAccess(AS_public);
17781 CurContext->addDecl(D);
17782
17783 return D;
17784}
17785
17786NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
17787 MultiTemplateParamsArg TemplateParams) {
17788 const DeclSpec &DS = D.getDeclSpec();
17789
17790 assert(DS.isFriendSpecified());
17791 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17792
17793 SourceLocation Loc = D.getIdentifierLoc();
17794 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17795
17796 // C++ [class.friend]p1
17797 // A friend of a class is a function or class....
17798 // Note that this sees through typedefs, which is intended.
17799 // It *doesn't* see through dependent types, which is correct
17800 // according to [temp.arg.type]p3:
17801 // If a declaration acquires a function type through a
17802 // type dependent on a template-parameter and this causes
17803 // a declaration that does not use the syntactic form of a
17804 // function declarator to have a function type, the program
17805 // is ill-formed.
17806 if (!TInfo->getType()->isFunctionType()) {
17807 Diag(Loc, diag::err_unexpected_friend);
17808
17809 // It might be worthwhile to try to recover by creating an
17810 // appropriate declaration.
17811 return nullptr;
17812 }
17813
17814 // C++ [namespace.memdef]p3
17815 // - If a friend declaration in a non-local class first declares a
17816 // class or function, the friend class or function is a member
17817 // of the innermost enclosing namespace.
17818 // - The name of the friend is not found by simple name lookup
17819 // until a matching declaration is provided in that namespace
17820 // scope (either before or after the class declaration granting
17821 // friendship).
17822 // - If a friend function is called, its name may be found by the
17823 // name lookup that considers functions from namespaces and
17824 // classes associated with the types of the function arguments.
17825 // - When looking for a prior declaration of a class or a function
17826 // declared as a friend, scopes outside the innermost enclosing
17827 // namespace scope are not considered.
17828
17829 CXXScopeSpec &SS = D.getCXXScopeSpec();
17830 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
17831 assert(NameInfo.getName());
17832
17833 // Check for unexpanded parameter packs.
17834 if (DiagnoseUnexpandedParameterPack(Loc, T: TInfo, UPPC: UPPC_FriendDeclaration) ||
17835 DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_FriendDeclaration) ||
17836 DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_FriendDeclaration))
17837 return nullptr;
17838
17839 // The context we found the declaration in, or in which we should
17840 // create the declaration.
17841 DeclContext *DC;
17842 Scope *DCScope = S;
17843 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17844 ForExternalRedeclaration);
17845
17846 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17847
17848 // There are five cases here.
17849 // - There's no scope specifier and we're in a local class. Only look
17850 // for functions declared in the immediately-enclosing block scope.
17851 // We recover from invalid scope qualifiers as if they just weren't there.
17852 FunctionDecl *FunctionContainingLocalClass = nullptr;
17853 if ((SS.isInvalid() || !SS.isSet()) &&
17854 (FunctionContainingLocalClass =
17855 cast<CXXRecordDecl>(Val: CurContext)->isLocalClass())) {
17856 // C++11 [class.friend]p11:
17857 // If a friend declaration appears in a local class and the name
17858 // specified is an unqualified name, a prior declaration is
17859 // looked up without considering scopes that are outside the
17860 // innermost enclosing non-class scope. For a friend function
17861 // declaration, if there is no prior declaration, the program is
17862 // ill-formed.
17863
17864 // Find the innermost enclosing non-class scope. This is the block
17865 // scope containing the local class definition (or for a nested class,
17866 // the outer local class).
17867 DCScope = S->getFnParent();
17868
17869 // Look up the function name in the scope.
17870 Previous.clear(Kind: LookupLocalFriendName);
17871 LookupName(R&: Previous, S, /*AllowBuiltinCreation*/false);
17872
17873 if (!Previous.empty()) {
17874 // All possible previous declarations must have the same context:
17875 // either they were declared at block scope or they are members of
17876 // one of the enclosing local classes.
17877 DC = Previous.getRepresentativeDecl()->getDeclContext();
17878 } else {
17879 // This is ill-formed, but provide the context that we would have
17880 // declared the function in, if we were permitted to, for error recovery.
17881 DC = FunctionContainingLocalClass;
17882 }
17883 adjustContextForLocalExternDecl(DC);
17884
17885 // - There's no scope specifier, in which case we just go to the
17886 // appropriate scope and look for a function or function template
17887 // there as appropriate.
17888 } else if (SS.isInvalid() || !SS.isSet()) {
17889 // C++11 [namespace.memdef]p3:
17890 // If the name in a friend declaration is neither qualified nor
17891 // a template-id and the declaration is a function or an
17892 // elaborated-type-specifier, the lookup to determine whether
17893 // the entity has been previously declared shall not consider
17894 // any scopes outside the innermost enclosing namespace.
17895
17896 // Find the appropriate context according to the above.
17897 DC = CurContext;
17898
17899 // Skip class contexts. If someone can cite chapter and verse
17900 // for this behavior, that would be nice --- it's what GCC and
17901 // EDG do, and it seems like a reasonable intent, but the spec
17902 // really only says that checks for unqualified existing
17903 // declarations should stop at the nearest enclosing namespace,
17904 // not that they should only consider the nearest enclosing
17905 // namespace.
17906 while (DC->isRecord())
17907 DC = DC->getParent();
17908
17909 DeclContext *LookupDC = DC->getNonTransparentContext();
17910 while (true) {
17911 LookupQualifiedName(R&: Previous, LookupCtx: LookupDC);
17912
17913 if (!Previous.empty()) {
17914 DC = LookupDC;
17915 break;
17916 }
17917
17918 if (isTemplateId) {
17919 if (isa<TranslationUnitDecl>(Val: LookupDC)) break;
17920 } else {
17921 if (LookupDC->isFileContext()) break;
17922 }
17923 LookupDC = LookupDC->getParent();
17924 }
17925
17926 DCScope = getScopeForDeclContext(S, DC);
17927
17928 // - There's a non-dependent scope specifier, in which case we
17929 // compute it and do a previous lookup there for a function
17930 // or function template.
17931 } else if (!SS.getScopeRep()->isDependent()) {
17932 DC = computeDeclContext(SS);
17933 if (!DC) return nullptr;
17934
17935 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17936
17937 LookupQualifiedName(R&: Previous, LookupCtx: DC);
17938
17939 // C++ [class.friend]p1: A friend of a class is a function or
17940 // class that is not a member of the class . . .
17941 if (DC->Equals(CurContext))
17942 Diag(DS.getFriendSpecLoc(),
17943 getLangOpts().CPlusPlus11 ?
17944 diag::warn_cxx98_compat_friend_is_member :
17945 diag::err_friend_is_member);
17946
17947 // - There's a scope specifier that does not match any template
17948 // parameter lists, in which case we use some arbitrary context,
17949 // create a method or method template, and wait for instantiation.
17950 // - There's a scope specifier that does match some template
17951 // parameter lists, which we don't handle right now.
17952 } else {
17953 DC = CurContext;
17954 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17955 }
17956
17957 if (!DC->isRecord()) {
17958 int DiagArg = -1;
17959 switch (D.getName().getKind()) {
17960 case UnqualifiedIdKind::IK_ConstructorTemplateId:
17961 case UnqualifiedIdKind::IK_ConstructorName:
17962 DiagArg = 0;
17963 break;
17964 case UnqualifiedIdKind::IK_DestructorName:
17965 DiagArg = 1;
17966 break;
17967 case UnqualifiedIdKind::IK_ConversionFunctionId:
17968 DiagArg = 2;
17969 break;
17970 case UnqualifiedIdKind::IK_DeductionGuideName:
17971 DiagArg = 3;
17972 break;
17973 case UnqualifiedIdKind::IK_Identifier:
17974 case UnqualifiedIdKind::IK_ImplicitSelfParam:
17975 case UnqualifiedIdKind::IK_LiteralOperatorId:
17976 case UnqualifiedIdKind::IK_OperatorFunctionId:
17977 case UnqualifiedIdKind::IK_TemplateId:
17978 break;
17979 }
17980 // This implies that it has to be an operator or function.
17981 if (DiagArg >= 0) {
17982 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17983 return nullptr;
17984 }
17985 }
17986
17987 // FIXME: This is an egregious hack to cope with cases where the scope stack
17988 // does not contain the declaration context, i.e., in an out-of-line
17989 // definition of a class.
17990 Scope FakeDCScope(S, Scope::DeclScope, Diags);
17991 if (!DCScope) {
17992 FakeDCScope.setEntity(DC);
17993 DCScope = &FakeDCScope;
17994 }
17995
17996 bool AddToScope = true;
17997 NamedDecl *ND = ActOnFunctionDeclarator(S: DCScope, D, DC, TInfo, Previous,
17998 TemplateParamLists: TemplateParams, AddToScope);
17999 if (!ND) return nullptr;
18000
18001 assert(ND->getLexicalDeclContext() == CurContext);
18002
18003 // If we performed typo correction, we might have added a scope specifier
18004 // and changed the decl context.
18005 DC = ND->getDeclContext();
18006
18007 // Add the function declaration to the appropriate lookup tables,
18008 // adjusting the redeclarations list as necessary. We don't
18009 // want to do this yet if the friending class is dependent.
18010 //
18011 // Also update the scope-based lookup if the target context's
18012 // lookup context is in lexical scope.
18013 if (!CurContext->isDependentContext()) {
18014 DC = DC->getRedeclContext();
18015 DC->makeDeclVisibleInContext(D: ND);
18016 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18017 PushOnScopeChains(D: ND, S: EnclosingScope, /*AddToContext=*/ false);
18018 }
18019
18020 FriendDecl *FrD = FriendDecl::Create(C&: Context, DC: CurContext,
18021 L: D.getIdentifierLoc(), Friend_: ND,
18022 FriendL: DS.getFriendSpecLoc());
18023 FrD->setAccess(AS_public);
18024 CurContext->addDecl(FrD);
18025
18026 if (ND->isInvalidDecl()) {
18027 FrD->setInvalidDecl();
18028 } else {
18029 if (DC->isRecord()) CheckFriendAccess(D: ND);
18030
18031 FunctionDecl *FD;
18032 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: ND))
18033 FD = FTD->getTemplatedDecl();
18034 else
18035 FD = cast<FunctionDecl>(Val: ND);
18036
18037 // C++ [class.friend]p6:
18038 // A function may be defined in a friend declaration of a class if and
18039 // only if the class is a non-local class, and the function name is
18040 // unqualified.
18041 if (D.isFunctionDefinition()) {
18042 // Qualified friend function definition.
18043 if (SS.isNotEmpty()) {
18044 // FIXME: We should only do this if the scope specifier names the
18045 // innermost enclosing namespace; otherwise the fixit changes the
18046 // meaning of the code.
18047 SemaDiagnosticBuilder DB =
18048 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18049
18050 DB << SS.getScopeRep();
18051 if (DC->isFileContext())
18052 DB << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
18053
18054 // Friend function defined in a local class.
18055 } else if (FunctionContainingLocalClass) {
18056 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18057
18058 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18059 // a template-id, the function name is not unqualified because these is
18060 // no name. While the wording requires some reading in-between the
18061 // lines, GCC, MSVC, and EDG all consider a friend function
18062 // specialization definitions // to be de facto explicit specialization
18063 // and diagnose them as such.
18064 } else if (isTemplateId) {
18065 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18066 }
18067 }
18068
18069 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18070 // default argument expression, that declaration shall be a definition
18071 // and shall be the only declaration of the function or function
18072 // template in the translation unit.
18073 if (functionDeclHasDefaultArgument(FD)) {
18074 // We can't look at FD->getPreviousDecl() because it may not have been set
18075 // if we're in a dependent context. If the function is known to be a
18076 // redeclaration, we will have narrowed Previous down to the right decl.
18077 if (D.isRedeclaration()) {
18078 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18079 Diag(Previous.getRepresentativeDecl()->getLocation(),
18080 diag::note_previous_declaration);
18081 } else if (!D.isFunctionDefinition())
18082 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18083 }
18084
18085 // Mark templated-scope function declarations as unsupported.
18086 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18087 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18088 << SS.getScopeRep() << SS.getRange()
18089 << cast<CXXRecordDecl>(CurContext);
18090 FrD->setUnsupportedFriend(true);
18091 }
18092 }
18093
18094 warnOnReservedIdentifier(D: ND);
18095
18096 return ND;
18097}
18098
18099void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
18100 AdjustDeclIfTemplate(Decl&: Dcl);
18101
18102 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: Dcl);
18103 if (!Fn) {
18104 Diag(DelLoc, diag::err_deleted_non_function);
18105 return;
18106 }
18107
18108 // Deleted function does not have a body.
18109 Fn->setWillHaveBody(false);
18110
18111 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18112 // Don't consider the implicit declaration we generate for explicit
18113 // specializations. FIXME: Do not generate these implicit declarations.
18114 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18115 Prev->getPreviousDecl()) &&
18116 !Prev->isDefined()) {
18117 Diag(DelLoc, diag::err_deleted_decl_not_first);
18118 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18119 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18120 : diag::note_previous_declaration);
18121 // We can't recover from this; the declaration might have already
18122 // been used.
18123 Fn->setInvalidDecl();
18124 return;
18125 }
18126
18127 // To maintain the invariant that functions are only deleted on their first
18128 // declaration, mark the implicitly-instantiated declaration of the
18129 // explicitly-specialized function as deleted instead of marking the
18130 // instantiated redeclaration.
18131 Fn = Fn->getCanonicalDecl();
18132 }
18133
18134 // dllimport/dllexport cannot be deleted.
18135 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18136 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18137 Fn->setInvalidDecl();
18138 }
18139
18140 // C++11 [basic.start.main]p3:
18141 // A program that defines main as deleted [...] is ill-formed.
18142 if (Fn->isMain())
18143 Diag(DelLoc, diag::err_deleted_main);
18144
18145 // C++11 [dcl.fct.def.delete]p4:
18146 // A deleted function is implicitly inline.
18147 Fn->setImplicitlyInline();
18148 Fn->setDeletedAsWritten();
18149}
18150
18151void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18152 if (!Dcl || Dcl->isInvalidDecl())
18153 return;
18154
18155 auto *FD = dyn_cast<FunctionDecl>(Val: Dcl);
18156 if (!FD) {
18157 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Dcl)) {
18158 if (getDefaultedFunctionKind(FD: FTD->getTemplatedDecl()).isComparison()) {
18159 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18160 return;
18161 }
18162 }
18163
18164 Diag(DefaultLoc, diag::err_default_special_members)
18165 << getLangOpts().CPlusPlus20;
18166 return;
18167 }
18168
18169 // Reject if this can't possibly be a defaultable function.
18170 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
18171 if (!DefKind &&
18172 // A dependent function that doesn't locally look defaultable can
18173 // still instantiate to a defaultable function if it's a constructor
18174 // or assignment operator.
18175 (!FD->isDependentContext() ||
18176 (!isa<CXXConstructorDecl>(Val: FD) &&
18177 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18178 Diag(DefaultLoc, diag::err_default_special_members)
18179 << getLangOpts().CPlusPlus20;
18180 return;
18181 }
18182
18183 // Issue compatibility warning. We already warned if the operator is
18184 // 'operator<=>' when parsing the '<=>' token.
18185 if (DefKind.isComparison() &&
18186 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18187 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18188 ? diag::warn_cxx17_compat_defaulted_comparison
18189 : diag::ext_defaulted_comparison);
18190 }
18191
18192 FD->setDefaulted();
18193 FD->setExplicitlyDefaulted();
18194 FD->setDefaultLoc(DefaultLoc);
18195
18196 // Defer checking functions that are defaulted in a dependent context.
18197 if (FD->isDependentContext())
18198 return;
18199
18200 // Unset that we will have a body for this function. We might not,
18201 // if it turns out to be trivial, and we don't need this marking now
18202 // that we've marked it as defaulted.
18203 FD->setWillHaveBody(false);
18204
18205 if (DefKind.isComparison()) {
18206 // If this comparison's defaulting occurs within the definition of its
18207 // lexical class context, we have to do the checking when complete.
18208 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18209 if (!RD->isCompleteDefinition())
18210 return;
18211 }
18212
18213 // If this member fn was defaulted on its first declaration, we will have
18214 // already performed the checking in CheckCompletedCXXClass. Such a
18215 // declaration doesn't trigger an implicit definition.
18216 if (isa<CXXMethodDecl>(Val: FD)) {
18217 const FunctionDecl *Primary = FD;
18218 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18219 // Ask the template instantiation pattern that actually had the
18220 // '= default' on it.
18221 Primary = Pattern;
18222 if (Primary->getCanonicalDecl()->isDefaulted())
18223 return;
18224 }
18225
18226 if (DefKind.isComparison()) {
18227 if (CheckExplicitlyDefaultedComparison(S: nullptr, FD, DCK: DefKind.asComparison()))
18228 FD->setInvalidDecl();
18229 else
18230 DefineDefaultedComparison(UseLoc: DefaultLoc, FD, DCK: DefKind.asComparison());
18231 } else {
18232 auto *MD = cast<CXXMethodDecl>(Val: FD);
18233
18234 if (CheckExplicitlyDefaultedSpecialMember(MD, CSM: DefKind.asSpecialMember(),
18235 DefaultLoc))
18236 MD->setInvalidDecl();
18237 else
18238 DefineDefaultedFunction(*this, MD, DefaultLoc);
18239 }
18240}
18241
18242static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18243 for (Stmt *SubStmt : S->children()) {
18244 if (!SubStmt)
18245 continue;
18246 if (isa<ReturnStmt>(SubStmt))
18247 Self.Diag(SubStmt->getBeginLoc(),
18248 diag::err_return_in_constructor_handler);
18249 if (!isa<Expr>(Val: SubStmt))
18250 SearchForReturnInStmt(Self, S: SubStmt);
18251 }
18252}
18253
18254void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18255 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18256 CXXCatchStmt *Handler = TryBlock->getHandler(i: I);
18257 SearchForReturnInStmt(Self&: *this, S: Handler);
18258 }
18259}
18260
18261void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
18262 FnBodyKind BodyKind) {
18263 switch (BodyKind) {
18264 case FnBodyKind::Delete:
18265 SetDeclDeleted(Dcl: D, DelLoc: Loc);
18266 break;
18267 case FnBodyKind::Default:
18268 SetDeclDefaulted(Dcl: D, DefaultLoc: Loc);
18269 break;
18270 case FnBodyKind::Other:
18271 llvm_unreachable(
18272 "Parsed function body should be '= delete;' or '= default;'");
18273 }
18274}
18275
18276bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
18277 const CXXMethodDecl *Old) {
18278 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18279 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18280
18281 if (OldFT->hasExtParameterInfos()) {
18282 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18283 // A parameter of the overriding method should be annotated with noescape
18284 // if the corresponding parameter of the overridden method is annotated.
18285 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18286 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18287 Diag(New->getParamDecl(I)->getLocation(),
18288 diag::warn_overriding_method_missing_noescape);
18289 Diag(Old->getParamDecl(I)->getLocation(),
18290 diag::note_overridden_marked_noescape);
18291 }
18292 }
18293
18294 // SME attributes must match when overriding a function declaration.
18295 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
18296 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18297 << New << New->getType() << Old->getType();
18298 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18299 return true;
18300 }
18301
18302 // Virtual overrides must have the same code_seg.
18303 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18304 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18305 if ((NewCSA || OldCSA) &&
18306 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18307 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18308 Diag(Old->getLocation(), diag::note_previous_declaration);
18309 return true;
18310 }
18311
18312 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18313
18314 // If the calling conventions match, everything is fine
18315 if (NewCC == OldCC)
18316 return false;
18317
18318 // If the calling conventions mismatch because the new function is static,
18319 // suppress the calling convention mismatch error; the error about static
18320 // function override (err_static_overrides_virtual from
18321 // Sema::CheckFunctionDeclaration) is more clear.
18322 if (New->getStorageClass() == SC_Static)
18323 return false;
18324
18325 Diag(New->getLocation(),
18326 diag::err_conflicting_overriding_cc_attributes)
18327 << New->getDeclName() << New->getType() << Old->getType();
18328 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18329 return true;
18330}
18331
18332bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
18333 const CXXMethodDecl *Old) {
18334 // CWG2553
18335 // A virtual function shall not be an explicit object member function.
18336 if (!New->isExplicitObjectMemberFunction())
18337 return true;
18338 Diag(New->getParamDecl(0)->getBeginLoc(),
18339 diag::err_explicit_object_parameter_nonmember)
18340 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18341 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18342 New->setInvalidDecl();
18343 return false;
18344}
18345
18346bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18347 const CXXMethodDecl *Old) {
18348 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18349 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18350
18351 if (Context.hasSameType(T1: NewTy, T2: OldTy) ||
18352 NewTy->isDependentType() || OldTy->isDependentType())
18353 return false;
18354
18355 // Check if the return types are covariant
18356 QualType NewClassTy, OldClassTy;
18357
18358 /// Both types must be pointers or references to classes.
18359 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18360 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18361 NewClassTy = NewPT->getPointeeType();
18362 OldClassTy = OldPT->getPointeeType();
18363 }
18364 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18365 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18366 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18367 NewClassTy = NewRT->getPointeeType();
18368 OldClassTy = OldRT->getPointeeType();
18369 }
18370 }
18371 }
18372
18373 // The return types aren't either both pointers or references to a class type.
18374 if (NewClassTy.isNull()) {
18375 Diag(New->getLocation(),
18376 diag::err_different_return_type_for_overriding_virtual_function)
18377 << New->getDeclName() << NewTy << OldTy
18378 << New->getReturnTypeSourceRange();
18379 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18380 << Old->getReturnTypeSourceRange();
18381
18382 return true;
18383 }
18384
18385 if (!Context.hasSameUnqualifiedType(T1: NewClassTy, T2: OldClassTy)) {
18386 // C++14 [class.virtual]p8:
18387 // If the class type in the covariant return type of D::f differs from
18388 // that of B::f, the class type in the return type of D::f shall be
18389 // complete at the point of declaration of D::f or shall be the class
18390 // type D.
18391 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18392 if (!RT->isBeingDefined() &&
18393 RequireCompleteType(New->getLocation(), NewClassTy,
18394 diag::err_covariant_return_incomplete,
18395 New->getDeclName()))
18396 return true;
18397 }
18398
18399 // Check if the new class derives from the old class.
18400 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18401 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18402 << New->getDeclName() << NewTy << OldTy
18403 << New->getReturnTypeSourceRange();
18404 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18405 << Old->getReturnTypeSourceRange();
18406 return true;
18407 }
18408
18409 // Check if we the conversion from derived to base is valid.
18410 if (CheckDerivedToBaseConversion(
18411 NewClassTy, OldClassTy,
18412 diag::err_covariant_return_inaccessible_base,
18413 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18414 New->getLocation(), New->getReturnTypeSourceRange(),
18415 New->getDeclName(), nullptr)) {
18416 // FIXME: this note won't trigger for delayed access control
18417 // diagnostics, and it's impossible to get an undelayed error
18418 // here from access control during the original parse because
18419 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18420 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18421 << Old->getReturnTypeSourceRange();
18422 return true;
18423 }
18424 }
18425
18426 // The qualifiers of the return types must be the same.
18427 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18428 Diag(New->getLocation(),
18429 diag::err_covariant_return_type_different_qualifications)
18430 << New->getDeclName() << NewTy << OldTy
18431 << New->getReturnTypeSourceRange();
18432 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18433 << Old->getReturnTypeSourceRange();
18434 return true;
18435 }
18436
18437
18438 // The new class type must have the same or less qualifiers as the old type.
18439 if (NewClassTy.isMoreQualifiedThan(other: OldClassTy)) {
18440 Diag(New->getLocation(),
18441 diag::err_covariant_return_type_class_type_more_qualified)
18442 << New->getDeclName() << NewTy << OldTy
18443 << New->getReturnTypeSourceRange();
18444 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18445 << Old->getReturnTypeSourceRange();
18446 return true;
18447 }
18448
18449 return false;
18450}
18451
18452/// Mark the given method pure.
18453///
18454/// \param Method the method to be marked pure.
18455///
18456/// \param InitRange the source range that covers the "0" initializer.
18457bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
18458 SourceLocation EndLoc = InitRange.getEnd();
18459 if (EndLoc.isValid())
18460 Method->setRangeEnd(EndLoc);
18461
18462 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18463 Method->setIsPureVirtual();
18464 return false;
18465 }
18466
18467 if (!Method->isInvalidDecl())
18468 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18469 << Method->getDeclName() << InitRange;
18470 return true;
18471}
18472
18473void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
18474 if (D->getFriendObjectKind())
18475 Diag(D->getLocation(), diag::err_pure_friend);
18476 else if (auto *M = dyn_cast<CXXMethodDecl>(Val: D))
18477 CheckPureMethod(Method: M, InitRange: ZeroLoc);
18478 else
18479 Diag(D->getLocation(), diag::err_illegal_initializer);
18480}
18481
18482/// Determine whether the given declaration is a global variable or
18483/// static data member.
18484static bool isNonlocalVariable(const Decl *D) {
18485 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(Val: D))
18486 return Var->hasGlobalStorage();
18487
18488 return false;
18489}
18490
18491/// Invoked when we are about to parse an initializer for the declaration
18492/// 'Dcl'.
18493///
18494/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18495/// static data member of class X, names should be looked up in the scope of
18496/// class X. If the declaration had a scope specifier, a scope will have
18497/// been created and passed in for this purpose. Otherwise, S will be null.
18498void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
18499 // If there is no declaration, there was an error parsing it.
18500 if (!D || D->isInvalidDecl())
18501 return;
18502
18503 // We will always have a nested name specifier here, but this declaration
18504 // might not be out of line if the specifier names the current namespace:
18505 // extern int n;
18506 // int ::n = 0;
18507 if (S && D->isOutOfLine())
18508 EnterDeclaratorContext(S, DC: D->getDeclContext());
18509
18510 // If we are parsing the initializer for a static data member, push a
18511 // new expression evaluation context that is associated with this static
18512 // data member.
18513 if (isNonlocalVariable(D))
18514 PushExpressionEvaluationContext(
18515 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, LambdaContextDecl: D);
18516}
18517
18518/// Invoked after we are finished parsing an initializer for the declaration D.
18519void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
18520 // If there is no declaration, there was an error parsing it.
18521 if (!D || D->isInvalidDecl())
18522 return;
18523
18524 if (isNonlocalVariable(D))
18525 PopExpressionEvaluationContext();
18526
18527 if (S && D->isOutOfLine())
18528 ExitDeclaratorContext(S);
18529}
18530
18531/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
18532/// C++ if/switch/while/for statement.
18533/// e.g: "if (int x = f()) {...}"
18534DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
18535 // C++ 6.4p2:
18536 // The declarator shall not specify a function or an array.
18537 // The type-specifier-seq shall not contain typedef and shall not declare a
18538 // new class or enumeration.
18539 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18540 "Parser allowed 'typedef' as storage class of condition decl.");
18541
18542 Decl *Dcl = ActOnDeclarator(S, D);
18543 if (!Dcl)
18544 return true;
18545
18546 if (isa<FunctionDecl>(Val: Dcl)) { // The declarator shall not specify a function.
18547 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18548 << D.getSourceRange();
18549 return true;
18550 }
18551
18552 return Dcl;
18553}
18554
18555void Sema::LoadExternalVTableUses() {
18556 if (!ExternalSource)
18557 return;
18558
18559 SmallVector<ExternalVTableUse, 4> VTables;
18560 ExternalSource->ReadUsedVTables(VTables);
18561 SmallVector<VTableUse, 4> NewUses;
18562 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18563 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18564 = VTablesUsed.find(Val: VTables[I].Record);
18565 // Even if a definition wasn't required before, it may be required now.
18566 if (Pos != VTablesUsed.end()) {
18567 if (!Pos->second && VTables[I].DefinitionRequired)
18568 Pos->second = true;
18569 continue;
18570 }
18571
18572 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18573 NewUses.push_back(Elt: VTableUse(VTables[I].Record, VTables[I].Location));
18574 }
18575
18576 VTableUses.insert(I: VTableUses.begin(), From: NewUses.begin(), To: NewUses.end());
18577}
18578
18579void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
18580 bool DefinitionRequired) {
18581 // Ignore any vtable uses in unevaluated operands or for classes that do
18582 // not have a vtable.
18583 if (!Class->isDynamicClass() || Class->isDependentContext() ||
18584 CurContext->isDependentContext() || isUnevaluatedContext())
18585 return;
18586 // Do not mark as used if compiling for the device outside of the target
18587 // region.
18588 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18589 !isInOpenMPDeclareTargetContext() &&
18590 !isInOpenMPTargetExecutionDirective()) {
18591 if (!DefinitionRequired)
18592 MarkVirtualMembersReferenced(Loc, RD: Class);
18593 return;
18594 }
18595
18596 // Try to insert this class into the map.
18597 LoadExternalVTableUses();
18598 Class = Class->getCanonicalDecl();
18599 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18600 Pos = VTablesUsed.insert(KV: std::make_pair(x&: Class, y&: DefinitionRequired));
18601 if (!Pos.second) {
18602 // If we already had an entry, check to see if we are promoting this vtable
18603 // to require a definition. If so, we need to reappend to the VTableUses
18604 // list, since we may have already processed the first entry.
18605 if (DefinitionRequired && !Pos.first->second) {
18606 Pos.first->second = true;
18607 } else {
18608 // Otherwise, we can early exit.
18609 return;
18610 }
18611 } else {
18612 // The Microsoft ABI requires that we perform the destructor body
18613 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18614 // the deleting destructor is emitted with the vtable, not with the
18615 // destructor definition as in the Itanium ABI.
18616 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18617 CXXDestructorDecl *DD = Class->getDestructor();
18618 if (DD && DD->isVirtual() && !DD->isDeleted()) {
18619 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18620 // If this is an out-of-line declaration, marking it referenced will
18621 // not do anything. Manually call CheckDestructor to look up operator
18622 // delete().
18623 ContextRAII SavedContext(*this, DD);
18624 CheckDestructor(Destructor: DD);
18625 } else {
18626 MarkFunctionReferenced(Loc, Class->getDestructor());
18627 }
18628 }
18629 }
18630 }
18631
18632 // Local classes need to have their virtual members marked
18633 // immediately. For all other classes, we mark their virtual members
18634 // at the end of the translation unit.
18635 if (Class->isLocalClass())
18636 MarkVirtualMembersReferenced(Loc, RD: Class->getDefinition());
18637 else
18638 VTableUses.push_back(Elt: std::make_pair(x&: Class, y&: Loc));
18639}
18640
18641bool Sema::DefineUsedVTables() {
18642 LoadExternalVTableUses();
18643 if (VTableUses.empty())
18644 return false;
18645
18646 // Note: The VTableUses vector could grow as a result of marking
18647 // the members of a class as "used", so we check the size each
18648 // time through the loop and prefer indices (which are stable) to
18649 // iterators (which are not).
18650 bool DefinedAnything = false;
18651 for (unsigned I = 0; I != VTableUses.size(); ++I) {
18652 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18653 if (!Class)
18654 continue;
18655 TemplateSpecializationKind ClassTSK =
18656 Class->getTemplateSpecializationKind();
18657
18658 SourceLocation Loc = VTableUses[I].second;
18659
18660 bool DefineVTable = true;
18661
18662 // If this class has a key function, but that key function is
18663 // defined in another translation unit, we don't need to emit the
18664 // vtable even though we're using it.
18665 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(RD: Class);
18666 if (KeyFunction && !KeyFunction->hasBody()) {
18667 // The key function is in another translation unit.
18668 DefineVTable = false;
18669 TemplateSpecializationKind TSK =
18670 KeyFunction->getTemplateSpecializationKind();
18671 assert(TSK != TSK_ExplicitInstantiationDefinition &&
18672 TSK != TSK_ImplicitInstantiation &&
18673 "Instantiations don't have key functions");
18674 (void)TSK;
18675 } else if (!KeyFunction) {
18676 // If we have a class with no key function that is the subject
18677 // of an explicit instantiation declaration, suppress the
18678 // vtable; it will live with the explicit instantiation
18679 // definition.
18680 bool IsExplicitInstantiationDeclaration =
18681 ClassTSK == TSK_ExplicitInstantiationDeclaration;
18682 for (auto *R : Class->redecls()) {
18683 TemplateSpecializationKind TSK
18684 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18685 if (TSK == TSK_ExplicitInstantiationDeclaration)
18686 IsExplicitInstantiationDeclaration = true;
18687 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18688 IsExplicitInstantiationDeclaration = false;
18689 break;
18690 }
18691 }
18692
18693 if (IsExplicitInstantiationDeclaration)
18694 DefineVTable = false;
18695 }
18696
18697 // The exception specifications for all virtual members may be needed even
18698 // if we are not providing an authoritative form of the vtable in this TU.
18699 // We may choose to emit it available_externally anyway.
18700 if (!DefineVTable) {
18701 MarkVirtualMemberExceptionSpecsNeeded(Loc, RD: Class);
18702 continue;
18703 }
18704
18705 // Mark all of the virtual members of this class as referenced, so
18706 // that we can build a vtable. Then, tell the AST consumer that a
18707 // vtable for this class is required.
18708 DefinedAnything = true;
18709 MarkVirtualMembersReferenced(Loc, RD: Class);
18710 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18711 if (VTablesUsed[Canonical])
18712 Consumer.HandleVTable(RD: Class);
18713
18714 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18715 // no key function or the key function is inlined. Don't warn in C++ ABIs
18716 // that lack key functions, since the user won't be able to make one.
18717 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
18718 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18719 ClassTSK != TSK_ExplicitInstantiationDefinition) {
18720 const FunctionDecl *KeyFunctionDef = nullptr;
18721 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18722 KeyFunctionDef->isInlined()))
18723 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18724 }
18725 }
18726 VTableUses.clear();
18727
18728 return DefinedAnything;
18729}
18730
18731void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
18732 const CXXRecordDecl *RD) {
18733 for (const auto *I : RD->methods())
18734 if (I->isVirtual() && !I->isPureVirtual())
18735 ResolveExceptionSpec(Loc, FPT: I->getType()->castAs<FunctionProtoType>());
18736}
18737
18738void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
18739 const CXXRecordDecl *RD,
18740 bool ConstexprOnly) {
18741 // Mark all functions which will appear in RD's vtable as used.
18742 CXXFinalOverriderMap FinalOverriders;
18743 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
18744 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18745 E = FinalOverriders.end();
18746 I != E; ++I) {
18747 for (OverridingMethods::const_iterator OI = I->second.begin(),
18748 OE = I->second.end();
18749 OI != OE; ++OI) {
18750 assert(OI->second.size() > 0 && "no final overrider");
18751 CXXMethodDecl *Overrider = OI->second.front().Method;
18752
18753 // C++ [basic.def.odr]p2:
18754 // [...] A virtual member function is used if it is not pure. [...]
18755 if (!Overrider->isPureVirtual() &&
18756 (!ConstexprOnly || Overrider->isConstexpr()))
18757 MarkFunctionReferenced(Loc, Overrider);
18758 }
18759 }
18760
18761 // Only classes that have virtual bases need a VTT.
18762 if (RD->getNumVBases() == 0)
18763 return;
18764
18765 for (const auto &I : RD->bases()) {
18766 const auto *Base =
18767 cast<CXXRecordDecl>(Val: I.getType()->castAs<RecordType>()->getDecl());
18768 if (Base->getNumVBases() == 0)
18769 continue;
18770 MarkVirtualMembersReferenced(Loc, RD: Base);
18771 }
18772}
18773
18774/// SetIvarInitializers - This routine builds initialization ASTs for the
18775/// Objective-C implementation whose ivars need be initialized.
18776void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
18777 if (!getLangOpts().CPlusPlus)
18778 return;
18779 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
18780 SmallVector<ObjCIvarDecl*, 8> ivars;
18781 CollectIvarsToConstructOrDestruct(OI: OID, Ivars&: ivars);
18782 if (ivars.empty())
18783 return;
18784 SmallVector<CXXCtorInitializer*, 32> AllToInit;
18785 for (unsigned i = 0; i < ivars.size(); i++) {
18786 FieldDecl *Field = ivars[i];
18787 if (Field->isInvalidDecl())
18788 continue;
18789
18790 CXXCtorInitializer *Member;
18791 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Member: Field);
18792 InitializationKind InitKind =
18793 InitializationKind::CreateDefault(InitLoc: ObjCImplementation->getLocation());
18794
18795 InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt);
18796 ExprResult MemberInit =
18797 InitSeq.Perform(S&: *this, Entity: InitEntity, Kind: InitKind, Args: std::nullopt);
18798 MemberInit = MaybeCreateExprWithCleanups(SubExpr: MemberInit);
18799 // Note, MemberInit could actually come back empty if no initialization
18800 // is required (e.g., because it would call a trivial default constructor)
18801 if (!MemberInit.get() || MemberInit.isInvalid())
18802 continue;
18803
18804 Member =
18805 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
18806 SourceLocation(),
18807 MemberInit.getAs<Expr>(),
18808 SourceLocation());
18809 AllToInit.push_back(Elt: Member);
18810
18811 // Be sure that the destructor is accessible and is marked as referenced.
18812 if (const RecordType *RecordTy =
18813 Context.getBaseElementType(Field->getType())
18814 ->getAs<RecordType>()) {
18815 CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: RecordTy->getDecl());
18816 if (CXXDestructorDecl *Destructor = LookupDestructor(Class: RD)) {
18817 MarkFunctionReferenced(Loc: Field->getLocation(), Func: Destructor);
18818 CheckDestructorAccess(Field->getLocation(), Destructor,
18819 PDiag(diag::err_access_dtor_ivar)
18820 << Context.getBaseElementType(Field->getType()));
18821 }
18822 }
18823 }
18824 ObjCImplementation->setIvarInitializers(C&: Context,
18825 initializers: AllToInit.data(), numInitializers: AllToInit.size());
18826 }
18827}
18828
18829static
18830void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
18831 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
18832 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
18833 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
18834 Sema &S) {
18835 if (Ctor->isInvalidDecl())
18836 return;
18837
18838 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
18839
18840 // Target may not be determinable yet, for instance if this is a dependent
18841 // call in an uninstantiated template.
18842 if (Target) {
18843 const FunctionDecl *FNTarget = nullptr;
18844 (void)Target->hasBody(FNTarget);
18845 Target = const_cast<CXXConstructorDecl*>(
18846 cast_or_null<CXXConstructorDecl>(Val: FNTarget));
18847 }
18848
18849 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18850 // Avoid dereferencing a null pointer here.
18851 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18852
18853 if (!Current.insert(Ptr: Canonical).second)
18854 return;
18855
18856 // We know that beyond here, we aren't chaining into a cycle.
18857 if (!Target || !Target->isDelegatingConstructor() ||
18858 Target->isInvalidDecl() || Valid.count(Ptr: TCanonical)) {
18859 Valid.insert(I: Current.begin(), E: Current.end());
18860 Current.clear();
18861 // We've hit a cycle.
18862 } else if (TCanonical == Canonical || Invalid.count(Ptr: TCanonical) ||
18863 Current.count(Ptr: TCanonical)) {
18864 // If we haven't diagnosed this cycle yet, do so now.
18865 if (!Invalid.count(Ptr: TCanonical)) {
18866 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18867 diag::warn_delegating_ctor_cycle)
18868 << Ctor;
18869
18870 // Don't add a note for a function delegating directly to itself.
18871 if (TCanonical != Canonical)
18872 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18873
18874 CXXConstructorDecl *C = Target;
18875 while (C->getCanonicalDecl() != Canonical) {
18876 const FunctionDecl *FNTarget = nullptr;
18877 (void)C->getTargetConstructor()->hasBody(FNTarget);
18878 assert(FNTarget && "Ctor cycle through bodiless function");
18879
18880 C = const_cast<CXXConstructorDecl*>(
18881 cast<CXXConstructorDecl>(Val: FNTarget));
18882 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18883 }
18884 }
18885
18886 Invalid.insert(I: Current.begin(), E: Current.end());
18887 Current.clear();
18888 } else {
18889 DelegatingCycleHelper(Ctor: Target, Valid, Invalid, Current, S);
18890 }
18891}
18892
18893
18894void Sema::CheckDelegatingCtorCycles() {
18895 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18896
18897 for (DelegatingCtorDeclsType::iterator
18898 I = DelegatingCtorDecls.begin(source: ExternalSource.get()),
18899 E = DelegatingCtorDecls.end();
18900 I != E; ++I)
18901 DelegatingCycleHelper(Ctor: *I, Valid, Invalid, Current, S&: *this);
18902
18903 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18904 (*CI)->setInvalidDecl();
18905}
18906
18907namespace {
18908 /// AST visitor that finds references to the 'this' expression.
18909 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18910 Sema &S;
18911
18912 public:
18913 explicit FindCXXThisExpr(Sema &S) : S(S) { }
18914
18915 bool VisitCXXThisExpr(CXXThisExpr *E) {
18916 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18917 << E->isImplicit();
18918 return false;
18919 }
18920 };
18921}
18922
18923bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18924 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18925 if (!TSInfo)
18926 return false;
18927
18928 TypeLoc TL = TSInfo->getTypeLoc();
18929 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18930 if (!ProtoTL)
18931 return false;
18932
18933 // C++11 [expr.prim.general]p3:
18934 // [The expression this] shall not appear before the optional
18935 // cv-qualifier-seq and it shall not appear within the declaration of a
18936 // static member function (although its type and value category are defined
18937 // within a static member function as they are within a non-static member
18938 // function). [ Note: this is because declaration matching does not occur
18939 // until the complete declarator is known. - end note ]
18940 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18941 FindCXXThisExpr Finder(*this);
18942
18943 // If the return type came after the cv-qualifier-seq, check it now.
18944 if (Proto->hasTrailingReturn() &&
18945 !Finder.TraverseTypeLoc(TL: ProtoTL.getReturnLoc()))
18946 return true;
18947
18948 // Check the exception specification.
18949 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18950 return true;
18951
18952 // Check the trailing requires clause
18953 if (Expr *E = Method->getTrailingRequiresClause())
18954 if (!Finder.TraverseStmt(E))
18955 return true;
18956
18957 return checkThisInStaticMemberFunctionAttributes(Method);
18958}
18959
18960bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18961 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18962 if (!TSInfo)
18963 return false;
18964
18965 TypeLoc TL = TSInfo->getTypeLoc();
18966 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18967 if (!ProtoTL)
18968 return false;
18969
18970 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18971 FindCXXThisExpr Finder(*this);
18972
18973 switch (Proto->getExceptionSpecType()) {
18974 case EST_Unparsed:
18975 case EST_Uninstantiated:
18976 case EST_Unevaluated:
18977 case EST_BasicNoexcept:
18978 case EST_NoThrow:
18979 case EST_DynamicNone:
18980 case EST_MSAny:
18981 case EST_None:
18982 break;
18983
18984 case EST_DependentNoexcept:
18985 case EST_NoexceptFalse:
18986 case EST_NoexceptTrue:
18987 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18988 return true;
18989 [[fallthrough]];
18990
18991 case EST_Dynamic:
18992 for (const auto &E : Proto->exceptions()) {
18993 if (!Finder.TraverseType(E))
18994 return true;
18995 }
18996 break;
18997 }
18998
18999 return false;
19000}
19001
19002bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19003 FindCXXThisExpr Finder(*this);
19004
19005 // Check attributes.
19006 for (const auto *A : Method->attrs()) {
19007 // FIXME: This should be emitted by tblgen.
19008 Expr *Arg = nullptr;
19009 ArrayRef<Expr *> Args;
19010 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19011 Arg = G->getArg();
19012 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19013 Arg = G->getArg();
19014 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19015 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19016 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19017 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19018 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
19019 Arg = ETLF->getSuccessValue();
19020 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
19021 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
19022 Arg = STLF->getSuccessValue();
19023 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
19024 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19025 Arg = LR->getArg();
19026 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19027 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19028 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19029 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19030 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19031 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19032 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
19033 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19034 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19035 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19036
19037 if (Arg && !Finder.TraverseStmt(Arg))
19038 return true;
19039
19040 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
19041 if (!Finder.TraverseStmt(Args[I]))
19042 return true;
19043 }
19044 }
19045
19046 return false;
19047}
19048
19049void Sema::checkExceptionSpecification(
19050 bool IsTopLevel, ExceptionSpecificationType EST,
19051 ArrayRef<ParsedType> DynamicExceptions,
19052 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19053 SmallVectorImpl<QualType> &Exceptions,
19054 FunctionProtoType::ExceptionSpecInfo &ESI) {
19055 Exceptions.clear();
19056 ESI.Type = EST;
19057 if (EST == EST_Dynamic) {
19058 Exceptions.reserve(N: DynamicExceptions.size());
19059 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19060 // FIXME: Preserve type source info.
19061 QualType ET = GetTypeFromParser(Ty: DynamicExceptions[ei]);
19062
19063 if (IsTopLevel) {
19064 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19065 collectUnexpandedParameterPacks(T: ET, Unexpanded);
19066 if (!Unexpanded.empty()) {
19067 DiagnoseUnexpandedParameterPacks(
19068 Loc: DynamicExceptionRanges[ei].getBegin(), UPPC: UPPC_ExceptionType,
19069 Unexpanded);
19070 continue;
19071 }
19072 }
19073
19074 // Check that the type is valid for an exception spec, and
19075 // drop it if not.
19076 if (!CheckSpecifiedExceptionType(T&: ET, Range: DynamicExceptionRanges[ei]))
19077 Exceptions.push_back(Elt: ET);
19078 }
19079 ESI.Exceptions = Exceptions;
19080 return;
19081 }
19082
19083 if (isComputedNoexcept(ESpecType: EST)) {
19084 assert((NoexceptExpr->isTypeDependent() ||
19085 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19086 Context.BoolTy) &&
19087 "Parser should have made sure that the expression is boolean");
19088 if (IsTopLevel && DiagnoseUnexpandedParameterPack(E: NoexceptExpr)) {
19089 ESI.Type = EST_BasicNoexcept;
19090 return;
19091 }
19092
19093 ESI.NoexceptExpr = NoexceptExpr;
19094 return;
19095 }
19096}
19097
19098void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
19099 ExceptionSpecificationType EST,
19100 SourceRange SpecificationRange,
19101 ArrayRef<ParsedType> DynamicExceptions,
19102 ArrayRef<SourceRange> DynamicExceptionRanges,
19103 Expr *NoexceptExpr) {
19104 if (!MethodD)
19105 return;
19106
19107 // Dig out the method we're referring to.
19108 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: MethodD))
19109 MethodD = FunTmpl->getTemplatedDecl();
19110
19111 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: MethodD);
19112 if (!Method)
19113 return;
19114
19115 // Check the exception specification.
19116 llvm::SmallVector<QualType, 4> Exceptions;
19117 FunctionProtoType::ExceptionSpecInfo ESI;
19118 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
19119 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19120 ESI);
19121
19122 // Update the exception specification on the function type.
19123 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
19124
19125 if (Method->isStatic())
19126 checkThisInStaticMemberFunctionExceptionSpec(Method);
19127
19128 if (Method->isVirtual()) {
19129 // Check overrides, which we previously had to delay.
19130 for (const CXXMethodDecl *O : Method->overridden_methods())
19131 CheckOverridingFunctionExceptionSpec(New: Method, Old: O);
19132 }
19133}
19134
19135/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19136///
19137MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19138 SourceLocation DeclStart, Declarator &D,
19139 Expr *BitWidth,
19140 InClassInitStyle InitStyle,
19141 AccessSpecifier AS,
19142 const ParsedAttr &MSPropertyAttr) {
19143 IdentifierInfo *II = D.getIdentifier();
19144 if (!II) {
19145 Diag(DeclStart, diag::err_anonymous_property);
19146 return nullptr;
19147 }
19148 SourceLocation Loc = D.getIdentifierLoc();
19149
19150 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19151 QualType T = TInfo->getType();
19152 if (getLangOpts().CPlusPlus) {
19153 CheckExtraCXXDefaultArguments(D);
19154
19155 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19156 UPPC: UPPC_DataMemberType)) {
19157 D.setInvalidType();
19158 T = Context.IntTy;
19159 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19160 }
19161 }
19162
19163 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19164
19165 if (D.getDeclSpec().isInlineSpecified())
19166 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19167 << getLangOpts().CPlusPlus17;
19168 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19169 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
19170 diag::err_invalid_thread)
19171 << DeclSpec::getSpecifierName(TSCS);
19172
19173 // Check to see if this name was declared as a member previously
19174 NamedDecl *PrevDecl = nullptr;
19175 LookupResult Previous(*this, II, Loc, LookupMemberName,
19176 ForVisibleRedeclaration);
19177 LookupName(R&: Previous, S);
19178 switch (Previous.getResultKind()) {
19179 case LookupResult::Found:
19180 case LookupResult::FoundUnresolvedValue:
19181 PrevDecl = Previous.getAsSingle<NamedDecl>();
19182 break;
19183
19184 case LookupResult::FoundOverloaded:
19185 PrevDecl = Previous.getRepresentativeDecl();
19186 break;
19187
19188 case LookupResult::NotFound:
19189 case LookupResult::NotFoundInCurrentInstantiation:
19190 case LookupResult::Ambiguous:
19191 break;
19192 }
19193
19194 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19195 // Maybe we will complain about the shadowed template parameter.
19196 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
19197 // Just pretend that we didn't see the previous declaration.
19198 PrevDecl = nullptr;
19199 }
19200
19201 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19202 PrevDecl = nullptr;
19203
19204 SourceLocation TSSL = D.getBeginLoc();
19205 MSPropertyDecl *NewPD =
19206 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19207 MSPropertyAttr.getPropertyDataGetter(),
19208 MSPropertyAttr.getPropertyDataSetter());
19209 ProcessDeclAttributes(TUScope, NewPD, D);
19210 NewPD->setAccess(AS);
19211
19212 if (NewPD->isInvalidDecl())
19213 Record->setInvalidDecl();
19214
19215 if (D.getDeclSpec().isModulePrivateSpecified())
19216 NewPD->setModulePrivate();
19217
19218 if (NewPD->isInvalidDecl() && PrevDecl) {
19219 // Don't introduce NewFD into scope; there's already something
19220 // with the same name in the same scope.
19221 } else if (II) {
19222 PushOnScopeChains(NewPD, S);
19223 } else
19224 Record->addDecl(NewPD);
19225
19226 return NewPD;
19227}
19228
19229void Sema::ActOnStartFunctionDeclarationDeclarator(
19230 Declarator &Declarator, unsigned TemplateParameterDepth) {
19231 auto &Info = InventedParameterInfos.emplace_back();
19232 TemplateParameterList *ExplicitParams = nullptr;
19233 ArrayRef<TemplateParameterList *> ExplicitLists =
19234 Declarator.getTemplateParameterLists();
19235 if (!ExplicitLists.empty()) {
19236 bool IsMemberSpecialization, IsInvalid;
19237 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19238 DeclStartLoc: Declarator.getBeginLoc(), DeclLoc: Declarator.getIdentifierLoc(),
19239 SS: Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19240 ParamLists: ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, Invalid&: IsInvalid,
19241 /*SuppressDiagnostic=*/true);
19242 }
19243 // C++23 [dcl.fct]p23:
19244 // An abbreviated function template can have a template-head. The invented
19245 // template-parameters are appended to the template-parameter-list after
19246 // the explicitly declared template-parameters.
19247 //
19248 // A template-head must have one or more template-parameters (read:
19249 // 'template<>' is *not* a template-head). Only append the invented
19250 // template parameters if we matched the nested-name-specifier to a non-empty
19251 // TemplateParameterList.
19252 if (ExplicitParams && !ExplicitParams->empty()) {
19253 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19254 llvm::append_range(C&: Info.TemplateParams, R&: *ExplicitParams);
19255 Info.NumExplicitTemplateParams = ExplicitParams->size();
19256 } else {
19257 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19258 Info.NumExplicitTemplateParams = 0;
19259 }
19260}
19261
19262void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19263 auto &FSI = InventedParameterInfos.back();
19264 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19265 if (FSI.NumExplicitTemplateParams != 0) {
19266 TemplateParameterList *ExplicitParams =
19267 Declarator.getTemplateParameterLists().back();
19268 Declarator.setInventedTemplateParameterList(
19269 TemplateParameterList::Create(
19270 C: Context, TemplateLoc: ExplicitParams->getTemplateLoc(),
19271 LAngleLoc: ExplicitParams->getLAngleLoc(), Params: FSI.TemplateParams,
19272 RAngleLoc: ExplicitParams->getRAngleLoc(),
19273 RequiresClause: ExplicitParams->getRequiresClause()));
19274 } else {
19275 Declarator.setInventedTemplateParameterList(
19276 TemplateParameterList::Create(
19277 C: Context, TemplateLoc: SourceLocation(), LAngleLoc: SourceLocation(), Params: FSI.TemplateParams,
19278 RAngleLoc: SourceLocation(), /*RequiresClause=*/nullptr));
19279 }
19280 }
19281 InventedParameterInfos.pop_back();
19282}
19283

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