clang 23.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
28#include "clang/AST/TypeLoc.h"
37#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/Lookup.h"
43#include "clang/Sema/Scope.h"
45#include "clang/Sema/SemaCUDA.h"
47#include "clang/Sema/SemaObjC.h"
49#include "clang/Sema/Template.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/Support/ConvertUTF.h"
55#include "llvm/Support/SaveAndRestore.h"
56#include <map>
57#include <optional>
58#include <set>
59
60using namespace clang;
61
62//===----------------------------------------------------------------------===//
63// CheckDefaultArgumentVisitor
64//===----------------------------------------------------------------------===//
65
66namespace {
67/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
68/// the default argument of a parameter to determine whether it
69/// contains any ill-formed subexpressions. For example, this will
70/// diagnose the use of local variables or parameters within the
71/// default argument expression.
72class CheckDefaultArgumentVisitor
73 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
74 Sema &S;
75 const Expr *DefaultArg;
76
77public:
78 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
79 : S(S), DefaultArg(DefaultArg) {}
80
81 bool VisitExpr(const Expr *Node);
82 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
83 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
84 bool VisitLambdaExpr(const LambdaExpr *Lambda);
85 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
86 bool VisitCoawaitExpr(const CoawaitExpr *E);
87 bool VisitCoyieldExpr(const CoyieldExpr *E);
88};
89
90/// VisitExpr - Visit all of the children of this expression.
91bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
92 bool IsInvalid = false;
93 for (const Stmt *SubStmt : Node->children())
94 if (SubStmt)
95 IsInvalid |= Visit(SubStmt);
96 return IsInvalid;
97}
98
99/// VisitDeclRefExpr - Visit a reference to a declaration, to
100/// determine whether this declaration can be used in the default
101/// argument expression.
102bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
103 const ValueDecl *Decl = DRE->getDecl();
104
105 if (!isa<VarDecl, BindingDecl>(Decl))
106 return false;
107
108 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
109 // C++ [dcl.fct.default]p9:
110 // [...] parameters of a function shall not be used in default
111 // argument expressions, even if they are not evaluated. [...]
112 //
113 // C++17 [dcl.fct.default]p9 (by CWG 2082):
114 // [...] A parameter shall not appear as a potentially-evaluated
115 // expression in a default argument. [...]
116 //
117 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
118 return S.Diag(DRE->getBeginLoc(),
119 diag::err_param_default_argument_references_param)
120 << Param->getDeclName() << DefaultArg->getSourceRange();
121 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
122 // C++ [dcl.fct.default]p7:
123 // Local variables shall not be used in default argument
124 // expressions.
125 //
126 // C++17 [dcl.fct.default]p7 (by CWG 2082):
127 // A local variable shall not appear as a potentially-evaluated
128 // expression in a default argument.
129 //
130 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
131 // Note: A local variable cannot be odr-used (6.3) in a default
132 // argument.
133 //
134 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
135 return S.Diag(DRE->getBeginLoc(),
136 diag::err_param_default_argument_references_local)
137 << Decl << DefaultArg->getSourceRange();
138 }
139 return false;
140}
141
142/// VisitCXXThisExpr - Visit a C++ "this" expression.
143bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
144 // C++ [dcl.fct.default]p8:
145 // The keyword this shall not be used in a default argument of a
146 // member function.
147 return S.Diag(ThisE->getBeginLoc(),
148 diag::err_param_default_argument_references_this)
149 << ThisE->getSourceRange();
150}
151
152bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
153 const PseudoObjectExpr *POE) {
154 bool Invalid = false;
155 for (const Expr *E : POE->semantics()) {
156 // Look through bindings.
157 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
158 E = OVE->getSourceExpr();
159 assert(E && "pseudo-object binding without source expression?");
160 }
161
162 Invalid |= Visit(E);
163 }
164 return Invalid;
165}
166
167bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
168 // [expr.prim.lambda.capture]p9
169 // a lambda-expression appearing in a default argument cannot implicitly or
170 // explicitly capture any local entity. Such a lambda-expression can still
171 // have an init-capture if any full-expression in its initializer satisfies
172 // the constraints of an expression appearing in a default argument.
173 bool Invalid = false;
174 for (const LambdaCapture &LC : Lambda->captures()) {
175 if (!Lambda->isInitCapture(&LC))
176 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
177 // Init captures are always VarDecl.
178 auto *D = cast<VarDecl>(LC.getCapturedVar());
179 Invalid |= Visit(D->getInit());
180 }
181 return Invalid;
182}
183
184bool CheckDefaultArgumentVisitor::VisitCoawaitExpr(const CoawaitExpr *E) {
185 // [expr.await] An await-expression shall not appear in a default argument.
186 // Note that this is generally diagnosed by isValidCoroutineContext,
187 // however isValidCoroutineContext misses default argument in nested
188 // function declarations.
189 S.Diag(E->getBeginLoc(), diag::err_coroutine_outside_function)
190 << "co_await" << E->getSourceRange();
191 return true;
192}
193
194bool CheckDefaultArgumentVisitor::VisitCoyieldExpr(const CoyieldExpr *E) {
195 S.Diag(E->getBeginLoc(), diag::err_coroutine_outside_function)
196 << "co_yield" << E->getSourceRange();
197 return true;
198}
199
200} // namespace
201
202void
204 const CXXMethodDecl *Method) {
205 // If we have an MSAny spec already, don't bother.
206 if (!Method || ComputedEST == EST_MSAny)
207 return;
208
209 const FunctionProtoType *Proto
210 = Method->getType()->getAs<FunctionProtoType>();
211 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
212 if (!Proto)
213 return;
214
216
217 // If we have a throw-all spec at this point, ignore the function.
218 if (ComputedEST == EST_None)
219 return;
220
221 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
222 EST = EST_BasicNoexcept;
223
224 switch (EST) {
225 case EST_Unparsed:
227 case EST_Unevaluated:
228 llvm_unreachable("should not see unresolved exception specs here");
229
230 // If this function can throw any exceptions, make a note of that.
231 case EST_MSAny:
232 case EST_None:
233 // FIXME: Whichever we see last of MSAny and None determines our result.
234 // We should make a consistent, order-independent choice here.
235 ClearExceptions();
236 ComputedEST = EST;
237 return;
239 ClearExceptions();
240 ComputedEST = EST_None;
241 return;
242 // FIXME: If the call to this decl is using any of its default arguments, we
243 // need to search them for potentially-throwing calls.
244 // If this function has a basic noexcept, it doesn't affect the outcome.
246 case EST_NoexceptTrue:
247 case EST_NoThrow:
248 return;
249 // If we're still at noexcept(true) and there's a throw() callee,
250 // change to that specification.
251 case EST_DynamicNone:
252 if (ComputedEST == EST_BasicNoexcept)
253 ComputedEST = EST_DynamicNone;
254 return;
256 llvm_unreachable(
257 "should not generate implicit declarations for dependent cases");
258 case EST_Dynamic:
259 break;
260 }
261 assert(EST == EST_Dynamic && "EST case not considered earlier.");
262 assert(ComputedEST != EST_None &&
263 "Shouldn't collect exceptions when throw-all is guaranteed.");
264 ComputedEST = EST_Dynamic;
265 // Record the exceptions in this function's exception specification.
266 for (const auto &E : Proto->exceptions())
267 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
268 Exceptions.push_back(E);
269}
270
272 if (!S || ComputedEST == EST_MSAny)
273 return;
274
275 // FIXME:
276 //
277 // C++0x [except.spec]p14:
278 // [An] implicit exception-specification specifies the type-id T if and
279 // only if T is allowed by the exception-specification of a function directly
280 // invoked by f's implicit definition; f shall allow all exceptions if any
281 // function it directly invokes allows all exceptions, and f shall allow no
282 // exceptions if every function it directly invokes allows no exceptions.
283 //
284 // Note in particular that if an implicit exception-specification is generated
285 // for a function containing a throw-expression, that specification can still
286 // be noexcept(true).
287 //
288 // Note also that 'directly invoked' is not defined in the standard, and there
289 // is no indication that we should only consider potentially-evaluated calls.
290 //
291 // Ultimately we should implement the intent of the standard: the exception
292 // specification should be the set of exceptions which can be thrown by the
293 // implicit definition. For now, we assume that any non-nothrow expression can
294 // throw any exception.
295
296 if (Self->canThrow(S))
297 ComputedEST = EST_None;
298}
299
301 SourceLocation EqualLoc) {
302 if (RequireCompleteType(Param->getLocation(), Param->getType(),
303 diag::err_typecheck_decl_incomplete_type))
304 return true;
305
306 // C++ [dcl.fct.default]p5
307 // A default argument expression is implicitly converted (clause
308 // 4) to the parameter type. The default argument expression has
309 // the same semantic constraints as the initializer expression in
310 // a declaration of a variable of the parameter type, using the
311 // copy-initialization semantics (8.5).
313 Param);
314 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
315 EqualLoc);
316 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
317 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
318 if (Result.isInvalid())
319 return true;
320 Arg = Result.getAs<Expr>();
321
322 CheckCompletedExpr(Arg, EqualLoc);
324
325 return Arg;
326}
327
329 SourceLocation EqualLoc) {
330 // Add the default argument to the parameter
331 Param->setDefaultArg(Arg);
332
333 // We have already instantiated this parameter; provide each of the
334 // instantiations with the uninstantiated default argument.
335 UnparsedDefaultArgInstantiationsMap::iterator InstPos
337 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
338 for (auto &Instantiation : InstPos->second)
339 Instantiation->setUninstantiatedDefaultArg(Arg);
340
341 // We're done tracking this parameter's instantiations.
343 }
344}
345
346void
348 Expr *DefaultArg) {
349 if (!param || !DefaultArg)
350 return;
351
352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
353 UnparsedDefaultArgLocs.erase(Param);
354
355 // Default arguments are only permitted in C++
356 if (!getLangOpts().CPlusPlus) {
357 Diag(EqualLoc, diag::err_param_default_argument)
358 << DefaultArg->getSourceRange();
359 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
360 }
361
362 // Check for unexpanded parameter packs.
364 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
365
366 // C++11 [dcl.fct.default]p3
367 // A default argument expression [...] shall not be specified for a
368 // parameter pack.
369 if (Param->isParameterPack()) {
370 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
371 << DefaultArg->getSourceRange();
372 // Recover by discarding the default argument.
373 Param->setDefaultArg(nullptr);
374 return;
375 }
376
377 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
378 if (Result.isInvalid())
379 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
380
381 DefaultArg = Result.getAs<Expr>();
382
383 // Check that the default argument is well-formed
384 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
385 if (DefaultArgChecker.Visit(DefaultArg))
386 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
387
388 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
389}
390
392 SourceLocation EqualLoc,
393 SourceLocation ArgLoc) {
394 if (!param)
395 return;
396
397 ParmVarDecl *Param = cast<ParmVarDecl>(param);
398 Param->setUnparsedDefaultArg();
399 UnparsedDefaultArgLocs[Param] = ArgLoc;
400}
401
403 Expr *DefaultArg) {
404 if (!param)
405 return;
406
407 ParmVarDecl *Param = cast<ParmVarDecl>(param);
408 Param->setInvalidDecl();
409 UnparsedDefaultArgLocs.erase(Param);
410 ExprResult RE;
411 if (DefaultArg) {
412 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
413 Param->getType().getNonReferenceType());
414 } else {
415 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
416 Param->getType().getNonReferenceType());
417 }
418 Param->setDefaultArg(RE.get());
419}
420
422 // C++ [dcl.fct.default]p3
423 // A default argument expression shall be specified only in the
424 // parameter-declaration-clause of a function declaration or in a
425 // template-parameter (14.1). It shall not be specified for a
426 // parameter pack. If it is specified in a
427 // parameter-declaration-clause, it shall not occur within a
428 // declarator or abstract-declarator of a parameter-declaration.
429 bool MightBeFunction = D.isFunctionDeclarationContext();
430 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
431 DeclaratorChunk &chunk = D.getTypeObject(i);
432 if (chunk.Kind == DeclaratorChunk::Function) {
433 if (MightBeFunction) {
434 // This is a function declaration. It can have default arguments, but
435 // keep looking in case its return type is a function type with default
436 // arguments.
437 MightBeFunction = false;
438 continue;
439 }
440 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
441 ++argIdx) {
442 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
443 if (Param->hasUnparsedDefaultArg()) {
444 std::unique_ptr<CachedTokens> Toks =
445 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
446 SourceRange SR;
447 if (Toks->size() > 1)
448 SR = SourceRange((*Toks)[1].getLocation(),
449 Toks->back().getLocation());
450 else
451 SR = UnparsedDefaultArgLocs[Param];
452 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
453 << SR;
454 } else if (Param->getDefaultArg()) {
455 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
456 << Param->getDefaultArg()->getSourceRange();
457 Param->setDefaultArg(nullptr);
458 }
459 }
460 } else if (chunk.Kind != DeclaratorChunk::Paren) {
461 MightBeFunction = false;
462 }
463 }
464}
465
467 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
468 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
469 });
470}
471
473 Scope *S) {
474 bool Invalid = false;
475
476 // The declaration context corresponding to the scope is the semantic
477 // parent, unless this is a local function declaration, in which case
478 // it is that surrounding function.
479 DeclContext *ScopeDC = New->isLocalExternDecl()
480 ? New->getLexicalDeclContext()
481 : New->getDeclContext();
482
483 // Find the previous declaration for the purpose of default arguments.
484 FunctionDecl *PrevForDefaultArgs = Old;
485 for (/**/; PrevForDefaultArgs;
486 // Don't bother looking back past the latest decl if this is a local
487 // extern declaration; nothing else could work.
488 PrevForDefaultArgs = New->isLocalExternDecl()
489 ? nullptr
490 : PrevForDefaultArgs->getPreviousDecl()) {
491 // Ignore hidden declarations.
492 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
493 continue;
494
495 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
496 !New->isCXXClassMember()) {
497 // Ignore default arguments of old decl if they are not in
498 // the same scope and this is not an out-of-line definition of
499 // a member function.
500 continue;
501 }
502
503 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
504 // If only one of these is a local function declaration, then they are
505 // declared in different scopes, even though isDeclInScope may think
506 // they're in the same scope. (If both are local, the scope check is
507 // sufficient, and if neither is local, then they are in the same scope.)
508 continue;
509 }
510
511 // We found the right previous declaration.
512 break;
513 }
514
515 // C++ [dcl.fct.default]p4:
516 // For non-template functions, default arguments can be added in
517 // later declarations of a function in the same
518 // scope. Declarations in different scopes have completely
519 // distinct sets of default arguments. That is, declarations in
520 // inner scopes do not acquire default arguments from
521 // declarations in outer scopes, and vice versa. In a given
522 // function declaration, all parameters subsequent to a
523 // parameter with a default argument shall have default
524 // arguments supplied in this or previous declarations. A
525 // default argument shall not be redefined by a later
526 // declaration (not even to the same value).
527 //
528 // C++ [dcl.fct.default]p6:
529 // Except for member functions of class templates, the default arguments
530 // in a member function definition that appears outside of the class
531 // definition are added to the set of default arguments provided by the
532 // member function declaration in the class definition.
533 for (unsigned p = 0, NumParams = PrevForDefaultArgs
534 ? PrevForDefaultArgs->getNumParams()
535 : 0;
536 p < NumParams; ++p) {
537 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
538 ParmVarDecl *NewParam = New->getParamDecl(p);
539
540 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
541 bool NewParamHasDfl = NewParam->hasDefaultArg();
542
543 if (OldParamHasDfl && NewParamHasDfl) {
544 unsigned DiagDefaultParamID =
545 diag::err_param_default_argument_redefinition;
546
547 // MSVC accepts that default parameters be redefined for member functions
548 // of template class. The new default parameter's value is ignored.
549 Invalid = true;
550 if (getLangOpts().MicrosoftExt) {
551 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
552 if (MD && MD->getParent()->getDescribedClassTemplate()) {
553 // Merge the old default argument into the new parameter.
554 NewParam->setHasInheritedDefaultArg();
555 if (OldParam->hasUninstantiatedDefaultArg())
557 OldParam->getUninstantiatedDefaultArg());
558 else
559 NewParam->setDefaultArg(OldParam->getInit());
560 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
561 Invalid = false;
562 }
563 }
564
565 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
566 // hint here. Alternatively, we could walk the type-source information
567 // for NewParam to find the last source location in the type... but it
568 // isn't worth the effort right now. This is the kind of test case that
569 // is hard to get right:
570 // int f(int);
571 // void g(int (*fp)(int) = f);
572 // void g(int (*fp)(int) = &f);
573 Diag(NewParam->getLocation(), DiagDefaultParamID)
574 << NewParam->getDefaultArgRange();
575
576 // Look for the function declaration where the default argument was
577 // actually written, which may be a declaration prior to Old.
578 for (auto Older = PrevForDefaultArgs;
579 OldParam->hasInheritedDefaultArg(); /**/) {
580 Older = Older->getPreviousDecl();
581 OldParam = Older->getParamDecl(p);
582 }
583
584 Diag(OldParam->getLocation(), diag::note_previous_definition)
585 << OldParam->getDefaultArgRange();
586 } else if (OldParamHasDfl) {
587 // Merge the old default argument into the new parameter unless the new
588 // function is a friend declaration in a template class. In the latter
589 // case the default arguments will be inherited when the friend
590 // declaration will be instantiated.
591 if (New->getFriendObjectKind() == Decl::FOK_None ||
592 !New->getLexicalDeclContext()->isDependentContext()) {
593 // It's important to use getInit() here; getDefaultArg()
594 // strips off any top-level ExprWithCleanups.
595 NewParam->setHasInheritedDefaultArg();
596 if (OldParam->hasUnparsedDefaultArg())
597 NewParam->setUnparsedDefaultArg();
598 else if (OldParam->hasUninstantiatedDefaultArg())
600 OldParam->getUninstantiatedDefaultArg());
601 else
602 NewParam->setDefaultArg(OldParam->getInit());
603 }
604 } else if (NewParamHasDfl) {
605 if (New->getDescribedFunctionTemplate()) {
606 // Paragraph 4, quoted above, only applies to non-template functions.
607 Diag(NewParam->getLocation(),
608 diag::err_param_default_argument_template_redecl)
609 << NewParam->getDefaultArgRange();
610 Diag(PrevForDefaultArgs->getLocation(),
611 diag::note_template_prev_declaration)
612 << false;
613 } else if (New->getTemplateSpecializationKind()
615 New->getTemplateSpecializationKind() != TSK_Undeclared) {
616 // C++ [temp.expr.spec]p21:
617 // Default function arguments shall not be specified in a declaration
618 // or a definition for one of the following explicit specializations:
619 // - the explicit specialization of a function template;
620 // - the explicit specialization of a member function template;
621 // - the explicit specialization of a member function of a class
622 // template where the class template specialization to which the
623 // member function specialization belongs is implicitly
624 // instantiated.
625 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
626 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
627 << New->getDeclName()
628 << NewParam->getDefaultArgRange();
629 } else if (New->getDeclContext()->isDependentContext()) {
630 // C++ [dcl.fct.default]p6 (DR217):
631 // Default arguments for a member function of a class template shall
632 // be specified on the initial declaration of the member function
633 // within the class template.
634 //
635 // Reading the tea leaves a bit in DR217 and its reference to DR205
636 // leads me to the conclusion that one cannot add default function
637 // arguments for an out-of-line definition of a member function of a
638 // dependent type.
639 int WhichKind = 2;
641 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
642 if (Record->getDescribedClassTemplate())
643 WhichKind = 0;
645 WhichKind = 1;
646 else
647 WhichKind = 2;
648 }
649
650 Diag(NewParam->getLocation(),
651 diag::err_param_default_argument_member_template_redecl)
652 << WhichKind
653 << NewParam->getDefaultArgRange();
654 }
655 }
656 }
657
658 // DR1344: If a default argument is added outside a class definition and that
659 // default argument makes the function a special member function, the program
660 // is ill-formed. This can only happen for constructors.
662 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
665 if (NewSM != OldSM) {
666 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
667 assert(NewParam->hasDefaultArg());
668 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
669 << NewParam->getDefaultArgRange() << NewSM;
670 Diag(Old->getLocation(), diag::note_previous_declaration);
671 }
672 }
673
674 const FunctionDecl *Def;
675 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
676 // template has a constexpr specifier then all its declarations shall
677 // contain the constexpr specifier.
678 if (New->getConstexprKind() != Old->getConstexprKind()) {
679 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
680 << New << static_cast<int>(New->getConstexprKind())
681 << static_cast<int>(Old->getConstexprKind());
682 Diag(Old->getLocation(), diag::note_previous_declaration);
683 Invalid = true;
684 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
685 Old->isDefined(Def) &&
686 // If a friend function is inlined but does not have 'inline'
687 // specifier, it is a definition. Do not report attribute conflict
688 // in this case, redefinition will be diagnosed later.
689 (New->isInlineSpecified() ||
690 New->getFriendObjectKind() == Decl::FOK_None)) {
691 // C++11 [dcl.fcn.spec]p4:
692 // If the definition of a function appears in a translation unit before its
693 // first declaration as inline, the program is ill-formed.
694 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
695 Diag(Def->getLocation(), diag::note_previous_definition);
696 Invalid = true;
697 }
698
699 // C++17 [temp.deduct.guide]p3:
700 // Two deduction guide declarations in the same translation unit
701 // for the same class template shall not have equivalent
702 // parameter-declaration-clauses.
704 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
705 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
706 Diag(Old->getLocation(), diag::note_previous_declaration);
707 }
708
709 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
710 // argument expression, that declaration shall be a definition and shall be
711 // the only declaration of the function or function template in the
712 // translation unit.
715 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
716 Diag(Old->getLocation(), diag::note_previous_declaration);
717 Invalid = true;
718 }
719
720 // C++11 [temp.friend]p4 (DR329):
721 // When a function is defined in a friend function declaration in a class
722 // template, the function is instantiated when the function is odr-used.
723 // The same restrictions on multiple declarations and definitions that
724 // apply to non-template function declarations and definitions also apply
725 // to these implicit definitions.
726 const FunctionDecl *OldDefinition = nullptr;
727 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
728 Old->isDefined(OldDefinition, true))
729 CheckForFunctionRedefinition(New, OldDefinition);
730
731 return Invalid;
732}
733
736 ? diag::warn_cxx23_placeholder_var_definition
737 : diag::ext_placeholder_var_definition);
738}
739
740NamedDecl *
742 MultiTemplateParamsArg TemplateParamLists) {
743 assert(D.isDecompositionDeclarator());
745
746 // The syntax only allows a decomposition declarator as a simple-declaration,
747 // a for-range-declaration, or a condition in Clang, but we parse it in more
748 // cases than that.
750 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
751 << Decomp.getSourceRange();
752 return nullptr;
753 }
754
755 if (!TemplateParamLists.empty()) {
756 // C++17 [temp]/1:
757 // A template defines a family of class, functions, or variables, or an
758 // alias for a family of types.
759 //
760 // Structured bindings are not included.
761 Diag(TemplateParamLists.front()->getTemplateLoc(),
762 diag::err_decomp_decl_template);
763 return nullptr;
764 }
765
766 unsigned DiagID;
768 DiagID = diag::compat_pre_cxx17_decomp_decl;
770 DiagID = getLangOpts().CPlusPlus26
771 ? diag::compat_cxx26_decomp_decl_cond
772 : diag::compat_pre_cxx26_decomp_decl_cond;
773 else
774 DiagID = diag::compat_cxx17_decomp_decl;
775
776 Diag(Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
777
778 // The semantic context is always just the current context.
779 DeclContext *const DC = CurContext;
780
781 // C++17 [dcl.dcl]/8:
782 // The decl-specifier-seq shall contain only the type-specifier auto
783 // and cv-qualifiers.
784 // C++20 [dcl.dcl]/8:
785 // If decl-specifier-seq contains any decl-specifier other than static,
786 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
787 // C++23 [dcl.pre]/6:
788 // Each decl-specifier in the decl-specifier-seq shall be static,
789 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
790 // C++23 [dcl.pre]/7:
791 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
792 // constinit, static, thread_local, auto, or a cv-qualifier
793 auto &DS = D.getDeclSpec();
794 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
795 Diag(Loc, diag::err_decomp_decl_spec) << Name;
796 };
797
798 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
799 DiagCompat(Loc, diag_compat::decomp_decl_spec) << Name;
800 };
801
802 if (auto SCS = DS.getStorageClassSpec()) {
803 if (SCS == DeclSpec::SCS_static)
804 DiagCpp20Specifier(DeclSpec::getSpecifierName(SCS),
805 DS.getStorageClassSpecLoc());
806 else
807 DiagBadSpecifier(DeclSpec::getSpecifierName(SCS),
808 DS.getStorageClassSpecLoc());
809 }
810 if (auto TSCS = DS.getThreadStorageClassSpec())
811 DiagCpp20Specifier(DeclSpec::getSpecifierName(TSCS),
812 DS.getThreadStorageClassSpecLoc());
813
814 if (DS.isInlineSpecified())
815 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
816
817 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
818 ConstexprSpec != ConstexprSpecKind::Unspecified) {
819 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
821 DiagBadSpecifier(DeclSpec::getSpecifierName(ConstexprSpec),
822 DS.getConstexprSpecLoc());
823 }
824
825 // We can't recover from it being declared as a typedef.
826 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
827 return nullptr;
828
829 // C++2a [dcl.struct.bind]p1:
830 // A cv that includes volatile is deprecated
831 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
833 Diag(DS.getVolatileSpecLoc(),
834 diag::warn_deprecated_volatile_structured_binding);
835
837 QualType R = TInfo->getType();
838
841 D.setInvalidType();
842
843 // The syntax only allows a single ref-qualifier prior to the decomposition
844 // declarator. No other declarator chunks are permitted. Also check the type
845 // specifier here.
846 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
847 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
848 (D.getNumTypeObjects() == 1 &&
850 Diag(Decomp.getLSquareLoc(),
851 (D.hasGroupingParens() ||
852 (D.getNumTypeObjects() &&
854 ? diag::err_decomp_decl_parens
855 : diag::err_decomp_decl_type)
856 << R;
857
858 // In most cases, there's no actual problem with an explicitly-specified
859 // type, but a function type won't work here, and ActOnVariableDeclarator
860 // shouldn't be called for such a type.
861 if (R->isFunctionType())
862 D.setInvalidType();
863 }
864
865 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
866 if (DS.isConstrainedAuto()) {
867 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
868 assert(TemplRep->Kind == TNK_Concept_template &&
869 "No other template kind should be possible for a constrained auto");
870
871 SourceRange TemplRange{TemplRep->TemplateNameLoc,
872 TemplRep->RAngleLoc.isValid()
873 ? TemplRep->RAngleLoc
874 : TemplRep->TemplateNameLoc};
875 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
876 << TemplRange << FixItHint::CreateRemoval(TemplRange);
877 }
878
879 // Build the BindingDecls.
881
882 // Build the BindingDecls.
883 for (auto &B : D.getDecompositionDeclarator().bindings()) {
884 // Check for name conflicts.
885 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
886 IdentifierInfo *VarName = B.Name;
887 assert(VarName && "Cannot have an unnamed binding declaration");
888
892 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
893
894 // It's not permitted to shadow a template parameter name.
895 if (Previous.isSingleResult() &&
896 Previous.getFoundDecl()->isTemplateParameter()) {
897 DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());
898 Previous.clear();
899 }
900
901 QualType QT;
902 if (B.EllipsisLoc.isValid()) {
903 if (!cast<Decl>(DC)->isTemplated())
904 Diag(B.EllipsisLoc, diag::err_pack_outside_template);
905 QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,
906 /*ExpectsPackInType=*/false);
907 }
908
909 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
910
911 ProcessDeclAttributeList(S, BD, *B.Attrs);
912
913 // Find the shadowed declaration before filtering for scope.
914 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
916 : nullptr;
917
918 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
919 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
920 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
921 /*AllowInlineNamespace*/false);
922
923 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
924 DC->isFunctionOrMethod() && VarName->isPlaceholder();
925 if (!Previous.empty()) {
926 if (IsPlaceholder) {
927 bool sameDC = (Previous.end() - 1)
928 ->getDeclContext()
929 ->getRedeclContext()
930 ->Equals(DC->getRedeclContext());
931 if (sameDC &&
932 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
933 Previous.clear();
935 }
936 } else {
937 auto *Old = Previous.getRepresentativeDecl();
938 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
939 Diag(Old->getLocation(), diag::note_previous_definition);
940 }
941 } else if (ShadowedDecl && !D.isRedeclaration()) {
942 CheckShadow(BD, ShadowedDecl, Previous);
943 }
944 PushOnScopeChains(BD, S, true);
945 Bindings.push_back(BD);
946 ParsingInitForAutoVars.insert(BD);
947 }
948
949 // There are no prior lookup results for the variable itself, because it
950 // is unnamed.
951 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
952 Decomp.getLSquareLoc());
955
956 // Build the variable that holds the non-decomposed object.
957 bool AddToScope = true;
958 NamedDecl *New =
959 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
960 MultiTemplateParamsArg(), AddToScope, Bindings);
961 if (AddToScope) {
962 S->AddDecl(New);
963 CurContext->addHiddenDecl(New);
964 }
965
966 if (OpenMP().isInOpenMPDeclareTargetContext())
967 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
968
969 return New;
970}
971
972// Check the arity of the structured bindings.
973// Create the resolved pack expr if needed.
975 QualType DecompType,
977 unsigned MemberCount) {
978 auto BindingWithPackItr = llvm::find_if(
979 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
980 bool HasPack = BindingWithPackItr != Bindings.end();
981 bool IsValid;
982 if (!HasPack) {
983 IsValid = Bindings.size() == MemberCount;
984 } else {
985 // There may not be more members than non-pack bindings.
986 IsValid = MemberCount >= Bindings.size() - 1;
987 }
988
989 if (IsValid && HasPack) {
990 // Create the pack expr and assign it to the binding.
991 unsigned PackSize = MemberCount - Bindings.size() + 1;
992
993 BindingDecl *BPack = *BindingWithPackItr;
994 BPack->setDecomposedDecl(DD);
995 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
996 // Create the nested BindingDecls.
997 for (unsigned I = 0; I < PackSize; ++I) {
999 S.Context, BPack->getDeclContext(), BPack->getLocation(),
1000 BPack->getIdentifier(), QualType());
1001 NestedBD->setDecomposedDecl(DD);
1002 NestedBDs[I] = NestedBD;
1003 }
1004
1006 S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);
1007 auto *PackExpr = FunctionParmPackExpr::Create(
1008 S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);
1009 BPack->setBinding(PackType, PackExpr);
1010 }
1011
1012 if (IsValid)
1013 return false;
1014
1015 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1016 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1017 << (MemberCount < Bindings.size());
1018 return true;
1019}
1020
1023 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1024 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1025 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1026 auto *DD = cast<DecompositionDecl>(Src);
1027
1028 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1029 return true;
1030
1031 unsigned I = 0;
1032 for (auto *B : DD->flat_bindings()) {
1033 SourceLocation Loc = B->getLocation();
1034 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1035 if (E.isInvalid())
1036 return true;
1037 E = GetInit(Loc, E.get(), I++);
1038 if (E.isInvalid())
1039 return true;
1040 B->setBinding(ElemType, E.get());
1041 }
1042
1043 return false;
1044}
1045
1048 ValueDecl *Src, QualType DecompType,
1049 const llvm::APSInt &NumElems,
1050 QualType ElemType) {
1052 S, Bindings, Src, DecompType, NumElems, ElemType,
1053 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1054 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1055 if (E.isInvalid())
1056 return ExprError();
1057 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1058 });
1059}
1060
1062 ValueDecl *Src, QualType DecompType,
1063 const ConstantArrayType *CAT) {
1064 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1065 llvm::APSInt(CAT->getSize()),
1066 CAT->getElementType());
1067}
1068
1070 ValueDecl *Src, QualType DecompType,
1071 const VectorType *VT) {
1073 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1075 DecompType.getQualifiers()));
1076}
1077
1080 ValueDecl *Src, QualType DecompType,
1081 const ComplexType *CT) {
1083 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1085 DecompType.getQualifiers()),
1086 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1087 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1088 });
1089}
1090
1093 const TemplateParameterList *Params) {
1095 llvm::raw_svector_ostream OS(SS);
1096 bool First = true;
1097 unsigned I = 0;
1098 for (auto &Arg : Args.arguments()) {
1099 if (!First)
1100 OS << ", ";
1101 Arg.getArgument().print(PrintingPolicy, OS,
1103 PrintingPolicy, Params, I));
1104 First = false;
1105 I++;
1106 }
1107 return std::string(OS.str());
1108}
1109
1110static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1111 TemplateArgumentListInfo &Args, unsigned DiagID) {
1112 auto DiagnoseMissing = [&] {
1113 if (DiagID)
1114 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1115 Args, /*Params*/ nullptr);
1116 return QualType();
1117 };
1118
1119 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1120 NamespaceDecl *Std = S.getStdNamespace();
1121 if (!Std)
1122 return DiagnoseMissing();
1123
1124 // Look up the trait itself, within namespace std. We can diagnose various
1125 // problems with this lookup even if we've been asked to not diagnose a
1126 // missing specialization, because this can only fail if the user has been
1127 // declaring their own names in namespace std or we don't support the
1128 // standard library implementation in use.
1129 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), Loc,
1131 if (!S.LookupQualifiedName(Result, Std))
1132 return DiagnoseMissing();
1133 if (Result.isAmbiguous())
1134 return QualType();
1135
1136 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1137 if (!TraitTD) {
1138 Result.suppressDiagnostics();
1139 NamedDecl *Found = *Result.begin();
1140 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1141 S.Diag(Found->getLocation(), diag::note_declared_at);
1142 return QualType();
1143 }
1144
1145 // Build the template-id.
1146 QualType TraitTy = S.CheckTemplateIdType(
1147 ElaboratedTypeKeyword::None, TemplateName(TraitTD), Loc, Args,
1148 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1149 if (TraitTy.isNull())
1150 return QualType();
1151
1152 if (!S.isCompleteType(Loc, TraitTy)) {
1153 if (DiagID)
1155 Loc, TraitTy, DiagID,
1157 TraitTD->getTemplateParameters()));
1158 return QualType();
1159 }
1160 return TraitTy;
1161}
1162
1163static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1164 LookupResult &MemberLookup) {
1165 assert(RD && "specialization of class template is not a class?");
1166 S.LookupQualifiedName(MemberLookup, RD);
1167 return MemberLookup.isAmbiguous();
1168}
1169
1170static TemplateArgumentLoc
1172 uint64_t I) {
1173 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1174 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1175}
1176
1177static TemplateArgumentLoc
1181
1182namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1183
1184static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1185 unsigned &OutSize) {
1188
1189 // Form template argument list for tuple_size<T>.
1190 TemplateArgumentListInfo Args(Loc, Loc);
1192
1193 QualType TraitTy = getStdTrait(S, Loc, "tuple_size", Args, /*DiagID=*/0);
1194 if (TraitTy.isNull())
1195 return IsTupleLike::NotTupleLike;
1196
1199
1200 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1201 // it's not tuple-like.
1202 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R) || R.empty())
1203 return IsTupleLike::NotTupleLike;
1204
1205 // If we get this far, we've committed to the tuple interpretation, but
1206 // we can still fail if there actually isn't a usable ::value.
1207
1208 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1209 LookupResult &R;
1211 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1212 : R(R), Args(Args) {}
1213 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1214 SourceLocation Loc) override {
1215 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1217 /*Params*/ nullptr);
1218 }
1219 } Diagnoser(R, Args);
1220
1221 ExprResult E =
1222 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1223 if (E.isInvalid())
1224 return IsTupleLike::Error;
1225
1226 llvm::APSInt Size;
1227 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1228 if (E.isInvalid())
1229 return IsTupleLike::Error;
1230
1231 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1232 // an UnsignedOrNone.
1233 if (Size < 0 || Size >= UINT_MAX) {
1235 Size.toString(Str);
1236 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_invalid)
1238 /*Params=*/nullptr)
1239 << StringRef(Str.data(), Str.size());
1240 return IsTupleLike::Error;
1241 }
1242
1243 OutSize = Size.getExtValue();
1244 return IsTupleLike::TupleLike;
1245}
1246
1247/// \return std::tuple_element<I, T>::type.
1249 unsigned I, QualType T) {
1250 // Form template argument list for tuple_element<I, T>.
1251 TemplateArgumentListInfo Args(Loc, Loc);
1252 Args.addArgument(
1255
1256 QualType TraitTy =
1257 getStdTrait(S, Loc, "tuple_element", Args,
1258 diag::err_decomp_decl_std_tuple_element_not_specialized);
1259 if (TraitTy.isNull())
1260 return QualType();
1261
1262 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1263 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1264 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R))
1265 return QualType();
1266
1267 auto *TD = R.getAsSingle<TypeDecl>();
1268 if (!TD) {
1269 R.suppressDiagnostics();
1270 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1272 /*Params*/ nullptr);
1273 if (!R.empty())
1274 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1275 return QualType();
1276 }
1277
1278 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1279 return S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, Qualifier, TD);
1280}
1281
1282namespace {
1283struct InitializingBinding {
1284 Sema &S;
1285 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1286 Sema::CodeSynthesisContext Ctx;
1289 Ctx.Entity = BD;
1291 }
1292 ~InitializingBinding() {
1294 }
1295};
1296}
1297
1300 VarDecl *Src, QualType DecompType,
1301 unsigned NumElems) {
1302 auto *DD = cast<DecompositionDecl>(Src);
1303 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1304 return true;
1305
1306 if (Bindings.empty())
1307 return false;
1308
1309 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1310
1311 // [dcl.decomp]p3:
1312 // The unqualified-id get is looked up in the scope of E by class member
1313 // access lookup ...
1314 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1315 bool UseMemberGet = false;
1316 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1317 if (auto *RD = DecompType->getAsCXXRecordDecl())
1318 S.LookupQualifiedName(MemberGet, RD);
1319 if (MemberGet.isAmbiguous())
1320 return true;
1321 // ... and if that finds at least one declaration that is a function
1322 // template whose first template parameter is a non-type parameter ...
1323 for (NamedDecl *D : MemberGet) {
1324 if (FunctionTemplateDecl *FTD =
1325 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1326 TemplateParameterList *TPL = FTD->getTemplateParameters();
1327 if (TPL->size() != 0 &&
1329 // ... the initializer is e.get<i>().
1330 UseMemberGet = true;
1331 break;
1332 }
1333 }
1334 }
1335 }
1336
1337 unsigned I = 0;
1338 for (auto *B : DD->flat_bindings()) {
1339 InitializingBinding InitContext(S, B);
1340 SourceLocation Loc = B->getLocation();
1341
1342 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1343 if (E.isInvalid())
1344 return true;
1345
1346 // e is an lvalue if the type of the entity is an lvalue reference and
1347 // an xvalue otherwise
1348 if (!Src->getType()->isLValueReferenceType())
1349 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1350 E.get(), nullptr, VK_XValue,
1352
1353 TemplateArgumentListInfo Args(Loc, Loc);
1354 Args.addArgument(
1356
1357 if (UseMemberGet) {
1358 // if [lookup of member get] finds at least one declaration, the
1359 // initializer is e.get<i-1>().
1360 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1361 CXXScopeSpec(), SourceLocation(), nullptr,
1362 MemberGet, &Args, nullptr);
1363 if (E.isInvalid())
1364 return true;
1365
1366 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1367 } else {
1368 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1369 // in the associated namespaces.
1372 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1374 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1375
1376 Expr *Arg = E.get();
1377 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1378 }
1379 if (E.isInvalid())
1380 return true;
1381 Expr *Init = E.get();
1382
1383 // Given the type T designated by std::tuple_element<i - 1, E>::type
1384 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1385 if (T.isNull())
1386 return true;
1387
1388 // C++26 [dcl.struct.bind]p7:
1389 // and the type Ui, defined as Ti if the initializer is a prvalue,
1390 // as "lvalue reference to Ti" if the initializer is an lvalue,
1391 // or as "rvalue reference to Ti" otherwise
1392 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1393 QualType U = E.get()->isPRValue()
1394 ? T
1395 : S.BuildReferenceType(T, E.get()->isLValue(), Loc,
1396 B->getDeclName());
1397 if (U.isNull())
1398 return true;
1399
1400 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1401 // entity and this type was never written in source code.
1402 auto *BindingVD =
1403 VarDecl::Create(S.Context, Src->getDeclContext(), Loc, Loc,
1404 B->getDeclName().getAsIdentifierInfo(), U,
1405 /*TInfo=*/nullptr, Src->getStorageClass());
1406 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1407 BindingVD->setTSCSpec(Src->getTSCSpec());
1408 BindingVD->setConstexpr(Src->isConstexpr());
1409 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1410 BindingVD->addAttr(CIAttr->clone(S.Context));
1411 BindingVD->setImplicit();
1412 if (Src->isInlineSpecified())
1413 BindingVD->setInlineSpecified();
1414 BindingVD->getLexicalDeclContext()->addHiddenDecl(BindingVD);
1415
1418 InitializationSequence Seq(S, Entity, Kind, Init);
1419 E = Seq.Perform(S, Entity, Kind, Init);
1420 if (E.isInvalid())
1421 return true;
1422 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1423 if (E.isInvalid())
1424 return true;
1425 BindingVD->setInit(E.get());
1427
1429 CXXScopeSpec(), DeclarationNameInfo(B->getDeclName(), Loc), BindingVD);
1430 if (E.isInvalid())
1431 return true;
1432
1433 B->setBinding(T, E.get());
1434 I++;
1435 }
1436
1437 return false;
1438}
1439
1440/// Find the base class to decompose in a built-in decomposition of a class type.
1441/// This base class search is, unfortunately, not quite like any other that we
1442/// perform anywhere else in C++.
1444 const CXXRecordDecl *RD,
1445 CXXCastPath &BasePath) {
1446 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1447 CXXBasePath &Path) {
1448 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1449 };
1450
1451 const CXXRecordDecl *ClassWithFields = nullptr;
1453 if (RD->hasDirectFields())
1454 // [dcl.decomp]p4:
1455 // Otherwise, all of E's non-static data members shall be public direct
1456 // members of E ...
1457 ClassWithFields = RD;
1458 else {
1459 // ... or of ...
1460 CXXBasePaths Paths;
1461 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1462 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1463 // If no classes have fields, just decompose RD itself. (This will work
1464 // if and only if zero bindings were provided.)
1465 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1466 }
1467
1468 CXXBasePath *BestPath = nullptr;
1469 for (auto &P : Paths) {
1470 if (!BestPath)
1471 BestPath = &P;
1472 else if (!S.Context.hasSameType(P.back().Base->getType(),
1473 BestPath->back().Base->getType())) {
1474 // ... the same ...
1475 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1476 << false << RD << BestPath->back().Base->getType()
1477 << P.back().Base->getType();
1478 return DeclAccessPair();
1479 } else if (P.Access < BestPath->Access) {
1480 BestPath = &P;
1481 }
1482 }
1483
1484 // ... unambiguous ...
1485 QualType BaseType = BestPath->back().Base->getType();
1486 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1487 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1488 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1489 return DeclAccessPair();
1490 }
1491
1492 // ... [accessible, implied by other rules] base class of E.
1493 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getCanonicalTagType(RD),
1494 *BestPath, diag::err_decomp_decl_inaccessible_base);
1495 AS = BestPath->Access;
1496
1497 ClassWithFields = BaseType->getAsCXXRecordDecl();
1498 S.BuildBasePathArray(Paths, BasePath);
1499 }
1500
1501 // The above search did not check whether the selected class itself has base
1502 // classes with fields, so check that now.
1503 CXXBasePaths Paths;
1504 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1505 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1506 << (ClassWithFields == RD) << RD << ClassWithFields
1507 << Paths.front().back().Base->getType();
1508 return DeclAccessPair();
1509 }
1510
1511 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1512}
1513
1515 const CXXRecordDecl *OrigRD,
1516 QualType DecompType,
1517 DeclAccessPair BasePair) {
1518 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1519 if (!RD)
1520 return true;
1521
1522 for (auto *FD : RD->fields()) {
1523 if (FD->isUnnamedBitField())
1524 continue;
1525
1526 // All the non-static data members are required to be nameable, so they
1527 // must all have names.
1528 if (!FD->getDeclName()) {
1529 if (RD->isLambda()) {
1530 S.Diag(Loc, diag::err_decomp_decl_lambda);
1531 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1532 return true;
1533 }
1534
1535 if (FD->isAnonymousStructOrUnion()) {
1536 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1537 << DecompType << FD->getType()->isUnionType();
1538 S.Diag(FD->getLocation(), diag::note_declared_at);
1539 return true;
1540 }
1541
1542 // FIXME: Are there any other ways we could have an anonymous member?
1543 }
1544 // The field must be accessible in the context of the structured binding.
1545 // We already checked that the base class is accessible.
1546 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1547 // const_cast here.
1549 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1551 BasePair.getAccess(), FD->getAccess())));
1552 }
1553 return false;
1554}
1555
1557 ValueDecl *Src, QualType DecompType,
1558 const CXXRecordDecl *OrigRD) {
1559 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1560 diag::err_incomplete_type))
1561 return true;
1562
1563 CXXCastPath BasePath;
1564 DeclAccessPair BasePair =
1565 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1566 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1567 if (!RD)
1568 return true;
1569 QualType BaseType = S.Context.getQualifiedType(
1570 S.Context.getCanonicalTagType(RD), DecompType.getQualifiers());
1571
1572 auto *DD = cast<DecompositionDecl>(Src);
1573 unsigned NumFields = llvm::count_if(
1574 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1575 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))
1576 return true;
1577
1578 // all of E's non-static data members shall be [...] well-formed
1579 // when named as e.name in the context of the structured binding,
1580 // E shall not have an anonymous union member, ...
1581 auto FlatBindings = DD->flat_bindings();
1582 assert(llvm::range_size(FlatBindings) == NumFields);
1583 auto FlatBindingsItr = FlatBindings.begin();
1584
1585 if (CheckMemberDecompositionFields(S, Src->getLocation(), OrigRD, DecompType,
1586 BasePair))
1587 return true;
1588
1589 for (auto *FD : RD->fields()) {
1590 if (FD->isUnnamedBitField())
1591 continue;
1592
1593 // We have a real field to bind.
1594 assert(FlatBindingsItr != FlatBindings.end());
1595 BindingDecl *B = *(FlatBindingsItr++);
1596 SourceLocation Loc = B->getLocation();
1597
1598 // Initialize the binding to Src.FD.
1599 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1600 if (E.isInvalid())
1601 return true;
1602 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1603 VK_LValue, &BasePath);
1604 if (E.isInvalid())
1605 return true;
1606 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1607 CXXScopeSpec(), FD,
1609 DeclarationNameInfo(FD->getDeclName(), Loc));
1610 if (E.isInvalid())
1611 return true;
1612
1613 // If the type of the member is T, the referenced type is cv T, where cv is
1614 // the cv-qualification of the decomposition expression.
1615 //
1616 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1617 // 'const' to the type of the field.
1618 Qualifiers Q = DecompType.getQualifiers();
1619 if (FD->isMutable())
1620 Q.removeConst();
1621 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1622 }
1623
1624 return false;
1625}
1626
1628 QualType DecompType = DD->getType();
1629
1630 // If the type of the decomposition is dependent, then so is the type of
1631 // each binding.
1632 if (DecompType->isDependentType()) {
1633 // Note that all of the types are still Null or PackExpansionType.
1634 for (auto *B : DD->bindings()) {
1635 // Do not overwrite any pack type.
1636 if (B->getType().isNull())
1637 B->setType(Context.DependentTy);
1638 }
1639 return;
1640 }
1641
1642 DecompType = DecompType.getNonReferenceType();
1644
1645 // C++1z [dcl.decomp]/2:
1646 // If E is an array type [...]
1647 // As an extension, we also support decomposition of built-in complex and
1648 // vector types.
1649 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1650 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1651 DD->setInvalidDecl();
1652 return;
1653 }
1654 if (auto *VT = DecompType->getAs<VectorType>()) {
1655 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1656 DD->setInvalidDecl();
1657 return;
1658 }
1659 if (auto *CT = DecompType->getAs<ComplexType>()) {
1660 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1661 DD->setInvalidDecl();
1662 return;
1663 }
1664
1665 // C++1z [dcl.decomp]/3:
1666 // if the expression std::tuple_size<E>::value is a well-formed integral
1667 // constant expression, [...]
1668 unsigned TupleSize;
1669 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1670 case IsTupleLike::Error:
1671 DD->setInvalidDecl();
1672 return;
1673
1674 case IsTupleLike::TupleLike:
1675 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1676 DD->setInvalidDecl();
1677 return;
1678
1679 case IsTupleLike::NotTupleLike:
1680 break;
1681 }
1682
1683 // C++1z [dcl.dcl]/8:
1684 // [E shall be of array or non-union class type]
1685 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1686 if (!RD || RD->isUnion()) {
1687 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1688 << DD << !RD << DecompType;
1689 DD->setInvalidDecl();
1690 return;
1691 }
1692
1693 // C++1z [dcl.decomp]/4:
1694 // all of E's non-static data members shall be [...] direct members of
1695 // E or of the same unambiguous public base class of E, ...
1696 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1697 DD->setInvalidDecl();
1698}
1699
1701 SourceLocation Loc) {
1702 const ASTContext &Ctx = getASTContext();
1703 assert(!T->isDependentType());
1704
1705 Qualifiers Quals;
1706 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1707 Quals.removeCVRQualifiers();
1708 T = Context.getQualifiedType(Unqual, Quals);
1709
1710 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1711 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1712 if (auto *VT = T->getAs<VectorType>())
1713 return VT->getNumElements();
1714 if (T->getAs<ComplexType>())
1715 return 2u;
1716
1717 unsigned TupleSize;
1718 switch (isTupleLike(*this, Loc, T, TupleSize)) {
1719 case IsTupleLike::Error:
1720 return std::nullopt;
1721 case IsTupleLike::TupleLike:
1722 return TupleSize;
1723 case IsTupleLike::NotTupleLike:
1724 break;
1725 }
1726
1727 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1728 if (!OrigRD || OrigRD->isUnion())
1729 return std::nullopt;
1730
1731 if (RequireCompleteType(Loc, T, diag::err_incomplete_type))
1732 return std::nullopt;
1733
1734 CXXCastPath BasePath;
1735 DeclAccessPair BasePair =
1736 findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);
1737 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1738 if (!RD)
1739 return std::nullopt;
1740
1741 unsigned NumFields = llvm::count_if(
1742 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1743
1744 if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))
1745 return std::nullopt;
1746
1747 return NumFields;
1748}
1749
1751 // Shortcut if exceptions are disabled.
1752 if (!getLangOpts().CXXExceptions)
1753 return;
1754
1755 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1756 "Should only be called if types are otherwise the same.");
1757
1758 QualType NewType = New->getType();
1759 QualType OldType = Old->getType();
1760
1761 // We're only interested in pointers and references to functions, as well
1762 // as pointers to member functions.
1763 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1764 NewType = R->getPointeeType();
1765 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1766 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1767 NewType = P->getPointeeType();
1768 OldType = OldType->castAs<PointerType>()->getPointeeType();
1769 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1770 NewType = M->getPointeeType();
1771 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1772 }
1773
1774 if (!NewType->isFunctionProtoType())
1775 return;
1776
1777 // There's lots of special cases for functions. For function pointers, system
1778 // libraries are hopefully not as broken so that we don't need these
1779 // workarounds.
1781 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1782 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1783 New->setInvalidDecl();
1784 }
1785}
1786
1787/// CheckCXXDefaultArguments - Verify that the default arguments for a
1788/// function declaration are well-formed according to C++
1789/// [dcl.fct.default].
1791 // This checking doesn't make sense for explicit specializations; their
1792 // default arguments are determined by the declaration we're specializing,
1793 // not by FD.
1795 return;
1796 if (auto *FTD = FD->getDescribedFunctionTemplate())
1797 if (FTD->isMemberSpecialization())
1798 return;
1799
1800 unsigned NumParams = FD->getNumParams();
1801 unsigned ParamIdx = 0;
1802
1803 // Find first parameter with a default argument
1804 for (; ParamIdx < NumParams; ++ParamIdx) {
1805 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1806 if (Param->hasDefaultArg())
1807 break;
1808 }
1809
1810 // C++20 [dcl.fct.default]p4:
1811 // In a given function declaration, each parameter subsequent to a parameter
1812 // with a default argument shall have a default argument supplied in this or
1813 // a previous declaration, unless the parameter was expanded from a
1814 // parameter pack, or shall be a function parameter pack.
1815 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1816 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1817 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1819 CurrentInstantiationScope->isLocalPackExpansion(Param)))
1820 continue;
1821 if (Param->isInvalidDecl())
1822 /* We already complained about this parameter. */;
1823 else if (Param->getIdentifier())
1824 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1825 << Param->getIdentifier();
1826 else
1827 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1828 }
1829}
1830
1831/// Check that the given type is a literal type. Issue a diagnostic if not,
1832/// if Kind is Diagnose.
1833/// \return \c true if a problem has been found (and optionally diagnosed).
1834template <typename... Ts>
1836 SourceLocation Loc, QualType T, unsigned DiagID,
1837 Ts &&...DiagArgs) {
1838 if (T->isDependentType())
1839 return false;
1840
1841 switch (Kind) {
1843 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1844 std::forward<Ts>(DiagArgs)...);
1845
1847 return !T->isLiteralType(SemaRef.Context);
1848 }
1849
1850 llvm_unreachable("unknown CheckConstexprKind");
1851}
1852
1853/// Determine whether a destructor cannot be constexpr due to
1855 const CXXDestructorDecl *DD,
1857 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1858 "this check is obsolete for C++23");
1859 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1860 const CXXRecordDecl *RD =
1861 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1862 if (!RD || RD->hasConstexprDestructor())
1863 return true;
1864
1866 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1867 << static_cast<int>(DD->getConstexprKind()) << !FD
1868 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1869 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1870 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1871 }
1872 return false;
1873 };
1874
1875 const CXXRecordDecl *RD = DD->getParent();
1876 for (const CXXBaseSpecifier &B : RD->bases())
1877 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1878 return false;
1879 for (const FieldDecl *FD : RD->fields())
1880 if (!Check(FD->getLocation(), FD->getType(), FD))
1881 return false;
1882 return true;
1883}
1884
1885/// Check whether a function's parameter types are all literal types. If so,
1886/// return true. If not, produce a suitable diagnostic and return false.
1888 const FunctionDecl *FD,
1890 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1891 "this check is obsolete for C++23");
1892 unsigned ArgIndex = 0;
1893 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1894 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1895 e = FT->param_type_end();
1896 i != e; ++i, ++ArgIndex) {
1897 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1898 assert(PD && "null in a parameter list");
1899 SourceLocation ParamLoc = PD->getLocation();
1900 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1901 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1903 FD->isConsteval()))
1904 return false;
1905 }
1906 return true;
1907}
1908
1909/// Check whether a function's return type is a literal type. If so, return
1910/// true. If not, produce a suitable diagnostic and return false.
1911static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1913 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1914 "this check is obsolete for C++23");
1915 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1916 diag::err_constexpr_non_literal_return,
1917 FD->isConsteval()))
1918 return false;
1919 return true;
1920}
1921
1922/// Get diagnostic %select index for tag kind for
1923/// record diagnostic message.
1924/// WARNING: Indexes apply to particular diagnostics only!
1925///
1926/// \returns diagnostic %select index.
1928 switch (Tag) {
1930 return 0;
1932 return 1;
1933 case TagTypeKind::Class:
1934 return 2;
1935 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1936 }
1937}
1938
1939static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1940 Stmt *Body,
1942static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1943
1945 CheckConstexprKind Kind) {
1946 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1947 if (MD && MD->isInstance()) {
1948 // C++11 [dcl.constexpr]p4:
1949 // The definition of a constexpr constructor shall satisfy the following
1950 // constraints:
1951 // - the class shall not have any virtual base classes;
1952 //
1953 // FIXME: This only applies to constructors and destructors, not arbitrary
1954 // member functions.
1955 const CXXRecordDecl *RD = MD->getParent();
1956 if (RD->getNumVBases()) {
1958 return false;
1959
1960 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1961 << isa<CXXConstructorDecl>(NewFD)
1963 for (const auto &I : RD->vbases())
1964 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1965 << I.getSourceRange();
1966 return false;
1967 }
1968 }
1969
1970 if (!isa<CXXConstructorDecl>(NewFD)) {
1971 // C++11 [dcl.constexpr]p3:
1972 // The definition of a constexpr function shall satisfy the following
1973 // constraints:
1974 // - it shall not be virtual; (removed in C++20)
1975 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1976 if (Method && Method->isVirtual()) {
1977 if (getLangOpts().CPlusPlus20) {
1978 if (Kind == CheckConstexprKind::Diagnose)
1979 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1980 } else {
1982 return false;
1983
1984 Method = Method->getCanonicalDecl();
1985 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1986
1987 // If it's not obvious why this function is virtual, find an overridden
1988 // function which uses the 'virtual' keyword.
1989 const CXXMethodDecl *WrittenVirtual = Method;
1990 while (!WrittenVirtual->isVirtualAsWritten())
1991 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1992 if (WrittenVirtual != Method)
1993 Diag(WrittenVirtual->getLocation(),
1994 diag::note_overridden_virtual_function);
1995 return false;
1996 }
1997 }
1998
1999 // - its return type shall be a literal type; (removed in C++23)
2000 if (!getLangOpts().CPlusPlus23 &&
2001 !CheckConstexprReturnType(*this, NewFD, Kind))
2002 return false;
2003 }
2004
2005 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
2006 // A destructor can be constexpr only if the defaulted destructor could be;
2007 // we don't need to check the members and bases if we already know they all
2008 // have constexpr destructors. (removed in C++23)
2009 if (!getLangOpts().CPlusPlus23 &&
2010 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2012 return false;
2013 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
2014 return false;
2015 }
2016 }
2017
2018 // - each of its parameter types shall be a literal type; (removed in C++23)
2019 if (!getLangOpts().CPlusPlus23 &&
2020 !CheckConstexprParameterTypes(*this, NewFD, Kind))
2021 return false;
2022
2023 Stmt *Body = NewFD->getBody();
2024 assert(Body &&
2025 "CheckConstexprFunctionDefinition called on function with no body");
2026 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
2027}
2028
2029/// Check the given declaration statement is legal within a constexpr function
2030/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2031///
2032/// \return true if the body is OK (maybe only as an extension), false if we
2033/// have diagnosed a problem.
2034static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2035 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2037 // C++11 [dcl.constexpr]p3 and p4:
2038 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2039 // contain only
2040 for (const auto *DclIt : DS->decls()) {
2041 switch (DclIt->getKind()) {
2042 case Decl::StaticAssert:
2043 case Decl::Using:
2044 case Decl::UsingShadow:
2045 case Decl::UsingDirective:
2046 case Decl::UnresolvedUsingTypename:
2047 case Decl::UnresolvedUsingValue:
2048 case Decl::UsingEnum:
2049 // - static_assert-declarations
2050 // - using-declarations,
2051 // - using-directives,
2052 // - using-enum-declaration
2053 continue;
2054
2055 case Decl::Typedef:
2056 case Decl::TypeAlias: {
2057 // - typedef declarations and alias-declarations that do not define
2058 // classes or enumerations,
2059 const auto *TN = cast<TypedefNameDecl>(DclIt);
2060 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2061 // Don't allow variably-modified types in constexpr functions.
2063 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2064 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
2065 << TL.getSourceRange() << TL.getType()
2067 }
2068 return false;
2069 }
2070 continue;
2071 }
2072
2073 case Decl::Enum:
2074 case Decl::CXXRecord:
2075 // C++1y allows types to be defined, not just declared.
2076 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
2078 SemaRef.DiagCompat(DS->getBeginLoc(),
2079 diag_compat::constexpr_type_definition)
2081 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2082 return false;
2083 }
2084 }
2085 continue;
2086
2087 case Decl::EnumConstant:
2088 case Decl::IndirectField:
2089 case Decl::ParmVar:
2090 // These can only appear with other declarations which are banned in
2091 // C++11 and permitted in C++1y, so ignore them.
2092 continue;
2093
2094 case Decl::Var:
2095 case Decl::Decomposition: {
2096 // C++1y [dcl.constexpr]p3 allows anything except:
2097 // a definition of a variable of non-literal type or of static or
2098 // thread storage duration or [before C++2a] for which no
2099 // initialization is performed.
2100 const auto *VD = cast<VarDecl>(DclIt);
2101 if (VD->isThisDeclarationADefinition()) {
2102 if (VD->isStaticLocal()) {
2104 SemaRef.DiagCompat(VD->getLocation(),
2105 diag_compat::constexpr_static_var)
2107 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2108 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2109 return false;
2110 }
2111 }
2112 if (SemaRef.LangOpts.CPlusPlus23) {
2113 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
2114 diag::warn_cxx20_compat_constexpr_var,
2116 } else if (CheckLiteralType(
2117 SemaRef, Kind, VD->getLocation(), VD->getType(),
2118 diag::err_constexpr_local_var_non_literal_type,
2120 return false;
2121 }
2122 if (!VD->getType()->isDependentType() &&
2123 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2125 SemaRef.DiagCompat(VD->getLocation(),
2126 diag_compat::constexpr_local_var_no_init)
2128 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2129 return false;
2130 }
2131 continue;
2132 }
2133 }
2135 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2137 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2138 return false;
2139 }
2140 continue;
2141 }
2142
2143 case Decl::NamespaceAlias:
2144 case Decl::Function:
2145 // These are disallowed in C++11 and permitted in C++1y. Allow them
2146 // everywhere as an extension.
2147 if (!Cxx1yLoc.isValid())
2148 Cxx1yLoc = DS->getBeginLoc();
2149 continue;
2150
2151 default:
2153 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2154 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2155 }
2156 return false;
2157 }
2158 }
2159
2160 return true;
2161}
2162
2163/// Check that the given field is initialized within a constexpr constructor.
2164///
2165/// \param Dcl The constexpr constructor being checked.
2166/// \param Field The field being checked. This may be a member of an anonymous
2167/// struct or union nested within the class being checked.
2168/// \param Inits All declarations, including anonymous struct/union members and
2169/// indirect members, for which any initialization was provided.
2170/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2171/// multiple notes for different members to the same error.
2172/// \param Kind Whether we're diagnosing a constructor as written or determining
2173/// whether the formal requirements are satisfied.
2174/// \return \c false if we're checking for validity and the constructor does
2175/// not satisfy the requirements on a constexpr constructor.
2177 const FunctionDecl *Dcl,
2178 FieldDecl *Field,
2180 bool &Diagnosed,
2182 // In C++20 onwards, there's nothing to check for validity.
2184 SemaRef.getLangOpts().CPlusPlus20)
2185 return true;
2186
2187 if (Field->isInvalidDecl())
2188 return true;
2189
2190 if (Field->isUnnamedBitField())
2191 return true;
2192
2193 // Anonymous unions with no variant members and empty anonymous structs do not
2194 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2195 // indirect fields don't need initializing.
2196 if (Field->isAnonymousStructOrUnion() &&
2197 (Field->getType()->isUnionType()
2198 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2199 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2200 return true;
2201
2202 if (!Inits.count(Field)) {
2204 if (!Diagnosed) {
2205 SemaRef.DiagCompat(Dcl->getLocation(),
2206 diag_compat::constexpr_ctor_missing_init);
2207 Diagnosed = true;
2208 }
2209 SemaRef.Diag(Field->getLocation(),
2210 diag::note_constexpr_ctor_missing_init);
2211 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2212 return false;
2213 }
2214 } else if (Field->isAnonymousStructOrUnion()) {
2215 const auto *RD = Field->getType()->castAsRecordDecl();
2216 for (auto *I : RD->fields())
2217 // If an anonymous union contains an anonymous struct of which any member
2218 // is initialized, all members must be initialized.
2219 if (!RD->isUnion() || Inits.count(I))
2220 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2221 Kind))
2222 return false;
2223 }
2224 return true;
2225}
2226
2227/// Check the provided statement is allowed in a constexpr function
2228/// definition.
2229static bool
2232 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2233 SourceLocation &Cxx2bLoc,
2235 // - its function-body shall be [...] a compound-statement that contains only
2236 switch (S->getStmtClass()) {
2237 case Stmt::NullStmtClass:
2238 // - null statements,
2239 return true;
2240
2241 case Stmt::DeclStmtClass:
2242 // - static_assert-declarations
2243 // - using-declarations,
2244 // - using-directives,
2245 // - typedef declarations and alias-declarations that do not define
2246 // classes or enumerations,
2247 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2248 return false;
2249 return true;
2250
2251 case Stmt::ReturnStmtClass:
2252 // - and exactly one return statement;
2253 if (isa<CXXConstructorDecl>(Dcl)) {
2254 // C++1y allows return statements in constexpr constructors.
2255 if (!Cxx1yLoc.isValid())
2256 Cxx1yLoc = S->getBeginLoc();
2257 return true;
2258 }
2259
2260 ReturnStmts.push_back(S->getBeginLoc());
2261 return true;
2262
2263 case Stmt::AttributedStmtClass:
2264 // Attributes on a statement don't affect its formal kind and hence don't
2265 // affect its validity in a constexpr function.
2267 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2268 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2269
2270 case Stmt::CompoundStmtClass: {
2271 // C++1y allows compound-statements.
2272 if (!Cxx1yLoc.isValid())
2273 Cxx1yLoc = S->getBeginLoc();
2274
2275 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2276 for (auto *BodyIt : CompStmt->body()) {
2277 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2278 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2279 return false;
2280 }
2281 return true;
2282 }
2283
2284 case Stmt::IfStmtClass: {
2285 // C++1y allows if-statements.
2286 if (!Cxx1yLoc.isValid())
2287 Cxx1yLoc = S->getBeginLoc();
2288
2289 IfStmt *If = cast<IfStmt>(S);
2290 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2291 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2292 return false;
2293 if (If->getElse() &&
2294 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2295 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2296 return false;
2297 return true;
2298 }
2299
2300 case Stmt::WhileStmtClass:
2301 case Stmt::DoStmtClass:
2302 case Stmt::ForStmtClass:
2303 case Stmt::CXXForRangeStmtClass:
2304 case Stmt::ContinueStmtClass:
2305 // C++1y allows all of these. We don't allow them as extensions in C++11,
2306 // because they don't make sense without variable mutation.
2307 if (!SemaRef.getLangOpts().CPlusPlus14)
2308 break;
2309 if (!Cxx1yLoc.isValid())
2310 Cxx1yLoc = S->getBeginLoc();
2311 for (Stmt *SubStmt : S->children()) {
2312 if (SubStmt &&
2313 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2314 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2315 return false;
2316 }
2317 return true;
2318
2319 case Stmt::SwitchStmtClass:
2320 case Stmt::CaseStmtClass:
2321 case Stmt::DefaultStmtClass:
2322 case Stmt::BreakStmtClass:
2323 // C++1y allows switch-statements, and since they don't need variable
2324 // mutation, we can reasonably allow them in C++11 as an extension.
2325 if (!Cxx1yLoc.isValid())
2326 Cxx1yLoc = S->getBeginLoc();
2327 for (Stmt *SubStmt : S->children()) {
2328 if (SubStmt &&
2329 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2330 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2331 return false;
2332 }
2333 return true;
2334
2335 case Stmt::LabelStmtClass:
2336 case Stmt::GotoStmtClass:
2337 if (Cxx2bLoc.isInvalid())
2338 Cxx2bLoc = S->getBeginLoc();
2339 for (Stmt *SubStmt : S->children()) {
2340 if (SubStmt &&
2341 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2342 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2343 return false;
2344 }
2345 return true;
2346
2347 case Stmt::GCCAsmStmtClass:
2348 case Stmt::MSAsmStmtClass:
2349 // C++2a allows inline assembly statements.
2350 case Stmt::CXXTryStmtClass:
2351 if (Cxx2aLoc.isInvalid())
2352 Cxx2aLoc = S->getBeginLoc();
2353 for (Stmt *SubStmt : S->children()) {
2354 if (SubStmt &&
2355 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2356 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2357 return false;
2358 }
2359 return true;
2360
2361 case Stmt::CXXCatchStmtClass:
2362 // Do not bother checking the language mode (already covered by the
2363 // try block check).
2365 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2366 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2367 return false;
2368 return true;
2369
2370 default:
2371 if (!isa<Expr>(S))
2372 break;
2373
2374 // C++1y allows expression-statements.
2375 if (!Cxx1yLoc.isValid())
2376 Cxx1yLoc = S->getBeginLoc();
2377 return true;
2378 }
2379
2381 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2382 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2383 }
2384 return false;
2385}
2386
2387/// Check the body for the given constexpr function declaration only contains
2388/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2389///
2390/// \return true if the body is OK, false if we have found or diagnosed a
2391/// problem.
2392static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2393 Stmt *Body,
2396
2397 if (isa<CXXTryStmt>(Body)) {
2398 // C++11 [dcl.constexpr]p3:
2399 // The definition of a constexpr function shall satisfy the following
2400 // constraints: [...]
2401 // - its function-body shall be = delete, = default, or a
2402 // compound-statement
2403 //
2404 // C++11 [dcl.constexpr]p4:
2405 // In the definition of a constexpr constructor, [...]
2406 // - its function-body shall not be a function-try-block;
2407 //
2408 // This restriction is lifted in C++2a, as long as inner statements also
2409 // apply the general constexpr rules.
2410 switch (Kind) {
2412 if (!SemaRef.getLangOpts().CPlusPlus20)
2413 return false;
2414 break;
2415
2417 SemaRef.DiagCompat(Body->getBeginLoc(),
2418 diag_compat::constexpr_function_try_block)
2420 break;
2421 }
2422 }
2423
2424 // - its function-body shall be [...] a compound-statement that contains only
2425 // [... list of cases ...]
2426 //
2427 // Note that walking the children here is enough to properly check for
2428 // CompoundStmt and CXXTryStmt body.
2429 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2430 for (Stmt *SubStmt : Body->children()) {
2431 if (SubStmt &&
2432 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2433 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2434 return false;
2435 }
2436
2438 // If this is only valid as an extension, report that we don't satisfy the
2439 // constraints of the current language.
2440 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2441 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2442 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2443 return false;
2444 } else if (Cxx2bLoc.isValid()) {
2445 SemaRef.DiagCompat(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2447 } else if (Cxx2aLoc.isValid()) {
2448 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2450 } else if (Cxx1yLoc.isValid()) {
2451 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2453 }
2454
2456 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2457 const CXXRecordDecl *RD = Constructor->getParent();
2458 // DR1359:
2459 // - every non-variant non-static data member and base class sub-object
2460 // shall be initialized;
2461 // DR1460:
2462 // - if the class is a union having variant members, exactly one of them
2463 // shall be initialized;
2464 if (RD->isUnion()) {
2465 if (Constructor->getNumCtorInitializers() == 0 &&
2466 RD->hasVariantMembers()) {
2468 SemaRef.DiagCompat(Dcl->getLocation(),
2469 diag_compat::constexpr_union_ctor_no_init);
2470 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2471 return false;
2472 }
2473 }
2474 } else if (!Constructor->isDependentContext() &&
2475 !Constructor->isDelegatingConstructor()) {
2476 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2477
2478 // Skip detailed checking if we have enough initializers, and we would
2479 // allow at most one initializer per member.
2480 bool AnyAnonStructUnionMembers = false;
2481 unsigned Fields = 0;
2483 E = RD->field_end(); I != E; ++I, ++Fields) {
2484 if (I->isAnonymousStructOrUnion()) {
2485 AnyAnonStructUnionMembers = true;
2486 break;
2487 }
2488 }
2489 // DR1460:
2490 // - if the class is a union-like class, but is not a union, for each of
2491 // its anonymous union members having variant members, exactly one of
2492 // them shall be initialized;
2493 if (AnyAnonStructUnionMembers ||
2494 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2495 // Check initialization of non-static data members. Base classes are
2496 // always initialized so do not need to be checked. Dependent bases
2497 // might not have initializers in the member initializer list.
2499 for (const auto *I: Constructor->inits()) {
2500 if (FieldDecl *FD = I->getMember())
2501 Inits.insert(FD);
2502 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2503 Inits.insert(ID->chain_begin(), ID->chain_end());
2504 }
2505
2506 bool Diagnosed = false;
2507 for (auto *I : RD->fields())
2508 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2509 Kind))
2510 return false;
2511 }
2512 }
2513 } else {
2514 if (ReturnStmts.empty()) {
2515 switch (Kind) {
2517 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2518 return false;
2519 break;
2520
2522 // The formal requirements don't include this rule in C++14, even
2523 // though the "must be able to produce a constant expression" rules
2524 // still imply it in some cases.
2525 if (!SemaRef.getLangOpts().CPlusPlus14)
2526 return false;
2527 break;
2528 }
2529 } else if (ReturnStmts.size() > 1) {
2530 switch (Kind) {
2532 SemaRef.DiagCompat(ReturnStmts.back(),
2533 diag_compat::constexpr_body_multiple_return);
2534 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2535 SemaRef.Diag(ReturnStmts[I],
2536 diag::note_constexpr_body_previous_return);
2537 break;
2538
2540 if (!SemaRef.getLangOpts().CPlusPlus14)
2541 return false;
2542 break;
2543 }
2544 }
2545 }
2546
2547 // C++11 [dcl.constexpr]p5:
2548 // if no function argument values exist such that the function invocation
2549 // substitution would produce a constant expression, the program is
2550 // ill-formed; no diagnostic required.
2551 // C++11 [dcl.constexpr]p3:
2552 // - every constructor call and implicit conversion used in initializing the
2553 // return value shall be one of those allowed in a constant expression.
2554 // C++11 [dcl.constexpr]p4:
2555 // - every constructor involved in initializing non-static data members and
2556 // base class sub-objects shall be a constexpr constructor.
2557 //
2558 // Note that this rule is distinct from the "requirements for a constexpr
2559 // function", so is not checked in CheckValid mode. Because the check for
2560 // constexpr potential is expensive, skip the check if the diagnostic is
2561 // disabled, the function is declared in a system header, or we're in C++23
2562 // or later mode (see https://wg21.link/P2448).
2563 bool SkipCheck =
2564 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2565 SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||
2566 SemaRef.getDiagnostics().isIgnored(
2567 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2569 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2570 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2571 SemaRef.Diag(Dcl->getLocation(),
2572 diag::ext_constexpr_function_never_constant_expr)
2573 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2574 << Dcl->getNameInfo().getSourceRange();
2575 for (const auto &Diag : Diags)
2576 SemaRef.Diag(Diag.first, Diag.second);
2577 // Don't return false here: we allow this for compatibility in
2578 // system headers.
2579 }
2580
2581 return true;
2582}
2583
2585 const FunctionDecl *Dcl) {
2586 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2588 // Skip emitting a missing return error diagnostic for non-void functions
2589 // since C++23 no longer mandates constexpr functions to yield constant
2590 // expressions.
2591 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2592 return true;
2593
2594 // C++14 doesn't require constexpr functions to contain a 'return'
2595 // statement. We still do, unless the return type might be void, because
2596 // otherwise if there's no return statement, the function cannot
2597 // be used in a core constant expression.
2598 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2599 SemaRef.Diag(Dcl->getLocation(),
2600 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2601 : diag::err_constexpr_body_no_return)
2602 << Dcl->isConsteval();
2603 return OK;
2604}
2605
2607 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2609 return true;
2613 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2614 if (it != UndefinedButUsed.end()) {
2615 Diag(it->second, diag::err_immediate_function_used_before_definition)
2616 << it->first;
2617 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2618 if (FD->isImmediateFunction() && !FD->isConsteval())
2620 return false;
2621 }
2622 }
2623 return true;
2624}
2625
2627 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2628 "expected an immediate function");
2629 assert(FD->hasBody() && "expected the function to have a body");
2630 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2631 Sema &SemaRef;
2632
2633 const FunctionDecl *ImmediateFn;
2634 bool ImmediateFnIsConstructor;
2635 CXXConstructorDecl *CurrentConstructor = nullptr;
2636 CXXCtorInitializer *CurrentInit = nullptr;
2637
2638 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2639 : SemaRef(SemaRef), ImmediateFn(FD),
2640 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2641 ShouldVisitImplicitCode = true;
2642 ShouldVisitLambdaBody = false;
2643 }
2644
2645 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2646 SourceLocation Loc = E->getBeginLoc();
2647 SourceRange Range = E->getSourceRange();
2648 if (CurrentConstructor && CurrentInit) {
2649 Loc = CurrentConstructor->getLocation();
2650 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2651 : SourceRange();
2652 }
2653
2654 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2655
2656 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2657 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2658 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2659 << (InitializedField != nullptr)
2660 << (CurrentInit && !CurrentInit->isWritten())
2661 << InitializedField << Range;
2662 }
2663 bool TraverseCallExpr(CallExpr *E) override {
2664 if (const auto *DR =
2665 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2666 DR && DR->isImmediateEscalating()) {
2667 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2668 return false;
2669 }
2670
2671 for (Expr *A : E->arguments())
2672 if (!TraverseStmt(A))
2673 return false;
2674
2675 return true;
2676 }
2677
2678 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2679 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2680 ReferencedFn && E->isImmediateEscalating()) {
2681 Diag(E, ReferencedFn, /*IsCall=*/false);
2682 return false;
2683 }
2684
2685 return true;
2686 }
2687
2688 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2690 if (E->isImmediateEscalating()) {
2691 Diag(E, D, /*IsCall=*/true);
2692 return false;
2693 }
2694 return true;
2695 }
2696
2697 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2698 llvm::SaveAndRestore RAII(CurrentInit, Init);
2700 }
2701
2702 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2703 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2704 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2705 }
2706
2707 bool TraverseType(QualType T, bool TraverseQualifier) override {
2708 return true;
2709 }
2710 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2711
2712 } Visitor(*this, FD);
2713 Visitor.TraverseDecl(FD);
2714}
2715
2717 assert(getLangOpts().CPlusPlus && "No class names in C!");
2718
2719 if (SS && SS->isInvalid())
2720 return nullptr;
2721
2722 if (SS && SS->isNotEmpty()) {
2723 DeclContext *DC = computeDeclContext(*SS, true);
2724 return dyn_cast_or_null<CXXRecordDecl>(DC);
2725 }
2726
2727 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2728}
2729
2731 const CXXScopeSpec *SS) {
2732 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2733 return CurDecl && &II == CurDecl->getIdentifier();
2734}
2735
2737 assert(getLangOpts().CPlusPlus && "No class names in C!");
2738
2739 if (!getLangOpts().SpellChecking)
2740 return false;
2741
2742 CXXRecordDecl *CurDecl;
2743 if (SS && SS->isSet() && !SS->isInvalid()) {
2744 DeclContext *DC = computeDeclContext(*SS, true);
2745 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2746 } else
2747 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2748
2749 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2750 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2751 < II->getLength()) {
2752 II = CurDecl->getIdentifier();
2753 return true;
2754 }
2755
2756 return false;
2757}
2758
2760 SourceRange SpecifierRange,
2761 bool Virtual, AccessSpecifier Access,
2762 TypeSourceInfo *TInfo,
2763 SourceLocation EllipsisLoc) {
2764 QualType BaseType = TInfo->getType();
2765 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2766 if (BaseType->containsErrors()) {
2767 // Already emitted a diagnostic when parsing the error type.
2768 return nullptr;
2769 }
2770
2771 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2772 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2773 << TInfo->getTypeLoc().getSourceRange();
2774 EllipsisLoc = SourceLocation();
2775 }
2776
2777 auto *BaseDecl =
2778 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2779 // C++ [class.derived.general]p2:
2780 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2781 // that is not an incompletely defined class; any cv-qualifiers are
2782 // ignored.
2783 if (BaseDecl) {
2784 // C++ [class.union.general]p4:
2785 // [...] A union shall not be used as a base class.
2786 if (BaseDecl->isUnion()) {
2787 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2788 return nullptr;
2789 }
2790
2791 if (BaseType.hasQualifiers()) {
2792 std::string Quals =
2793 BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
2794 Diag(BaseLoc, diag::warn_qual_base_type)
2795 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2796 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2797 }
2798
2799 // For the MS ABI, propagate DLL attributes to base class templates.
2800 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2801 Context.getTargetInfo().getTriple().isPS()) {
2802 if (Attr *ClassAttr = getDLLAttr(Class)) {
2803 if (auto *BaseSpec =
2804 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2805 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2806 BaseLoc);
2807 }
2808 }
2809 }
2810
2811 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2812 SpecifierRange)) {
2813 Class->setInvalidDecl();
2814 return nullptr;
2815 }
2816
2817 BaseDecl = BaseDecl->getDefinition();
2818 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2819
2820 // Microsoft docs say:
2821 // "If a base-class has a code_seg attribute, derived classes must have the
2822 // same attribute."
2823 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2824 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2825 if ((DerivedCSA || BaseCSA) &&
2826 (!BaseCSA || !DerivedCSA ||
2827 BaseCSA->getName() != DerivedCSA->getName())) {
2828 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2829 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2830 << BaseDecl;
2831 return nullptr;
2832 }
2833
2834 // A class which contains a flexible array member is not suitable for use as
2835 // a base class:
2836 // - If the layout determines that a base comes before another base,
2837 // the flexible array member would index into the subsequent base.
2838 // - If the layout determines that base comes before the derived class,
2839 // the flexible array member would index into the derived class.
2840 if (BaseDecl->hasFlexibleArrayMember()) {
2841 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2842 << BaseDecl->getDeclName();
2843 return nullptr;
2844 }
2845
2846 // C++ [class]p3:
2847 // If a class is marked final and it appears as a base-type-specifier in
2848 // base-clause, the program is ill-formed.
2849 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2850 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2851 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2852 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2853 << BaseDecl->getDeclName() << FA->getRange();
2854 return nullptr;
2855 }
2856
2857 // If the base class is invalid the derived class is as well.
2858 if (BaseDecl->isInvalidDecl())
2859 Class->setInvalidDecl();
2860 } else if (BaseType->isDependentType()) {
2861 // Make sure that we don't make an ill-formed AST where the type of the
2862 // Class is non-dependent and its attached base class specifier is an
2863 // dependent type, which violates invariants in many clang code paths (e.g.
2864 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2865 // explicitly mark the Class decl invalid. The diagnostic was already
2866 // emitted.
2867 if (!Class->isDependentContext())
2868 Class->setInvalidDecl();
2869 } else {
2870 // The base class is some non-dependent non-class type.
2871 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2872 return nullptr;
2873 }
2874
2875 // In HLSL, unspecified class access is public rather than private.
2876 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2877 Access == AS_none)
2878 Access = AS_public;
2879
2880 // Create the base specifier.
2881 return new (Context) CXXBaseSpecifier(
2882 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2883 Access, TInfo, EllipsisLoc);
2884}
2885
2887 const ParsedAttributesView &Attributes,
2888 bool Virtual, AccessSpecifier Access,
2889 ParsedType basetype, SourceLocation BaseLoc,
2890 SourceLocation EllipsisLoc) {
2891 if (!classdecl)
2892 return true;
2893
2894 AdjustDeclIfTemplate(classdecl);
2895 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2896 if (!Class)
2897 return true;
2898
2899 // We haven't yet attached the base specifiers.
2900 Class->setIsParsingBaseSpecifiers();
2901
2902 // We do not support any C++11 attributes on base-specifiers yet.
2903 // Diagnose any attributes we see.
2904 for (const ParsedAttr &AL : Attributes) {
2905 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2906 continue;
2907 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2909 else
2910 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2911 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2912 }
2913
2914 TypeSourceInfo *TInfo = nullptr;
2915 GetTypeFromParser(basetype, &TInfo);
2916
2917 if (EllipsisLoc.isInvalid() &&
2918 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2920 return true;
2921
2922 // C++ [class.union.general]p4:
2923 // [...] A union shall not have base classes.
2924 if (Class->isUnion()) {
2925 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2926 << SpecifierRange;
2927 return true;
2928 }
2929
2930 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2931 Virtual, Access, TInfo,
2932 EllipsisLoc))
2933 return BaseSpec;
2934
2935 Class->setInvalidDecl();
2936 return true;
2937}
2938
2939/// Use small set to collect indirect bases. As this is only used
2940/// locally, there's no need to abstract the small size parameter.
2942
2943/// Recursively add the bases of Type. Don't add Type itself.
2944static void
2946 const QualType &Type)
2947{
2948 // Even though the incoming type is a base, it might not be
2949 // a class -- it could be a template parm, for instance.
2950 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2951 // Iterate over its bases.
2952 for (const auto &BaseSpec : Decl->bases()) {
2953 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2954 .getUnqualifiedType();
2955 if (Set.insert(Base).second)
2956 // If we've not already seen it, recurse.
2957 NoteIndirectBases(Context, Set, Base);
2958 }
2959 }
2960}
2961
2964 if (Bases.empty())
2965 return false;
2966
2967 // Used to keep track of which base types we have already seen, so
2968 // that we can properly diagnose redundant direct base types. Note
2969 // that the key is always the unqualified canonical type of the base
2970 // class.
2971 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2972
2973 // Used to track indirect bases so we can see if a direct base is
2974 // ambiguous.
2975 IndirectBaseSet IndirectBaseTypes;
2976
2977 // Copy non-redundant base specifiers into permanent storage.
2978 unsigned NumGoodBases = 0;
2979 bool Invalid = false;
2980 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2981 QualType NewBaseType
2982 = Context.getCanonicalType(Bases[idx]->getType());
2983 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2984
2985 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2986 if (KnownBase) {
2987 // C++ [class.mi]p3:
2988 // A class shall not be specified as a direct base class of a
2989 // derived class more than once.
2990 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2991 << KnownBase->getType() << Bases[idx]->getSourceRange();
2992
2993 // Delete the duplicate base class specifier; we're going to
2994 // overwrite its pointer later.
2995 Context.Deallocate(Bases[idx]);
2996
2997 Invalid = true;
2998 } else {
2999 // Okay, add this new base class.
3000 KnownBase = Bases[idx];
3001 Bases[NumGoodBases++] = Bases[idx];
3002
3003 if (NewBaseType->isDependentType())
3004 continue;
3005 // Note this base's direct & indirect bases, if there could be ambiguity.
3006 if (Bases.size() > 1)
3007 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
3008
3009 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3010 if (Class->isInterface() &&
3011 (!RD->isInterfaceLike() ||
3012 KnownBase->getAccessSpecifier() != AS_public)) {
3013 // The Microsoft extension __interface does not permit bases that
3014 // are not themselves public interfaces.
3015 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
3016 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
3017 << RD->getSourceRange();
3018 Invalid = true;
3019 }
3020 if (RD->hasAttr<WeakAttr>())
3021 Class->addAttr(WeakAttr::CreateImplicit(Context));
3022 }
3023 }
3024 }
3025
3026 // Attach the remaining base class specifiers to the derived class.
3027 Class->setBases(Bases.data(), NumGoodBases);
3028
3029 // Check that the only base classes that are duplicate are virtual.
3030 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3031 // Check whether this direct base is inaccessible due to ambiguity.
3032 QualType BaseType = Bases[idx]->getType();
3033
3034 // Skip all dependent types in templates being used as base specifiers.
3035 // Checks below assume that the base specifier is a CXXRecord.
3036 if (BaseType->isDependentType())
3037 continue;
3038
3039 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3040 .getUnqualifiedType();
3041
3042 if (IndirectBaseTypes.count(CanonicalBase)) {
3043 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3044 /*DetectVirtual=*/true);
3045 bool found
3046 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3047 assert(found);
3048 (void)found;
3049
3050 if (Paths.isAmbiguous(CanonicalBase))
3051 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3052 << BaseType << getAmbiguousPathsDisplayString(Paths)
3053 << Bases[idx]->getSourceRange();
3054 else
3055 assert(Bases[idx]->isVirtual());
3056 }
3057
3058 // Delete the base class specifier, since its data has been copied
3059 // into the CXXRecordDecl.
3060 Context.Deallocate(Bases[idx]);
3061 }
3062
3063 return Invalid;
3064}
3065
3068 if (!ClassDecl || Bases.empty())
3069 return;
3070
3071 AdjustDeclIfTemplate(ClassDecl);
3072 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3073}
3074
3076 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3077 if (!getLangOpts().CPlusPlus)
3078 return false;
3079
3080 if (!Base || !Derived)
3081 return false;
3082
3083 // If either the base or the derived type is invalid, don't try to
3084 // check whether one is derived from the other.
3085 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3086 return false;
3087
3088 // FIXME: In a modules build, do we need the entire path to be visible for us
3089 // to be able to use the inheritance relationship?
3090 if (!isCompleteType(Loc, Context.getCanonicalTagType(Derived)) &&
3091 !Derived->isBeingDefined())
3092 return false;
3093
3094 return Derived->isDerivedFrom(Base, Paths);
3095}
3096
3099 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3100 /*DetectVirtual=*/false);
3101 return IsDerivedFrom(Loc, Derived, Base, Paths);
3102}
3103
3105 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3106 /*DetectVirtual=*/false);
3107 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3108 Base->getAsCXXRecordDecl(), Paths);
3109}
3110
3112 CXXBasePaths &Paths) {
3113 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3114 Base->getAsCXXRecordDecl(), Paths);
3115}
3116
3117static void BuildBasePathArray(const CXXBasePath &Path,
3118 CXXCastPath &BasePathArray) {
3119 // We first go backward and check if we have a virtual base.
3120 // FIXME: It would be better if CXXBasePath had the base specifier for
3121 // the nearest virtual base.
3122 unsigned Start = 0;
3123 for (unsigned I = Path.size(); I != 0; --I) {
3124 if (Path[I - 1].Base->isVirtual()) {
3125 Start = I - 1;
3126 break;
3127 }
3128 }
3129
3130 // Now add all bases.
3131 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3132 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3133}
3134
3135
3137 CXXCastPath &BasePathArray) {
3138 assert(BasePathArray.empty() && "Base path array must be empty!");
3139 assert(Paths.isRecordingPaths() && "Must record paths!");
3140 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3141}
3142
3143bool
3145 unsigned InaccessibleBaseID,
3146 unsigned AmbiguousBaseConvID,
3147 SourceLocation Loc, SourceRange Range,
3148 DeclarationName Name,
3149 CXXCastPath *BasePath,
3150 bool IgnoreAccess) {
3151 // First, determine whether the path from Derived to Base is
3152 // ambiguous. This is slightly more expensive than checking whether
3153 // the Derived to Base conversion exists, because here we need to
3154 // explore multiple paths to determine if there is an ambiguity.
3155 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3156 /*DetectVirtual=*/false);
3157 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3158 if (!DerivationOkay)
3159 return true;
3160
3161 const CXXBasePath *Path = nullptr;
3162 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3163 Path = &Paths.front();
3164
3165 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3166 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3167 // user to access such bases.
3168 if (!Path && getLangOpts().MSVCCompat) {
3169 for (const CXXBasePath &PossiblePath : Paths) {
3170 if (PossiblePath.size() == 1) {
3171 Path = &PossiblePath;
3172 if (AmbiguousBaseConvID)
3173 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3174 << Base << Derived << Range;
3175 break;
3176 }
3177 }
3178 }
3179
3180 if (Path) {
3181 if (!IgnoreAccess) {
3182 // Check that the base class can be accessed.
3183 switch (
3184 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3185 case AR_inaccessible:
3186 return true;
3187 case AR_accessible:
3188 case AR_dependent:
3189 case AR_delayed:
3190 break;
3191 }
3192 }
3193
3194 // Build a base path if necessary.
3195 if (BasePath)
3196 ::BuildBasePathArray(*Path, *BasePath);
3197 return false;
3198 }
3199
3200 if (AmbiguousBaseConvID) {
3201 // We know that the derived-to-base conversion is ambiguous, and
3202 // we're going to produce a diagnostic. Perform the derived-to-base
3203 // search just one more time to compute all of the possible paths so
3204 // that we can print them out. This is more expensive than any of
3205 // the previous derived-to-base checks we've done, but at this point
3206 // performance isn't as much of an issue.
3207 Paths.clear();
3208 Paths.setRecordingPaths(true);
3209 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3210 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3211 (void)StillOkay;
3212
3213 // Build up a textual representation of the ambiguous paths, e.g.,
3214 // D -> B -> A, that will be used to illustrate the ambiguous
3215 // conversions in the diagnostic. We only print one of the paths
3216 // to each base class subobject.
3217 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3218
3219 Diag(Loc, AmbiguousBaseConvID)
3220 << Derived << Base << PathDisplayStr << Range << Name;
3221 }
3222 return true;
3223}
3224
3225bool
3227 SourceLocation Loc, SourceRange Range,
3228 CXXCastPath *BasePath,
3229 bool IgnoreAccess) {
3231 Derived, Base, diag::err_upcast_to_inaccessible_base,
3232 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3233 BasePath, IgnoreAccess);
3234}
3235
3237 std::string PathDisplayStr;
3238 std::set<unsigned> DisplayedPaths;
3239 for (const CXXBasePath &Path : Paths) {
3240 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
3241 // We haven't displayed a path to this particular base
3242 // class subobject yet.
3243 PathDisplayStr += "\n ";
3244 PathDisplayStr += QualType(Context.getCanonicalTagType(Paths.getOrigin()))
3245 .getAsString();
3246 for (const CXXBasePathElement &Element : Path)
3247 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3248 }
3249 }
3250
3251 return PathDisplayStr;
3252}
3253
3254//===----------------------------------------------------------------------===//
3255// C++ class member Handling
3256//===----------------------------------------------------------------------===//
3257
3259 SourceLocation ColonLoc,
3260 const ParsedAttributesView &Attrs) {
3261 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3263 ASLoc, ColonLoc);
3264 CurContext->addHiddenDecl(ASDecl);
3265 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3266}
3267
3269 if (D->isInvalidDecl())
3270 return;
3271
3272 // We only care about "override" and "final" declarations.
3273 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3274 return;
3275
3276 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3277
3278 // We can't check dependent instance methods.
3279 if (MD && MD->isInstance() &&
3280 (MD->getParent()->hasAnyDependentBases() ||
3281 MD->getType()->isDependentType()))
3282 return;
3283
3284 if (MD && !MD->isVirtual()) {
3285 // If we have a non-virtual method, check if it hides a virtual method.
3286 // (In that case, it's most likely the method has the wrong type.)
3287 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3288 FindHiddenVirtualMethods(MD, OverloadedMethods);
3289
3290 if (!OverloadedMethods.empty()) {
3291 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3292 Diag(OA->getLocation(),
3293 diag::override_keyword_hides_virtual_member_function)
3294 << "override" << (OverloadedMethods.size() > 1);
3295 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3296 Diag(FA->getLocation(),
3297 diag::override_keyword_hides_virtual_member_function)
3298 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3299 << (OverloadedMethods.size() > 1);
3300 }
3301 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3302 MD->setInvalidDecl();
3303 return;
3304 }
3305 // Fall through into the general case diagnostic.
3306 // FIXME: We might want to attempt typo correction here.
3307 }
3308
3309 if (!MD || !MD->isVirtual()) {
3310 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3311 Diag(OA->getLocation(),
3312 diag::override_keyword_only_allowed_on_virtual_member_functions)
3313 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3314 D->dropAttr<OverrideAttr>();
3315 }
3316 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3317 Diag(FA->getLocation(),
3318 diag::override_keyword_only_allowed_on_virtual_member_functions)
3319 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3320 << FixItHint::CreateRemoval(FA->getLocation());
3321 D->dropAttr<FinalAttr>();
3322 }
3323 return;
3324 }
3325
3326 // C++11 [class.virtual]p5:
3327 // If a function is marked with the virt-specifier override and
3328 // does not override a member function of a base class, the program is
3329 // ill-formed.
3330 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3331 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3332 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3333 << MD->getDeclName();
3334}
3335
3337 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3338 return;
3339 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3340 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3341 return;
3342
3343 SourceLocation Loc = MD->getLocation();
3344 SourceLocation SpellingLoc = Loc;
3345 if (getSourceManager().isMacroArgExpansion(Loc))
3346 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3347 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3348 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3349 return;
3350
3351 if (MD->size_overridden_methods() > 0) {
3352 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3353 unsigned DiagID =
3354 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3355 ? DiagInconsistent
3356 : DiagSuggest;
3357 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3358 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3359 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3360 };
3361 if (isa<CXXDestructorDecl>(MD))
3362 EmitDiag(
3363 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3364 diag::warn_suggest_destructor_marked_not_override_overriding);
3365 else
3366 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3367 diag::warn_suggest_function_marked_not_override_overriding);
3368 }
3369}
3370
3372 const CXXMethodDecl *Old) {
3373 FinalAttr *FA = Old->getAttr<FinalAttr>();
3374 if (!FA)
3375 return false;
3376
3377 Diag(New->getLocation(), diag::err_final_function_overridden)
3378 << New->getDeclName()
3379 << FA->isSpelledAsSealed();
3380 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3381 return true;
3382}
3383
3385 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3386 // FIXME: Destruction of ObjC lifetime types has side-effects.
3387 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3388 return !RD->isCompleteDefinition() ||
3389 !RD->hasTrivialDefaultConstructor() ||
3390 !RD->hasTrivialDestructor();
3391 return false;
3392}
3393
3394void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3395 DeclarationName FieldName,
3396 const CXXRecordDecl *RD,
3397 bool DeclIsField) {
3398 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3399 return;
3400
3401 // To record a shadowed field in a base
3402 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3403 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3404 CXXBasePath &Path) {
3405 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3406 // Record an ambiguous path directly
3407 if (Bases.find(Base) != Bases.end())
3408 return true;
3409 for (const auto Field : Base->lookup(FieldName)) {
3410 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3411 Field->getAccess() != AS_private) {
3412 assert(Field->getAccess() != AS_none);
3413 assert(Bases.find(Base) == Bases.end());
3414 Bases[Base] = Field;
3415 return true;
3416 }
3417 }
3418 return false;
3419 };
3420
3421 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3422 /*DetectVirtual=*/true);
3423 if (!RD->lookupInBases(FieldShadowed, Paths))
3424 return;
3425
3426 for (const auto &P : Paths) {
3427 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3428 auto It = Bases.find(Base);
3429 // Skip duplicated bases
3430 if (It == Bases.end())
3431 continue;
3432 auto BaseField = It->second;
3433 assert(BaseField->getAccess() != AS_private);
3434 if (AS_none !=
3435 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3436 Diag(Loc, diag::warn_shadow_field)
3437 << FieldName << RD << Base << DeclIsField;
3438 Diag(BaseField->getLocation(), diag::note_shadow_field);
3439 Bases.erase(It);
3440 }
3441 }
3442}
3443
3444template <typename AttrType>
3445inline static bool HasAttribute(const QualType &T) {
3446 if (const TagDecl *TD = T->getAsTagDecl())
3447 return TD->hasAttr<AttrType>();
3448 if (const TypedefType *TDT = T->getAs<TypedefType>())
3449 return TDT->getDecl()->hasAttr<AttrType>();
3450 return false;
3451}
3452
3453static bool IsUnusedPrivateField(const FieldDecl *FD) {
3454 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3455 QualType FieldType = FD->getType();
3456 if (HasAttribute<WarnUnusedAttr>(FieldType))
3457 return true;
3458
3459 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3460 !FD->getParent()->isDependentContext() &&
3461 !HasAttribute<UnusedAttr>(FieldType) &&
3463 }
3464 return false;
3465}
3466
3467NamedDecl *
3469 MultiTemplateParamsArg TemplateParameterLists,
3470 Expr *BitWidth, const VirtSpecifiers &VS,
3471 InClassInitStyle InitStyle) {
3472 const DeclSpec &DS = D.getDeclSpec();
3474 DeclarationName Name = NameInfo.getName();
3475 SourceLocation Loc = NameInfo.getLoc();
3476
3477 // For anonymous bitfields, the location should point to the type.
3478 if (Loc.isInvalid())
3479 Loc = D.getBeginLoc();
3480
3482 assert(!DS.isFriendSpecified());
3483
3484 bool isFunc = D.isDeclarationOfFunction();
3485 const ParsedAttr *MSPropertyAttr =
3487
3488 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3489 // The Microsoft extension __interface only permits public member functions
3490 // and prohibits constructors, destructors, operators, non-public member
3491 // functions, static methods and data members.
3492 unsigned InvalidDecl;
3493 bool ShowDeclName = true;
3494 if (!isFunc &&
3495 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3496 InvalidDecl = 0;
3497 else if (!isFunc)
3498 InvalidDecl = 1;
3499 else if (AS != AS_public)
3500 InvalidDecl = 2;
3502 InvalidDecl = 3;
3503 else switch (Name.getNameKind()) {
3505 InvalidDecl = 4;
3506 ShowDeclName = false;
3507 break;
3508
3510 InvalidDecl = 5;
3511 ShowDeclName = false;
3512 break;
3513
3516 InvalidDecl = 6;
3517 break;
3518
3519 default:
3520 InvalidDecl = 0;
3521 break;
3522 }
3523
3524 if (InvalidDecl) {
3525 if (ShowDeclName)
3526 Diag(Loc, diag::err_invalid_member_in_interface)
3527 << (InvalidDecl-1) << Name;
3528 else
3529 Diag(Loc, diag::err_invalid_member_in_interface)
3530 << (InvalidDecl-1) << "";
3531 return nullptr;
3532 }
3533 }
3534
3535 // HLSL prohibits user defined constructors and destructors.
3536 if (getLangOpts().HLSL) {
3537 switch (Name.getNameKind()) {
3540 Diag(Loc, diag::err_hlsl_cstor_dstor);
3541 return nullptr;
3542 default:
3543 break;
3544 }
3545 }
3546
3547 // C++ 9.2p6: A member shall not be declared to have automatic storage
3548 // duration (auto, register) or with the extern storage-class-specifier.
3549 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3550 // data members and cannot be applied to names declared const or static,
3551 // and cannot be applied to reference members.
3552 switch (DS.getStorageClassSpec()) {
3556 break;
3558 if (isFunc) {
3559 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3560
3561 // FIXME: It would be nicer if the keyword was ignored only for this
3562 // declarator. Otherwise we could get follow-up errors.
3564 }
3565 break;
3566 default:
3568 diag::err_storageclass_invalid_for_member);
3570 break;
3571 }
3572
3573 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3575 !isFunc && TemplateParameterLists.empty();
3576
3577 if (DS.hasConstexprSpecifier() && isInstField) {
3579 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3580 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3581 if (InitStyle == ICIS_NoInit) {
3582 B << 0 << 0;
3584 B << FixItHint::CreateRemoval(ConstexprLoc);
3585 else {
3586 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3588 const char *PrevSpec;
3589 unsigned DiagID;
3590 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3591 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3592 (void)Failed;
3593 assert(!Failed && "Making a constexpr member const shouldn't fail");
3594 }
3595 } else {
3596 B << 1;
3597 const char *PrevSpec;
3598 unsigned DiagID;
3600 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3601 Context.getPrintingPolicy())) {
3603 "This is the only DeclSpec that should fail to be applied");
3604 B << 1;
3605 } else {
3606 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3607 isInstField = false;
3608 }
3609 }
3610 }
3611
3613 if (isInstField) {
3614 CXXScopeSpec &SS = D.getCXXScopeSpec();
3615
3616 // Data members must have identifiers for names.
3617 if (!Name.isIdentifier()) {
3618 Diag(Loc, diag::err_bad_variable_name)
3619 << Name;
3620 return nullptr;
3621 }
3622
3625 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3626 << II
3630 D.SetIdentifier(II, Loc);
3631 }
3632
3633 if (SS.isSet() && !SS.isInvalid()) {
3634 // The user provided a superfluous scope specifier inside a class
3635 // definition:
3636 //
3637 // class X {
3638 // int X::member;
3639 // };
3640 if (DeclContext *DC = computeDeclContext(SS, false)) {
3641 TemplateIdAnnotation *TemplateId =
3643 ? D.getName().TemplateId
3644 : nullptr;
3646 TemplateId,
3647 /*IsMemberSpecialization=*/false);
3648 } else {
3649 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3650 << Name << SS.getRange();
3651 }
3652 SS.clear();
3653 }
3654
3655 if (MSPropertyAttr) {
3657 BitWidth, InitStyle, AS, *MSPropertyAttr);
3658 if (!Member)
3659 return nullptr;
3660 isInstField = false;
3661 } else {
3663 BitWidth, InitStyle, AS);
3664 if (!Member)
3665 return nullptr;
3666 }
3667
3668 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3669 } else {
3670 Member = HandleDeclarator(S, D, TemplateParameterLists);
3671 if (!Member)
3672 return nullptr;
3673
3674 // Non-instance-fields can't have a bitfield.
3675 if (BitWidth) {
3676 if (Member->isInvalidDecl()) {
3677 // don't emit another diagnostic.
3679 // C++ 9.6p3: A bit-field shall not be a static member.
3680 // "static member 'A' cannot be a bit-field"
3681 Diag(Loc, diag::err_static_not_bitfield)
3682 << Name << BitWidth->getSourceRange();
3683 } else if (isa<TypedefDecl>(Member)) {
3684 // "typedef member 'x' cannot be a bit-field"
3685 Diag(Loc, diag::err_typedef_not_bitfield)
3686 << Name << BitWidth->getSourceRange();
3687 } else {
3688 // A function typedef ("typedef int f(); f a;").
3689 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3690 Diag(Loc, diag::err_not_integral_type_bitfield)
3691 << Name << cast<ValueDecl>(Member)->getType()
3692 << BitWidth->getSourceRange();
3693 }
3694
3695 BitWidth = nullptr;
3696 Member->setInvalidDecl();
3697 }
3698
3699 NamedDecl *NonTemplateMember = Member;
3700 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3701 NonTemplateMember = FunTmpl->getTemplatedDecl();
3702 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3703 NonTemplateMember = VarTmpl->getTemplatedDecl();
3704
3705 Member->setAccess(AS);
3706
3707 // If we have declared a member function template or static data member
3708 // template, set the access of the templated declaration as well.
3709 if (NonTemplateMember != Member)
3710 NonTemplateMember->setAccess(AS);
3711
3712 // C++ [temp.deduct.guide]p3:
3713 // A deduction guide [...] for a member class template [shall be
3714 // declared] with the same access [as the template].
3715 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3716 auto *TD = DG->getDeducedTemplate();
3717 // Access specifiers are only meaningful if both the template and the
3718 // deduction guide are from the same scope.
3719 if (AS != TD->getAccess() &&
3720 TD->getDeclContext()->getRedeclContext()->Equals(
3721 DG->getDeclContext()->getRedeclContext())) {
3722 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3723 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3724 << TD->getAccess();
3725 const AccessSpecDecl *LastAccessSpec = nullptr;
3726 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3727 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3728 LastAccessSpec = AccessSpec;
3729 }
3730 assert(LastAccessSpec && "differing access with no access specifier");
3731 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3732 << AS;
3733 }
3734 }
3735 }
3736
3737 if (VS.isOverrideSpecified())
3738 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3739 if (VS.isFinalSpecified())
3740 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3742 ? FinalAttr::Keyword_sealed
3743 : FinalAttr::Keyword_final));
3744
3745 if (VS.getLastLocation().isValid()) {
3746 // Update the end location of a method that has a virt-specifiers.
3747 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3748 MD->setRangeEnd(VS.getLastLocation());
3749 }
3750
3752
3753 assert((Name || isInstField) && "No identifier for non-field ?");
3754
3755 if (isInstField) {
3757 FieldCollector->Add(FD);
3758
3759 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3761 // Remember all explicit private FieldDecls that have a name, no side
3762 // effects and are not part of a dependent type declaration.
3763 UnusedPrivateFields.insert(FD);
3764 }
3765 }
3766
3767 return Member;
3768}
3769
3770namespace {
3771 class UninitializedFieldVisitor
3772 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3773 Sema &S;
3774 // List of Decls to generate a warning on. Also remove Decls that become
3775 // initialized.
3776 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3777 // List of base classes of the record. Classes are removed after their
3778 // initializers.
3779 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3780 // Vector of decls to be removed from the Decl set prior to visiting the
3781 // nodes. These Decls may have been initialized in the prior initializer.
3783 // If non-null, add a note to the warning pointing back to the constructor.
3785 // Variables to hold state when processing an initializer list. When
3786 // InitList is true, special case initialization of FieldDecls matching
3787 // InitListFieldDecl.
3788 bool InitList;
3789 FieldDecl *InitListFieldDecl;
3790 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3791
3792 public:
3794 UninitializedFieldVisitor(Sema &S,
3795 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3796 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3797 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3798 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3799
3800 // Returns true if the use of ME is not an uninitialized use.
3801 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3802 bool CheckReferenceOnly) {
3804 bool ReferenceField = false;
3805 while (ME) {
3806 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3807 if (!FD)
3808 return false;
3809 Fields.push_back(FD);
3810 if (FD->getType()->isReferenceType())
3811 ReferenceField = true;
3812 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3813 }
3814
3815 // Binding a reference to an uninitialized field is not an
3816 // uninitialized use.
3817 if (CheckReferenceOnly && !ReferenceField)
3818 return true;
3819
3820 // Discard the first field since it is the field decl that is being
3821 // initialized.
3822 auto UsedFields = llvm::drop_begin(llvm::reverse(Fields));
3823 auto UsedIter = UsedFields.begin();
3824 const auto UsedEnd = UsedFields.end();
3825
3826 for (const unsigned Orig : InitFieldIndex) {
3827 if (UsedIter == UsedEnd)
3828 break;
3829 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3830 if (UsedIndex < Orig)
3831 return true;
3832 if (UsedIndex > Orig)
3833 break;
3834 ++UsedIter;
3835 }
3836
3837 return false;
3838 }
3839
3840 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3841 bool AddressOf) {
3843 return;
3844
3845 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3846 // or union.
3847 MemberExpr *FieldME = ME;
3848
3849 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3850
3851 Expr *Base = ME;
3852 while (MemberExpr *SubME =
3853 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3854
3855 if (isa<VarDecl>(SubME->getMemberDecl()))
3856 return;
3857
3858 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3859 if (!FD->isAnonymousStructOrUnion())
3860 FieldME = SubME;
3861
3862 if (!FieldME->getType().isPODType(S.Context))
3863 AllPODFields = false;
3864
3865 Base = SubME->getBase();
3866 }
3867
3868 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3869 Visit(Base);
3870 return;
3871 }
3872
3873 if (AddressOf && AllPODFields)
3874 return;
3875
3876 ValueDecl* FoundVD = FieldME->getMemberDecl();
3877
3878 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3879 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3880 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3881 }
3882
3883 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3884 QualType T = BaseCast->getType();
3885 if (T->isPointerType() &&
3886 BaseClasses.count(T->getPointeeType())) {
3887 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3888 << T->getPointeeType() << FoundVD;
3889 }
3890 }
3891 }
3892
3893 if (!Decls.count(FoundVD))
3894 return;
3895
3896 const bool IsReference = FoundVD->getType()->isReferenceType();
3897
3898 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3899 // Special checking for initializer lists.
3900 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3901 return;
3902 }
3903 } else {
3904 // Prevent double warnings on use of unbounded references.
3905 if (CheckReferenceOnly && !IsReference)
3906 return;
3907 }
3908
3909 unsigned diag = IsReference
3910 ? diag::warn_reference_field_is_uninit
3911 : diag::warn_field_is_uninit;
3912 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3913 if (Constructor)
3914 S.Diag(Constructor->getLocation(),
3915 diag::note_uninit_in_this_constructor)
3916 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3917
3918 }
3919
3920 void HandleValue(Expr *E, bool AddressOf) {
3921 E = E->IgnoreParens();
3922
3923 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3924 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3925 AddressOf /*AddressOf*/);
3926 return;
3927 }
3928
3929 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3930 Visit(CO->getCond());
3931 HandleValue(CO->getTrueExpr(), AddressOf);
3932 HandleValue(CO->getFalseExpr(), AddressOf);
3933 return;
3934 }
3935
3936 if (BinaryConditionalOperator *BCO =
3937 dyn_cast<BinaryConditionalOperator>(E)) {
3938 Visit(BCO->getCond());
3939 HandleValue(BCO->getFalseExpr(), AddressOf);
3940 return;
3941 }
3942
3943 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3944 HandleValue(OVE->getSourceExpr(), AddressOf);
3945 return;
3946 }
3947
3948 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3949 switch (BO->getOpcode()) {
3950 default:
3951 break;
3952 case(BO_PtrMemD):
3953 case(BO_PtrMemI):
3954 HandleValue(BO->getLHS(), AddressOf);
3955 Visit(BO->getRHS());
3956 return;
3957 case(BO_Comma):
3958 Visit(BO->getLHS());
3959 HandleValue(BO->getRHS(), AddressOf);
3960 return;
3961 }
3962 }
3963
3964 Visit(E);
3965 }
3966
3967 void CheckInitListExpr(InitListExpr *ILE) {
3968 InitFieldIndex.push_back(0);
3969 for (auto *Child : ILE->children()) {
3970 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3971 CheckInitListExpr(SubList);
3972 } else {
3973 Visit(Child);
3974 }
3975 ++InitFieldIndex.back();
3976 }
3977 InitFieldIndex.pop_back();
3978 }
3979
3980 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3981 FieldDecl *Field, const Type *BaseClass) {
3982 // Remove Decls that may have been initialized in the previous
3983 // initializer.
3984 for (ValueDecl* VD : DeclsToRemove)
3985 Decls.erase(VD);
3986 DeclsToRemove.clear();
3987
3988 Constructor = FieldConstructor;
3989 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3990
3991 if (ILE && Field) {
3992 InitList = true;
3993 InitListFieldDecl = Field;
3994 InitFieldIndex.clear();
3995 CheckInitListExpr(ILE);
3996 } else {
3997 InitList = false;
3998 Visit(E);
3999 }
4000
4001 if (Field)
4002 Decls.erase(Field);
4003 if (BaseClass)
4004 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
4005 }
4006
4007 void VisitMemberExpr(MemberExpr *ME) {
4008 // All uses of unbounded reference fields will warn.
4009 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4010 }
4011
4012 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4013 if (E->getCastKind() == CK_LValueToRValue) {
4014 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4015 return;
4016 }
4017
4018 Inherited::VisitImplicitCastExpr(E);
4019 }
4020
4021 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4022 if (E->getConstructor()->isCopyConstructor()) {
4023 Expr *ArgExpr = E->getArg(0);
4024 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4025 if (ILE->getNumInits() == 1)
4026 ArgExpr = ILE->getInit(0);
4027 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4028 if (ICE->getCastKind() == CK_NoOp)
4029 ArgExpr = ICE->getSubExpr();
4030 HandleValue(ArgExpr, false /*AddressOf*/);
4031 return;
4032 }
4033 Inherited::VisitCXXConstructExpr(E);
4034 }
4035
4036 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4037 Expr *Callee = E->getCallee();
4038 if (isa<MemberExpr>(Callee)) {
4039 HandleValue(Callee, false /*AddressOf*/);
4040 for (auto *Arg : E->arguments())
4041 Visit(Arg);
4042 return;
4043 }
4044
4045 Inherited::VisitCXXMemberCallExpr(E);
4046 }
4047
4048 void VisitCallExpr(CallExpr *E) {
4049 // Treat std::move as a use.
4050 if (E->isCallToStdMove()) {
4051 HandleValue(E->getArg(0), /*AddressOf=*/false);
4052 return;
4053 }
4054
4055 Inherited::VisitCallExpr(E);
4056 }
4057
4058 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4059 Expr *Callee = E->getCallee();
4060
4061 if (isa<UnresolvedLookupExpr>(Callee))
4062 return Inherited::VisitCXXOperatorCallExpr(E);
4063
4064 Visit(Callee);
4065 for (auto *Arg : E->arguments())
4066 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4067 }
4068
4069 void VisitBinaryOperator(BinaryOperator *E) {
4070 // If a field assignment is detected, remove the field from the
4071 // uninitiailized field set.
4072 if (E->getOpcode() == BO_Assign)
4073 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4074 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4075 if (!FD->getType()->isReferenceType())
4076 DeclsToRemove.push_back(FD);
4077
4078 if (E->isCompoundAssignmentOp()) {
4079 HandleValue(E->getLHS(), false /*AddressOf*/);
4080 Visit(E->getRHS());
4081 return;
4082 }
4083
4084 Inherited::VisitBinaryOperator(E);
4085 }
4086
4087 void VisitUnaryOperator(UnaryOperator *E) {
4088 if (E->isIncrementDecrementOp()) {
4089 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4090 return;
4091 }
4092 if (E->getOpcode() == UO_AddrOf) {
4093 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4094 HandleValue(ME->getBase(), true /*AddressOf*/);
4095 return;
4096 }
4097 }
4098
4099 Inherited::VisitUnaryOperator(E);
4100 }
4101 };
4102
4103 // Diagnose value-uses of fields to initialize themselves, e.g.
4104 // foo(foo)
4105 // where foo is not also a parameter to the constructor.
4106 // Also diagnose across field uninitialized use such as
4107 // x(y), y(x)
4108 // TODO: implement -Wuninitialized and fold this into that framework.
4109 static void DiagnoseUninitializedFields(
4110 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4111
4112 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4113 Constructor->getLocation())) {
4114 return;
4115 }
4116
4117 if (Constructor->isInvalidDecl())
4118 return;
4119
4120 const CXXRecordDecl *RD = Constructor->getParent();
4121
4122 if (RD->isDependentContext())
4123 return;
4124
4125 // Holds fields that are uninitialized.
4126 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4127
4128 // At the beginning, all fields are uninitialized.
4129 for (auto *I : RD->decls()) {
4130 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4131 UninitializedFields.insert(FD);
4132 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4133 UninitializedFields.insert(IFD->getAnonField());
4134 }
4135 }
4136
4137 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4138 for (const auto &I : RD->bases())
4139 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4140
4141 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4142 return;
4143
4144 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4145 UninitializedFields,
4146 UninitializedBaseClasses);
4147
4148 for (const auto *FieldInit : Constructor->inits()) {
4149 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4150 break;
4151
4152 Expr *InitExpr = FieldInit->getInit();
4153 if (!InitExpr)
4154 continue;
4155
4156 if (CXXDefaultInitExpr *Default =
4157 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4158 InitExpr = Default->getExpr();
4159 if (!InitExpr)
4160 continue;
4161 // In class initializers will point to the constructor.
4162 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4163 FieldInit->getAnyMember(),
4164 FieldInit->getBaseClass());
4165 } else {
4166 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4167 FieldInit->getAnyMember(),
4168 FieldInit->getBaseClass());
4169 }
4170 }
4171 }
4172} // namespace
4173
4175 // Create a synthetic function scope to represent the call to the constructor
4176 // that notionally surrounds a use of this initializer.
4178}
4179
4181 if (!D.isFunctionDeclarator())
4182 return;
4183 auto &FTI = D.getFunctionTypeInfo();
4184 if (!FTI.Params)
4185 return;
4186 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4187 FTI.NumParams)) {
4188 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4189 if (ParamDecl->getDeclName())
4190 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4191 }
4192}
4193
4195 return ActOnRequiresClause(ConstraintExpr);
4196}
4197
4199 if (ConstraintExpr.isInvalid())
4200 return ExprError();
4201
4202 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4204 return ExprError();
4205
4206 return ConstraintExpr;
4207}
4208
4210 Expr *InitExpr,
4211 SourceLocation InitLoc) {
4212 InitializedEntity Entity =
4214 InitializationKind Kind =
4217 InitExpr->getBeginLoc(),
4218 InitExpr->getEndLoc())
4219 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4220 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4221 return Seq.Perform(*this, Entity, Kind, InitExpr);
4222}
4223
4225 SourceLocation InitLoc,
4226 ExprResult InitExpr) {
4227 // Pop the notional constructor scope we created earlier.
4228 PopFunctionScopeInfo(nullptr, D);
4229
4230 // Microsoft C++'s property declaration cannot have a default member
4231 // initializer.
4232 if (isa<MSPropertyDecl>(D)) {
4233 D->setInvalidDecl();
4234 return;
4235 }
4236
4237 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4238 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4239 "must set init style when field is created");
4240
4241 if (!InitExpr.isUsable() ||
4243 FD->setInvalidDecl();
4244 ExprResult RecoveryInit =
4245 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4246 if (RecoveryInit.isUsable())
4247 FD->setInClassInitializer(RecoveryInit.get());
4248 return;
4249 }
4250
4251 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4252 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr.get(), InitLoc);
4253 // C++11 [class.base.init]p7:
4254 // The initialization of each base and member constitutes a
4255 // full-expression.
4256 if (!InitExpr.isInvalid())
4257 InitExpr = ActOnFinishFullExpr(InitExpr.get(), /*DiscarededValue=*/false);
4258 if (InitExpr.isInvalid()) {
4259 FD->setInvalidDecl();
4260 return;
4261 }
4262 }
4263
4264 FD->setInClassInitializer(InitExpr.get());
4265}
4266
4267/// Find the direct and/or virtual base specifiers that
4268/// correspond to the given base type, for use in base initialization
4269/// within a constructor.
4270static bool FindBaseInitializer(Sema &SemaRef,
4271 CXXRecordDecl *ClassDecl,
4272 QualType BaseType,
4273 const CXXBaseSpecifier *&DirectBaseSpec,
4274 const CXXBaseSpecifier *&VirtualBaseSpec) {
4275 // First, check for a direct base class.
4276 DirectBaseSpec = nullptr;
4277 for (const auto &Base : ClassDecl->bases()) {
4278 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4279 // We found a direct base of this type. That's what we're
4280 // initializing.
4281 DirectBaseSpec = &Base;
4282 break;
4283 }
4284 }
4285
4286 // Check for a virtual base class.
4287 // FIXME: We might be able to short-circuit this if we know in advance that
4288 // there are no virtual bases.
4289 VirtualBaseSpec = nullptr;
4290 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4291 // We haven't found a base yet; search the class hierarchy for a
4292 // virtual base class.
4293 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4294 /*DetectVirtual=*/false);
4295 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4296 SemaRef.Context.getCanonicalTagType(ClassDecl),
4297 BaseType, Paths)) {
4298 for (const CXXBasePath &Path : Paths) {
4299 if (Path.back().Base->isVirtual()) {
4300 VirtualBaseSpec = Path.back().Base;
4301 break;
4302 }
4303 }
4304 }
4305 }
4306
4307 return DirectBaseSpec || VirtualBaseSpec;
4308}
4309
4312 Scope *S,
4313 CXXScopeSpec &SS,
4314 IdentifierInfo *MemberOrBase,
4315 ParsedType TemplateTypeTy,
4316 const DeclSpec &DS,
4317 SourceLocation IdLoc,
4318 Expr *InitList,
4319 SourceLocation EllipsisLoc) {
4320 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4321 DS, IdLoc, InitList,
4322 EllipsisLoc);
4323}
4324
4327 Scope *S,
4328 CXXScopeSpec &SS,
4329 IdentifierInfo *MemberOrBase,
4330 ParsedType TemplateTypeTy,
4331 const DeclSpec &DS,
4332 SourceLocation IdLoc,
4333 SourceLocation LParenLoc,
4334 ArrayRef<Expr *> Args,
4335 SourceLocation RParenLoc,
4336 SourceLocation EllipsisLoc) {
4337 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4338 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4339 DS, IdLoc, List, EllipsisLoc);
4340}
4341
4342namespace {
4343
4344// Callback to only accept typo corrections that can be a valid C++ member
4345// initializer: either a non-static field member or a base class.
4346class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4347public:
4348 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4349 : ClassDecl(ClassDecl) {}
4350
4351 bool ValidateCandidate(const TypoCorrection &candidate) override {
4352 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4353 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4354 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4355 return isa<TypeDecl>(ND);
4356 }
4357 return false;
4358 }
4359
4360 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4361 return std::make_unique<MemInitializerValidatorCCC>(*this);
4362 }
4363
4364private:
4365 CXXRecordDecl *ClassDecl;
4366};
4367
4368}
4369
4371 RecordDecl *ClassDecl,
4372 const IdentifierInfo *Name) {
4373 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4375 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4376 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4378 });
4379 // We did not find a placeholder variable
4380 if (Found == Result.end())
4381 return false;
4382 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4383 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4384 const NamedDecl *ND = *It;
4385 if (ND->getDeclContext() != ND->getDeclContext())
4386 break;
4389 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4390 }
4391 return true;
4392}
4393
4394ValueDecl *
4396 const IdentifierInfo *MemberOrBase) {
4397 ValueDecl *ND = nullptr;
4398 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4400 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4401 if (ND) {
4402 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4403 return nullptr;
4404 break;
4405 }
4406 if (!IsPlaceholder)
4407 return cast<ValueDecl>(D);
4408 ND = cast<ValueDecl>(D);
4409 }
4410 }
4411 return ND;
4412}
4413
4415 CXXScopeSpec &SS,
4416 ParsedType TemplateTypeTy,
4417 IdentifierInfo *MemberOrBase) {
4418 if (SS.getScopeRep() || TemplateTypeTy)
4419 return nullptr;
4420 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4421}
4422
4425 Scope *S,
4426 CXXScopeSpec &SS,
4427 IdentifierInfo *MemberOrBase,
4428 ParsedType TemplateTypeTy,
4429 const DeclSpec &DS,
4430 SourceLocation IdLoc,
4431 Expr *Init,
4432 SourceLocation EllipsisLoc) {
4433 if (!ConstructorD || !Init)
4434 return true;
4435
4436 AdjustDeclIfTemplate(ConstructorD);
4437
4439 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4440 if (!Constructor) {
4441 // The user wrote a constructor initializer on a function that is
4442 // not a C++ constructor. Ignore the error for now, because we may
4443 // have more member initializers coming; we'll diagnose it just
4444 // once in ActOnMemInitializers.
4445 return true;
4446 }
4447
4448 CXXRecordDecl *ClassDecl = Constructor->getParent();
4449
4450 // C++ [class.base.init]p2:
4451 // Names in a mem-initializer-id are looked up in the scope of the
4452 // constructor's class and, if not found in that scope, are looked
4453 // up in the scope containing the constructor's definition.
4454 // [Note: if the constructor's class contains a member with the
4455 // same name as a direct or virtual base class of the class, a
4456 // mem-initializer-id naming the member or base class and composed
4457 // of a single identifier refers to the class member. A
4458 // mem-initializer-id for the hidden base class may be specified
4459 // using a qualified name. ]
4460
4461 // Look for a member, first.
4463 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4464 if (EllipsisLoc.isValid())
4465 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4466 << MemberOrBase
4467 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4468
4469 return BuildMemberInitializer(Member, Init, IdLoc);
4470 }
4471 // It didn't name a member, so see if it names a class.
4472 QualType BaseType;
4473 TypeSourceInfo *TInfo = nullptr;
4474
4475 if (TemplateTypeTy) {
4476 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4477 if (BaseType.isNull())
4478 return true;
4479 } else if (DS.getTypeSpecType() == TST_decltype) {
4480 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4481 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4482 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4483 return true;
4484 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4485 BaseType =
4487 DS.getBeginLoc(), DS.getEllipsisLoc());
4488 } else {
4489 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4490 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4491
4492 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4493 if (!TyD) {
4494 if (R.isAmbiguous()) return true;
4495
4496 // We don't want access-control diagnostics here.
4497 R.suppressDiagnostics();
4498
4499 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4500 bool NotUnknownSpecialization = false;
4501 DeclContext *DC = computeDeclContext(SS, false);
4502 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4503 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4504
4505 if (!NotUnknownSpecialization) {
4506 // When the scope specifier can refer to a member of an unknown
4507 // specialization, we take it as a type name.
4508 BaseType = CheckTypenameType(
4510 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4511 if (BaseType.isNull())
4512 return true;
4513
4514 TInfo = Context.CreateTypeSourceInfo(BaseType);
4517 if (!TL.isNull()) {
4518 TL.setNameLoc(IdLoc);
4521 }
4522
4523 R.clear();
4524 R.setLookupName(MemberOrBase);
4525 }
4526 }
4527
4528 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4529 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4530 auto *TempSpec = cast<TemplateSpecializationType>(
4531 UnqualifiedBase->getCanonicalInjectedSpecializationType(Context));
4532 TemplateName TN = TempSpec->getTemplateName();
4533 for (auto const &Base : ClassDecl->bases()) {
4534 auto BaseTemplate =
4535 Base.getType()->getAs<TemplateSpecializationType>();
4536 if (BaseTemplate &&
4537 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4538 /*IgnoreDeduced=*/true)) {
4539 Diag(IdLoc, diag::ext_unqualified_base_class)
4540 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4541 BaseType = Base.getType();
4542 break;
4543 }
4544 }
4545 }
4546 }
4547
4548 // If no results were found, try to correct typos.
4549 TypoCorrection Corr;
4550 MemInitializerValidatorCCC CCC(ClassDecl);
4551 if (R.empty() && BaseType.isNull() &&
4552 (Corr =
4553 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4554 CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {
4556 // We have found a non-static data member with a similar
4557 // name to what was typed; complain and initialize that
4558 // member.
4559 diagnoseTypo(Corr,
4560 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4561 << MemberOrBase << true);
4562 return BuildMemberInitializer(Member, Init, IdLoc);
4563 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4564 const CXXBaseSpecifier *DirectBaseSpec;
4565 const CXXBaseSpecifier *VirtualBaseSpec;
4566 if (FindBaseInitializer(*this, ClassDecl,
4567 Context.getTypeDeclType(Type),
4568 DirectBaseSpec, VirtualBaseSpec)) {
4569 // We have found a direct or virtual base class with a
4570 // similar name to what was typed; complain and initialize
4571 // that base class.
4572 diagnoseTypo(Corr,
4573 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4574 << MemberOrBase << false,
4575 PDiag() /*Suppress note, we provide our own.*/);
4576
4577 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4578 : VirtualBaseSpec;
4579 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4580 << BaseSpec->getType() << BaseSpec->getSourceRange();
4581
4582 TyD = Type;
4583 }
4584 }
4585 }
4586
4587 if (!TyD && BaseType.isNull()) {
4588 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4589 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4590 return true;
4591 }
4592 }
4593
4594 if (BaseType.isNull()) {
4595 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4596
4597 TypeLocBuilder TLB;
4598 // FIXME: This is missing building the UsingType for TyD, if any.
4599 if (const auto *TD = dyn_cast<TagDecl>(TyD)) {
4600 BaseType = Context.getTagType(ElaboratedTypeKeyword::None,
4601 SS.getScopeRep(), TD, /*OwnsTag=*/false);
4602 auto TL = TLB.push<TagTypeLoc>(BaseType);
4604 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4605 TL.setNameLoc(IdLoc);
4606 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TyD)) {
4607 BaseType = Context.getTypedefType(ElaboratedTypeKeyword::None,
4608 SS.getScopeRep(), TN);
4609 TLB.push<TypedefTypeLoc>(BaseType).set(
4610 /*ElaboratedKeywordLoc=*/SourceLocation(),
4611 SS.getWithLocInContext(Context), IdLoc);
4612 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TyD)) {
4613 BaseType = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
4614 SS.getScopeRep(), UD);
4615 TLB.push<UnresolvedUsingTypeLoc>(BaseType).set(
4616 /*ElaboratedKeywordLoc=*/SourceLocation(),
4617 SS.getWithLocInContext(Context), IdLoc);
4618 } else {
4619 // FIXME: What else can appear here?
4620 assert(SS.isEmpty());
4621 BaseType = Context.getTypeDeclType(TyD);
4622 TLB.pushTypeSpec(BaseType).setNameLoc(IdLoc);
4623 }
4624 TInfo = TLB.getTypeSourceInfo(Context, BaseType);
4625 }
4626 }
4627
4628 if (!TInfo)
4629 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4630
4631 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4632}
4633
4636 SourceLocation IdLoc) {
4637 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4638 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4639 assert((DirectMember || IndirectMember) &&
4640 "Member must be a FieldDecl or IndirectFieldDecl");
4641
4643 return true;
4644
4645 if (Member->isInvalidDecl())
4646 return true;
4647
4648 MultiExprArg Args;
4649 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4650 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4651 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4652 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4653 } else {
4654 // Template instantiation doesn't reconstruct ParenListExprs for us.
4655 Args = Init;
4656 }
4657
4658 SourceRange InitRange = Init->getSourceRange();
4659
4660 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4661 // Can't check initialization for a member of dependent type or when
4662 // any of the arguments are type-dependent expressions.
4664 } else {
4665 bool InitList = false;
4666 if (isa<InitListExpr>(Init)) {
4667 InitList = true;
4668 Args = Init;
4669 }
4670
4671 // Initialize the member.
4672 InitializedEntity MemberEntity =
4673 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4674 : InitializedEntity::InitializeMember(IndirectMember,
4675 nullptr);
4676 InitializationKind Kind =
4678 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4679 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4680 InitRange.getEnd());
4681
4682 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4683 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4684 nullptr);
4685 if (!MemberInit.isInvalid()) {
4686 // C++11 [class.base.init]p7:
4687 // The initialization of each base and member constitutes a
4688 // full-expression.
4689 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4690 /*DiscardedValue*/ false);
4691 }
4692
4693 if (MemberInit.isInvalid()) {
4694 // Args were sensible expressions but we couldn't initialize the member
4695 // from them. Preserve them in a RecoveryExpr instead.
4696 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4697 Member->getType())
4698 .get();
4699 if (!Init)
4700 return true;
4701 } else {
4702 Init = MemberInit.get();
4703 }
4704 }
4705
4706 if (DirectMember) {
4707 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4708 InitRange.getBegin(), Init,
4709 InitRange.getEnd());
4710 } else {
4711 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4712 InitRange.getBegin(), Init,
4713 InitRange.getEnd());
4714 }
4715}
4716
4719 CXXRecordDecl *ClassDecl) {
4720 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4721 if (!LangOpts.CPlusPlus11)
4722 return Diag(NameLoc, diag::err_delegating_ctor)
4723 << TInfo->getTypeLoc().getSourceRange();
4724 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4725
4726 bool InitList = true;
4727 MultiExprArg Args = Init;
4728 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4729 InitList = false;
4730 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4731 }
4732
4733 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
4734
4735 SourceRange InitRange = Init->getSourceRange();
4736 // Initialize the object.
4737 InitializedEntity DelegationEntity =
4739 InitializationKind Kind =
4741 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4742 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4743 InitRange.getEnd());
4744 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4745 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4746 Args, nullptr);
4747 if (!DelegationInit.isInvalid()) {
4748 assert((DelegationInit.get()->containsErrors() ||
4749 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4750 "Delegating constructor with no target?");
4751
4752 // C++11 [class.base.init]p7:
4753 // The initialization of each base and member constitutes a
4754 // full-expression.
4755 DelegationInit = ActOnFinishFullExpr(
4756 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4757 }
4758
4759 if (DelegationInit.isInvalid()) {
4760 DelegationInit = CreateRecoveryExpr(InitRange.getBegin(),
4761 InitRange.getEnd(), Args, ClassType);
4762 if (DelegationInit.isInvalid())
4763 return true;
4764 } else {
4765 // If we are in a dependent context, template instantiation will
4766 // perform this type-checking again. Just save the arguments that we
4767 // received in a ParenListExpr.
4768 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4769 // of the information that we have about the base
4770 // initializer. However, deconstructing the ASTs is a dicey process,
4771 // and this approach is far more likely to get the corner cases right.
4772 if (CurContext->isDependentContext())
4773 DelegationInit = Init;
4774 }
4775
4776 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4777 DelegationInit.getAs<Expr>(),
4778 InitRange.getEnd());
4779}
4780
4783 Expr *Init, CXXRecordDecl *ClassDecl,
4784 SourceLocation EllipsisLoc) {
4785 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4786
4787 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4788 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4789 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4790
4791 // C++ [class.base.init]p2:
4792 // [...] Unless the mem-initializer-id names a nonstatic data
4793 // member of the constructor's class or a direct or virtual base
4794 // of that class, the mem-initializer is ill-formed. A
4795 // mem-initializer-list can initialize a base class using any
4796 // name that denotes that base class type.
4797
4798 // We can store the initializers in "as-written" form and delay analysis until
4799 // instantiation if the constructor is dependent. But not for dependent
4800 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4801 bool Dependent = CurContext->isDependentContext() &&
4802 (BaseType->isDependentType() || Init->isTypeDependent());
4803
4804 SourceRange InitRange = Init->getSourceRange();
4805 if (EllipsisLoc.isValid()) {
4806 // This is a pack expansion.
4807 if (!BaseType->containsUnexpandedParameterPack()) {
4808 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4809 << SourceRange(BaseLoc, InitRange.getEnd());
4810
4811 EllipsisLoc = SourceLocation();
4812 }
4813 } else {
4814 // Check for any unexpanded parameter packs.
4815 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4816 return true;
4817
4819 return true;
4820 }
4821
4822 // Check for direct and virtual base classes.
4823 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4824 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4825 if (!Dependent) {
4826 if (declaresSameEntity(ClassDecl, BaseType->getAsCXXRecordDecl()))
4827 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4828
4829 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4830 VirtualBaseSpec);
4831
4832 // C++ [base.class.init]p2:
4833 // Unless the mem-initializer-id names a nonstatic data member of the
4834 // constructor's class or a direct or virtual base of that class, the
4835 // mem-initializer is ill-formed.
4836 if (!DirectBaseSpec && !VirtualBaseSpec) {
4837 // If the class has any dependent bases, then it's possible that
4838 // one of those types will resolve to the same type as
4839 // BaseType. Therefore, just treat this as a dependent base
4840 // class initialization. FIXME: Should we try to check the
4841 // initialization anyway? It seems odd.
4842 if (ClassDecl->hasAnyDependentBases())
4843 Dependent = true;
4844 else
4845 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4846 << BaseType << Context.getCanonicalTagType(ClassDecl)
4847 << BaseTInfo->getTypeLoc().getSourceRange();
4848 }
4849 }
4850
4851 if (Dependent) {
4853
4854 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4855 /*IsVirtual=*/false,
4856 InitRange.getBegin(), Init,
4857 InitRange.getEnd(), EllipsisLoc);
4858 }
4859
4860 // C++ [base.class.init]p2:
4861 // If a mem-initializer-id is ambiguous because it designates both
4862 // a direct non-virtual base class and an inherited virtual base
4863 // class, the mem-initializer is ill-formed.
4864 if (DirectBaseSpec && VirtualBaseSpec)
4865 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4866 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4867
4868 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4869 if (!BaseSpec)
4870 BaseSpec = VirtualBaseSpec;
4871
4872 // Initialize the base.
4873 bool InitList = true;
4874 MultiExprArg Args = Init;
4875 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4876 InitList = false;
4877 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4878 }
4879
4880 InitializedEntity BaseEntity =
4881 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4882 InitializationKind Kind =
4883 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4884 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4885 InitRange.getEnd());
4886 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4887 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4888 if (!BaseInit.isInvalid()) {
4889 // C++11 [class.base.init]p7:
4890 // The initialization of each base and member constitutes a
4891 // full-expression.
4892 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4893 /*DiscardedValue*/ false);
4894 }
4895
4896 if (BaseInit.isInvalid()) {
4897 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4898 Args, BaseType);
4899 if (BaseInit.isInvalid())
4900 return true;
4901 } else {
4902 // If we are in a dependent context, template instantiation will
4903 // perform this type-checking again. Just save the arguments that we
4904 // received in a ParenListExpr.
4905 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4906 // of the information that we have about the base
4907 // initializer. However, deconstructing the ASTs is a dicey process,
4908 // and this approach is far more likely to get the corner cases right.
4909 if (CurContext->isDependentContext())
4910 BaseInit = Init;
4911 }
4912
4913 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4914 BaseSpec->isVirtual(),
4915 InitRange.getBegin(),
4916 BaseInit.getAs<Expr>(),
4917 InitRange.getEnd(), EllipsisLoc);
4918}
4919
4920// Create a static_cast<T&&>(expr).
4921static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4922 QualType TargetType =
4923 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4925 SourceLocation ExprLoc = E->getBeginLoc();
4926 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4927 TargetType, ExprLoc);
4928
4929 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4930 SourceRange(ExprLoc, ExprLoc),
4931 E->getSourceRange()).get();
4932}
4933
4934/// ImplicitInitializerKind - How an implicit base or member initializer should
4935/// initialize its base or member.
4942
4943static bool
4945 ImplicitInitializerKind ImplicitInitKind,
4946 CXXBaseSpecifier *BaseSpec,
4947 bool IsInheritedVirtualBase,
4948 CXXCtorInitializer *&CXXBaseInit) {
4949 InitializedEntity InitEntity
4950 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4951 IsInheritedVirtualBase);
4952
4953 ExprResult BaseInit;
4954
4955 switch (ImplicitInitKind) {
4956 case IIK_Inherit:
4957 case IIK_Default: {
4958 InitializationKind InitKind
4960 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4961 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
4962 break;
4963 }
4964
4965 case IIK_Move:
4966 case IIK_Copy: {
4967 bool Moving = ImplicitInitKind == IIK_Move;
4968 ParmVarDecl *Param = Constructor->getParamDecl(0);
4969 QualType ParamType = Param->getType().getNonReferenceType();
4970
4971 Expr *CopyCtorArg =
4973 SourceLocation(), Param, false,
4974 Constructor->getLocation(), ParamType,
4975 VK_LValue, nullptr);
4976
4977 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4978
4979 // Cast to the base class to avoid ambiguities.
4980 QualType ArgTy =
4981 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4982 ParamType.getQualifiers());
4983
4984 if (Moving) {
4985 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4986 }
4987
4988 CXXCastPath BasePath;
4989 BasePath.push_back(BaseSpec);
4990 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4991 CK_UncheckedDerivedToBase,
4992 Moving ? VK_XValue : VK_LValue,
4993 &BasePath).get();
4994
4995 InitializationKind InitKind
4998 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4999 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
5000 break;
5001 }
5002 }
5003
5004 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
5005 if (BaseInit.isInvalid())
5006 return true;
5007
5008 CXXBaseInit =
5009 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5010 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
5011 SourceLocation()),
5012 BaseSpec->isVirtual(),
5014 BaseInit.getAs<Expr>(),
5016 SourceLocation());
5017
5018 return false;
5019}
5020
5021static bool RefersToRValueRef(Expr *MemRef) {
5022 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5023 return Referenced->getType()->isRValueReferenceType();
5024}
5025
5026static bool
5028 ImplicitInitializerKind ImplicitInitKind,
5029 FieldDecl *Field, IndirectFieldDecl *Indirect,
5030 CXXCtorInitializer *&CXXMemberInit) {
5031 if (Field->isInvalidDecl())
5032 return true;
5033
5034 SourceLocation Loc = Constructor->getLocation();
5035
5036 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5037 bool Moving = ImplicitInitKind == IIK_Move;
5038 ParmVarDecl *Param = Constructor->getParamDecl(0);
5039 QualType ParamType = Param->getType().getNonReferenceType();
5040
5041 // Suppress copying zero-width bitfields.
5042 if (Field->isZeroLengthBitField())
5043 return false;
5044
5045 Expr *MemberExprBase =
5047 SourceLocation(), Param, false,
5048 Loc, ParamType, VK_LValue, nullptr);
5049
5050 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5051
5052 if (Moving) {
5053 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5054 }
5055
5056 // Build a reference to this field within the parameter.
5057 CXXScopeSpec SS;
5058 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5060 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5061 : cast<ValueDecl>(Field), AS_public);
5062 MemberLookup.resolveKind();
5063 ExprResult CtorArg
5064 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5065 ParamType, Loc,
5066 /*IsArrow=*/false,
5067 SS,
5068 /*TemplateKWLoc=*/SourceLocation(),
5069 /*FirstQualifierInScope=*/nullptr,
5070 MemberLookup,
5071 /*TemplateArgs=*/nullptr,
5072 /*S*/nullptr);
5073 if (CtorArg.isInvalid())
5074 return true;
5075
5076 // C++11 [class.copy]p15:
5077 // - if a member m has rvalue reference type T&&, it is direct-initialized
5078 // with static_cast<T&&>(x.m);
5079 if (RefersToRValueRef(CtorArg.get())) {
5080 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5081 }
5082
5083 InitializedEntity Entity =
5086
5087 // Direct-initialize to use the copy constructor.
5088 InitializationKind InitKind =
5090
5091 Expr *CtorArgE = CtorArg.getAs<Expr>();
5092 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5093 ExprResult MemberInit =
5094 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5095 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5096 if (MemberInit.isInvalid())
5097 return true;
5098
5099 if (Indirect)
5100 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5101 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5102 else
5103 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5104 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5105 return false;
5106 }
5107
5108 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5109 "Unhandled implicit init kind!");
5110
5111 QualType FieldBaseElementType =
5112 SemaRef.Context.getBaseElementType(Field->getType());
5113
5114 if (FieldBaseElementType->isRecordType()) {
5115 InitializedEntity InitEntity =
5118 InitializationKind InitKind =
5120
5121 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5122 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5123
5124 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5125 if (MemberInit.isInvalid())
5126 return true;
5127
5128 if (Indirect)
5129 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5130 Indirect, Loc,
5131 Loc,
5132 MemberInit.get(),
5133 Loc);
5134 else
5135 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5136 Field, Loc, Loc,
5137 MemberInit.get(),
5138 Loc);
5139 return false;
5140 }
5141
5142 if (!Field->getParent()->isUnion()) {
5143 if (FieldBaseElementType->isReferenceType()) {
5144 SemaRef.Diag(Constructor->getLocation(),
5145 diag::err_uninitialized_member_in_ctor)
5146 << (int)Constructor->isImplicit()
5147 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 0
5148 << Field->getDeclName();
5149 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5150 return true;
5151 }
5152
5153 if (FieldBaseElementType.isConstQualified()) {
5154 SemaRef.Diag(Constructor->getLocation(),
5155 diag::err_uninitialized_member_in_ctor)
5156 << (int)Constructor->isImplicit()
5157 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 1
5158 << Field->getDeclName();
5159 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5160 return true;
5161 }
5162 }
5163
5164 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5165 // ARC and Weak:
5166 // Default-initialize Objective-C pointers to NULL.
5167 CXXMemberInit
5168 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5169 Loc, Loc,
5170 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5171 Loc);
5172 return false;
5173 }
5174
5175 // Nothing to initialize.
5176 CXXMemberInit = nullptr;
5177 return false;
5178}
5179
5180namespace {
5181struct BaseAndFieldInfo {
5182 Sema &S;
5183 CXXConstructorDecl *Ctor;
5184 bool AnyErrorsInInits;
5186 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5187 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5188 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5189
5190 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5191 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5192 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5193 if (Ctor->getInheritedConstructor())
5194 IIK = IIK_Inherit;
5195 else if (Generated && Ctor->isCopyConstructor())
5196 IIK = IIK_Copy;
5197 else if (Generated && Ctor->isMoveConstructor())
5198 IIK = IIK_Move;
5199 else
5200 IIK = IIK_Default;
5201 }
5202
5203 bool isImplicitCopyOrMove() const {
5204 switch (IIK) {
5205 case IIK_Copy:
5206 case IIK_Move:
5207 return true;
5208
5209 case IIK_Default:
5210 case IIK_Inherit:
5211 return false;
5212 }
5213
5214 llvm_unreachable("Invalid ImplicitInitializerKind!");
5215 }
5216
5217 bool addFieldInitializer(CXXCtorInitializer *Init) {
5218 AllToInit.push_back(Init);
5219
5220 // Check whether this initializer makes the field "used".
5221 if (Init->getInit()->HasSideEffects(S.Context))
5222 S.UnusedPrivateFields.remove(Init->getAnyMember());
5223
5224 return false;
5225 }
5226
5227 bool isInactiveUnionMember(FieldDecl *Field) {
5228 RecordDecl *Record = Field->getParent();
5229 if (!Record->isUnion())
5230 return false;
5231
5232 if (FieldDecl *Active =
5233 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5234 return Active != Field->getCanonicalDecl();
5235
5236 // In an implicit copy or move constructor, ignore any in-class initializer.
5237 if (isImplicitCopyOrMove())
5238 return true;
5239
5240 // If there's no explicit initialization, the field is active only if it
5241 // has an in-class initializer...
5242 if (Field->hasInClassInitializer())
5243 return false;
5244 // ... or it's an anonymous struct or union whose class has an in-class
5245 // initializer.
5246 if (!Field->isAnonymousStructOrUnion())
5247 return true;
5248 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5249 return !FieldRD->hasInClassInitializer();
5250 }
5251
5252 /// Determine whether the given field is, or is within, a union member
5253 /// that is inactive (because there was an initializer given for a different
5254 /// member of the union, or because the union was not initialized at all).
5255 bool isWithinInactiveUnionMember(FieldDecl *Field,
5256 IndirectFieldDecl *Indirect) {
5257 if (!Indirect)
5258 return isInactiveUnionMember(Field);
5259
5260 for (auto *C : Indirect->chain()) {
5261 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5262 if (Field && isInactiveUnionMember(Field))
5263 return true;
5264 }
5265 return false;
5266 }
5267};
5268}
5269
5270/// Determine whether the given type is an incomplete or zero-lenfgth
5271/// array type.
5273 if (T->isIncompleteArrayType())
5274 return true;
5275
5276 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5277 if (ArrayT->isZeroSize())
5278 return true;
5279
5280 T = ArrayT->getElementType();
5281 }
5282
5283 return false;
5284}
5285
5286static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5287 FieldDecl *Field,
5288 IndirectFieldDecl *Indirect = nullptr) {
5289 if (Field->isInvalidDecl())
5290 return false;
5291
5292 // Overwhelmingly common case: we have a direct initializer for this field.
5294 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5295 return Info.addFieldInitializer(Init);
5296
5297 // C++11 [class.base.init]p8:
5298 // if the entity is a non-static data member that has a
5299 // brace-or-equal-initializer and either
5300 // -- the constructor's class is a union and no other variant member of that
5301 // union is designated by a mem-initializer-id or
5302 // -- the constructor's class is not a union, and, if the entity is a member
5303 // of an anonymous union, no other member of that union is designated by
5304 // a mem-initializer-id,
5305 // the entity is initialized as specified in [dcl.init].
5306 //
5307 // We also apply the same rules to handle anonymous structs within anonymous
5308 // unions.
5309 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5310 return false;
5311
5312 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5313 ExprResult DIE =
5314 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5315 if (DIE.isInvalid())
5316 return true;
5317
5319 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5320
5322 if (Indirect)
5323 Init = new (SemaRef.Context)
5324 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5325 SourceLocation(), DIE.get(), SourceLocation());
5326 else
5327 Init = new (SemaRef.Context)
5328 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5329 SourceLocation(), DIE.get(), SourceLocation());
5330 return Info.addFieldInitializer(Init);
5331 }
5332
5333 // Don't initialize incomplete or zero-length arrays.
5334 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5335 return false;
5336
5337 // Don't try to build an implicit initializer if there were semantic
5338 // errors in any of the initializers (and therefore we might be
5339 // missing some that the user actually wrote).
5340 if (Info.AnyErrorsInInits)
5341 return false;
5342
5343 CXXCtorInitializer *Init = nullptr;
5344 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5345 Indirect, Init))
5346 return true;
5347
5348 if (!Init)
5349 return false;
5350
5351 return Info.addFieldInitializer(Init);
5352}
5353
5354bool
5357 assert(Initializer->isDelegatingInitializer());
5358 Constructor->setNumCtorInitializers(1);
5359 CXXCtorInitializer **initializer =
5360 new (Context) CXXCtorInitializer*[1];
5361 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5362 Constructor->setCtorInitializers(initializer);
5363
5364 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5365 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5366 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5367 }
5368
5370
5371 DiagnoseUninitializedFields(*this, Constructor);
5372
5373 return false;
5374}
5375
5377 CXXRecordDecl *Class) {
5378 if (Class->isInvalidDecl())
5379 return nullptr;
5380 if (Class->hasIrrelevantDestructor())
5381 return nullptr;
5382
5383 // Dtor might still be missing, e.g because it's invalid.
5384 return S.LookupDestructor(Class);
5385}
5386
5388 FieldDecl *Field) {
5389 if (Field->isInvalidDecl())
5390 return;
5391
5392 // Don't destroy incomplete or zero-length arrays.
5393 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5394 return;
5395
5396 QualType FieldType = S.Context.getBaseElementType(Field->getType());
5397
5398 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5399 if (!FieldClassDecl)
5400 return;
5401
5402 // The destructor for an implicit anonymous union member is never invoked.
5403 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5404 return;
5405
5406 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5407 if (!Dtor)
5408 return;
5409
5410 S.CheckDestructorAccess(Field->getLocation(), Dtor,
5411 S.PDiag(diag::err_access_dtor_field)
5412 << Field->getDeclName() << FieldType);
5413
5414 S.MarkFunctionReferenced(Location, Dtor);
5415 S.DiagnoseUseOfDecl(Dtor, Location);
5416}
5417
5419 CXXRecordDecl *ClassDecl) {
5420 if (ClassDecl->isDependentContext())
5421 return;
5422
5423 // We only potentially invoke the destructors of potentially constructed
5424 // subobjects.
5425 bool VisitVirtualBases = !ClassDecl->isAbstract();
5426
5427 // If the destructor exists and has already been marked used in the MS ABI,
5428 // then virtual base destructors have already been checked and marked used.
5429 // Skip checking them again to avoid duplicate diagnostics.
5431 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5432 if (Dtor && Dtor->isUsed())
5433 VisitVirtualBases = false;
5434 }
5435
5437
5438 // Bases.
5439 for (const auto &Base : ClassDecl->bases()) {
5440 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5441 if (!BaseClassDecl)
5442 continue;
5443
5444 // Remember direct virtual bases.
5445 if (Base.isVirtual()) {
5446 if (!VisitVirtualBases)
5447 continue;
5448 DirectVirtualBases.insert(BaseClassDecl);
5449 }
5450
5451 auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);
5452 if (!Dtor)
5453 continue;
5454
5455 // FIXME: caret should be on the start of the class name
5456 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5457 S.PDiag(diag::err_access_dtor_base)
5458 << Base.getType() << Base.getSourceRange(),
5459 S.Context.getCanonicalTagType(ClassDecl));
5460
5461 S.MarkFunctionReferenced(Location, Dtor);
5462 S.DiagnoseUseOfDecl(Dtor, Location);
5463 }
5464
5465 if (VisitVirtualBases)
5466 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5467 &DirectVirtualBases);
5468}
5469
5471 ArrayRef<CXXCtorInitializer *> Initializers) {
5472 if (Constructor->isDependentContext()) {
5473 // Just store the initializers as written, they will be checked during
5474 // instantiation.
5475 if (!Initializers.empty()) {
5476 Constructor->setNumCtorInitializers(Initializers.size());
5477 CXXCtorInitializer **baseOrMemberInitializers =
5478 new (Context) CXXCtorInitializer*[Initializers.size()];
5479 memcpy(baseOrMemberInitializers, Initializers.data(),
5480 Initializers.size() * sizeof(CXXCtorInitializer*));
5481 Constructor->setCtorInitializers(baseOrMemberInitializers);
5482 }
5483
5484 // Let template instantiation know whether we had errors.
5485 if (AnyErrors)
5486 Constructor->setInvalidDecl();
5487
5488 return false;
5489 }
5490
5491 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5492
5493 // We need to build the initializer AST according to order of construction
5494 // and not what user specified in the Initializers list.
5495 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5496 if (!ClassDecl)
5497 return true;
5498
5499 bool HadError = false;
5500
5501 for (CXXCtorInitializer *Member : Initializers) {
5502 if (Member->isBaseInitializer())
5503 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5504 Member;
5505 else {
5506 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5507
5508 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5509 for (auto *C : F->chain()) {
5510 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5511 if (FD && FD->getParent()->isUnion())
5512 Info.ActiveUnionMember.insert(std::make_pair(
5514 }
5515 } else if (FieldDecl *FD = Member->getMember()) {
5516 if (FD->getParent()->isUnion())
5517 Info.ActiveUnionMember.insert(std::make_pair(
5519 }
5520 }
5521 }
5522
5523 // Keep track of the direct virtual bases.
5525 for (auto &I : ClassDecl->bases()) {
5526 if (I.isVirtual())
5527 DirectVBases.insert(&I);
5528 }
5529
5530 // Push virtual bases before others.
5531 for (auto &VBase : ClassDecl->vbases()) {
5532 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5533 VBase.getType()->getAsCanonical<RecordType>())) {
5534 // [class.base.init]p7, per DR257:
5535 // A mem-initializer where the mem-initializer-id names a virtual base
5536 // class is ignored during execution of a constructor of any class that
5537 // is not the most derived class.
5538 if (ClassDecl->isAbstract()) {
5539 // FIXME: Provide a fixit to remove the base specifier. This requires
5540 // tracking the location of the associated comma for a base specifier.
5541 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5542 << VBase.getType() << ClassDecl;
5543 DiagnoseAbstractType(ClassDecl);
5544 }
5545
5546 Info.AllToInit.push_back(Value);
5547 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5548 // [class.base.init]p8, per DR257:
5549 // If a given [...] base class is not named by a mem-initializer-id
5550 // [...] and the entity is not a virtual base class of an abstract
5551 // class, then [...] the entity is default-initialized.
5552 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5553 CXXCtorInitializer *CXXBaseInit;
5554 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5555 &VBase, IsInheritedVirtualBase,
5556 CXXBaseInit)) {
5557 HadError = true;
5558 continue;
5559 }
5560
5561 Info.AllToInit.push_back(CXXBaseInit);
5562 }
5563 }
5564
5565 // Non-virtual bases.
5566 for (auto &Base : ClassDecl->bases()) {
5567 // Virtuals are in the virtual base list and already constructed.
5568 if (Base.isVirtual())
5569 continue;
5570
5571 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5572 Base.getType()->getAsCanonical<RecordType>())) {
5573 Info.AllToInit.push_back(Value);
5574 } else if (!AnyErrors) {
5575 CXXCtorInitializer *CXXBaseInit;
5576 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5577 &Base, /*IsInheritedVirtualBase=*/false,
5578 CXXBaseInit)) {
5579 HadError = true;
5580 continue;
5581 }
5582
5583 Info.AllToInit.push_back(CXXBaseInit);
5584 }
5585 }
5586
5587 // Fields.
5588 for (auto *Mem : ClassDecl->decls()) {
5589 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5590 // C++ [class.bit]p2:
5591 // A declaration for a bit-field that omits the identifier declares an
5592 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5593 // initialized.
5594 if (F->isUnnamedBitField())
5595 continue;
5596
5597 // If we're not generating the implicit copy/move constructor, then we'll
5598 // handle anonymous struct/union fields based on their individual
5599 // indirect fields.
5600 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5601 continue;
5602
5603 if (CollectFieldInitializer(*this, Info, F))
5604 HadError = true;
5605 continue;
5606 }
5607
5608 // Beyond this point, we only consider default initialization.
5609 if (Info.isImplicitCopyOrMove())
5610 continue;
5611
5612 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5613 if (F->getType()->isIncompleteArrayType()) {
5614 assert(ClassDecl->hasFlexibleArrayMember() &&
5615 "Incomplete array type is not valid");
5616 continue;
5617 }
5618
5619 // Initialize each field of an anonymous struct individually.
5620 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5621 HadError = true;
5622
5623 continue;
5624 }
5625 }
5626
5627 unsigned NumInitializers = Info.AllToInit.size();
5628 if (NumInitializers > 0) {
5629 Constructor->setNumCtorInitializers(NumInitializers);
5630 CXXCtorInitializer **baseOrMemberInitializers =
5631 new (Context) CXXCtorInitializer*[NumInitializers];
5632 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5633 NumInitializers * sizeof(CXXCtorInitializer*));
5634 Constructor->setCtorInitializers(baseOrMemberInitializers);
5635
5636 SourceLocation Location = Constructor->getLocation();
5637
5638 // Constructors implicitly reference the base and member
5639 // destructors.
5640
5641 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5642 FieldDecl *Field = Initializer->getAnyMember();
5643 if (!Field)
5644 continue;
5645
5646 // C++ [class.base.init]p12:
5647 // In a non-delegating constructor, the destructor for each
5648 // potentially constructed subobject of class type is potentially
5649 // invoked.
5650 MarkFieldDestructorReferenced(*this, Location, Field);
5651 }
5652
5653 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5654 }
5655
5656 return HadError;
5657}
5658
5660 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5661 const RecordDecl *RD = RT->getDecl();
5662 if (RD->isAnonymousStructOrUnion()) {
5663 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5664 PopulateKeysForFields(Field, IdealInits);
5665 return;
5666 }
5667 }
5668 IdealInits.push_back(Field->getCanonicalDecl());
5669}
5670
5671static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5672 return Context.getCanonicalType(BaseType).getTypePtr();
5673}
5674
5675static const void *GetKeyForMember(ASTContext &Context,
5677 if (!Member->isAnyMemberInitializer())
5678 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5679
5680 return Member->getAnyMember()->getCanonicalDecl();
5681}
5682
5685 const CXXCtorInitializer *Current) {
5686 if (Previous->isAnyMemberInitializer())
5687 Diag << 0 << Previous->getAnyMember();
5688 else
5689 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5690
5691 if (Current->isAnyMemberInitializer())
5692 Diag << 0 << Current->getAnyMember();
5693 else
5694 Diag << 1 << Current->getTypeSourceInfo()->getType();
5695}
5696
5698 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5700 if (Constructor->getDeclContext()->isDependentContext())
5701 return;
5702
5703 // Don't check initializers order unless the warning is enabled at the
5704 // location of at least one initializer.
5705 bool ShouldCheckOrder = false;
5706 for (const CXXCtorInitializer *Init : Inits) {
5707 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5708 Init->getSourceLocation())) {
5709 ShouldCheckOrder = true;
5710 break;
5711 }
5712 }
5713 if (!ShouldCheckOrder)
5714 return;
5715
5716 // Build the list of bases and members in the order that they'll
5717 // actually be initialized. The explicit initializers should be in
5718 // this same order but may be missing things.
5719 SmallVector<const void*, 32> IdealInitKeys;
5720
5721 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5722
5723 // 1. Virtual bases.
5724 for (const auto &VBase : ClassDecl->vbases())
5725 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5726
5727 // 2. Non-virtual bases.
5728 for (const auto &Base : ClassDecl->bases()) {
5729 if (Base.isVirtual())
5730 continue;
5731 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5732 }
5733
5734 // 3. Direct fields.
5735 for (auto *Field : ClassDecl->fields()) {
5736 if (Field->isUnnamedBitField())
5737 continue;
5738
5739 PopulateKeysForFields(Field, IdealInitKeys);
5740 }
5741
5742 unsigned NumIdealInits = IdealInitKeys.size();
5743 unsigned IdealIndex = 0;
5744
5745 // Track initializers that are in an incorrect order for either a warning or
5746 // note if multiple ones occur.
5747 SmallVector<unsigned> WarnIndexes;
5748 // Correlates the index of an initializer in the init-list to the index of
5749 // the field/base in the class.
5750 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5751
5752 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5753 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5754
5755 // Scan forward to try to find this initializer in the idealized
5756 // initializers list.
5757 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5758 if (InitKey == IdealInitKeys[IdealIndex])
5759 break;
5760
5761 // If we didn't find this initializer, it must be because we
5762 // scanned past it on a previous iteration. That can only
5763 // happen if we're out of order; emit a warning.
5764 if (IdealIndex == NumIdealInits && InitIndex) {
5765 WarnIndexes.push_back(InitIndex);
5766
5767 // Move back to the initializer's location in the ideal list.
5768 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5769 if (InitKey == IdealInitKeys[IdealIndex])
5770 break;
5771
5772 assert(IdealIndex < NumIdealInits &&
5773 "initializer not found in initializer list");
5774 }
5775 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5776 }
5777
5778 if (WarnIndexes.empty())
5779 return;
5780
5781 // Sort based on the ideal order, first in the pair.
5782 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5783
5784 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5785 // emit the diagnostic before we can try adding notes.
5786 {
5788 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5789 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5790 : diag::warn_some_initializers_out_of_order);
5791
5792 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5793 if (CorrelatedInitOrder[I].second == I)
5794 continue;
5795 // Ideally we would be using InsertFromRange here, but clang doesn't
5796 // appear to handle InsertFromRange correctly when the source range is
5797 // modified by another fix-it.
5799 Inits[I]->getSourceRange(),
5802 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5803 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5804 }
5805
5806 // If there is only 1 item out of order, the warning expects the name and
5807 // type of each being added to it.
5808 if (WarnIndexes.size() == 1) {
5809 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5810 Inits[WarnIndexes.front()]);
5811 return;
5812 }
5813 }
5814 // More than 1 item to warn, create notes letting the user know which ones
5815 // are bad.
5816 for (unsigned WarnIndex : WarnIndexes) {
5817 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5818 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5819 diag::note_initializer_out_of_order);
5820 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5821 D << PrevInit->getSourceRange();
5822 }
5823}
5824
5825namespace {
5826bool CheckRedundantInit(Sema &S,
5827 CXXCtorInitializer *Init,
5828 CXXCtorInitializer *&PrevInit) {
5829 if (!PrevInit) {
5830 PrevInit = Init;
5831 return false;
5832 }
5833
5834 if (FieldDecl *Field = Init->getAnyMember())
5835 S.Diag(Init->getSourceLocation(),
5836 diag::err_multiple_mem_initialization)
5837 << Field->getDeclName()
5838 << Init->getSourceRange();
5839 else {
5840 const Type *BaseClass = Init->getBaseClass();
5841 assert(BaseClass && "neither field nor base");
5842 S.Diag(Init->getSourceLocation(),
5843 diag::err_multiple_base_initialization)
5844 << QualType(BaseClass, 0)
5845 << Init->getSourceRange();
5846 }
5847 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5848 << 0 << PrevInit->getSourceRange();
5849
5850 return true;
5851}
5852
5853typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5854typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5855
5856bool CheckRedundantUnionInit(Sema &S,
5857 CXXCtorInitializer *Init,
5858 RedundantUnionMap &Unions) {
5859 FieldDecl *Field = Init->getAnyMember();
5860 RecordDecl *Parent = Field->getParent();
5861 NamedDecl *Child = Field;
5862
5863 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5864 if (Parent->isUnion()) {
5865 UnionEntry &En = Unions[Parent];
5866 if (En.first && En.first != Child) {
5867 S.Diag(Init->getSourceLocation(),
5868 diag::err_multiple_mem_union_initialization)
5869 << Field->getDeclName()
5870 << Init->getSourceRange();
5871 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5872 << 0 << En.second->getSourceRange();
5873 return true;
5874 }
5875 if (!En.first) {
5876 En.first = Child;
5877 En.second = Init;
5878 }
5879 if (!Parent->isAnonymousStructOrUnion())
5880 return false;
5881 }
5882
5883 Child = Parent;
5884 Parent = cast<RecordDecl>(Parent->getDeclContext());
5885 }
5886
5887 return false;
5888}
5889} // namespace
5890
5891void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5892 SourceLocation ColonLoc,
5894 bool AnyErrors) {
5895 if (!ConstructorDecl)
5896 return;
5897
5898 AdjustDeclIfTemplate(ConstructorDecl);
5899
5901 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5902
5903 if (!Constructor) {
5904 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5905 return;
5906 }
5907
5908 // Mapping for the duplicate initializers check.
5909 // For member initializers, this is keyed with a FieldDecl*.
5910 // For base initializers, this is keyed with a Type*.
5911 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5912
5913 // Mapping for the inconsistent anonymous-union initializers check.
5914 RedundantUnionMap MemberUnions;
5915
5916 bool HadError = false;
5917 for (unsigned i = 0; i < MemInits.size(); i++) {
5918 CXXCtorInitializer *Init = MemInits[i];
5919
5920 // Set the source order index.
5921 Init->setSourceOrder(i);
5922
5923 if (Init->isAnyMemberInitializer()) {
5924 const void *Key = GetKeyForMember(Context, Init);
5925 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5926 CheckRedundantUnionInit(*this, Init, MemberUnions))
5927 HadError = true;
5928 } else if (Init->isBaseInitializer()) {
5929 const void *Key = GetKeyForMember(Context, Init);
5930 if (CheckRedundantInit(*this, Init, Members[Key]))
5931 HadError = true;
5932 } else {
5933 assert(Init->isDelegatingInitializer());
5934 // This must be the only initializer
5935 if (MemInits.size() != 1) {
5936 Diag(Init->getSourceLocation(),
5937 diag::err_delegating_initializer_alone)
5938 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5939 // We will treat this as being the only initializer.
5940 }
5942 // Return immediately as the initializer is set.
5943 return;
5944 }
5945 }
5946
5947 if (HadError)
5948 return;
5949
5951
5952 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5953
5954 DiagnoseUninitializedFields(*this, Constructor);
5955}
5956
5958 CXXRecordDecl *ClassDecl) {
5959 // Ignore dependent contexts. Also ignore unions, since their members never
5960 // have destructors implicitly called.
5961 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5962 return;
5963
5964 // FIXME: all the access-control diagnostics are positioned on the
5965 // field/base declaration. That's probably good; that said, the
5966 // user might reasonably want to know why the destructor is being
5967 // emitted, and we currently don't say.
5968
5969 // Non-static data members.
5970 for (auto *Field : ClassDecl->fields()) {
5971 MarkFieldDestructorReferenced(*this, Location, Field);
5972 }
5973
5974 MarkBaseDestructorsReferenced(*this, Location, ClassDecl);
5975}
5976
5978 SourceLocation Location, CXXRecordDecl *ClassDecl,
5979 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5980 // Virtual bases.
5981 for (const auto &VBase : ClassDecl->vbases()) {
5982 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5983 if (!BaseClassDecl)
5984 continue;
5985
5986 // Ignore already visited direct virtual bases.
5987 if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))
5988 continue;
5989
5990 auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);
5991 if (!Dtor)
5992 continue;
5993
5994 CanQualType CT = Context.getCanonicalTagType(ClassDecl);
5995 if (CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
5996 PDiag(diag::err_access_dtor_vbase)
5997 << CT << VBase.getType(),
5998 CT) == AR_accessible) {
6000 CT, VBase.getType(), diag::err_access_dtor_vbase, 0,
6001 ClassDecl->getLocation(), SourceRange(), DeclarationName(), nullptr);
6002 }
6003
6004 MarkFunctionReferenced(Location, Dtor);
6005 DiagnoseUseOfDecl(Dtor, Location);
6006 }
6007}
6008
6010 if (!CDtorDecl)
6011 return;
6012
6014 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
6015 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6016 !ClassDecl || ClassDecl->isInvalidDecl()) {
6017 return;
6018 }
6019 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6020 DiagnoseUninitializedFields(*this, Constructor);
6021 }
6022}
6023
6025 if (!getLangOpts().CPlusPlus)
6026 return false;
6027
6028 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6029 if (!RD)
6030 return false;
6031
6032 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6033 // class template specialization here, but doing so breaks a lot of code.
6034
6035 // We can't answer whether something is abstract until it has a
6036 // definition. If it's currently being defined, we'll walk back
6037 // over all the declarations when we have a full definition.
6038 const CXXRecordDecl *Def = RD->getDefinition();
6039 if (!Def || Def->isBeingDefined())
6040 return false;
6041
6042 return RD->isAbstract();
6043}
6044
6046 TypeDiagnoser &Diagnoser) {
6047 if (!isAbstractType(Loc, T))
6048 return false;
6049
6050 T = Context.getBaseElementType(T);
6051 Diagnoser.diagnose(*this, Loc, T);
6052 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6053 return true;
6054}
6055
6057 // Check if we've already emitted the list of pure virtual functions
6058 // for this class.
6060 return;
6061
6062 // If the diagnostic is suppressed, don't emit the notes. We're only
6063 // going to emit them once, so try to attach them to a diagnostic we're
6064 // actually going to show.
6065 if (Diags.isLastDiagnosticIgnored())
6066 return;
6067
6068 CXXFinalOverriderMap FinalOverriders;
6069 RD->getFinalOverriders(FinalOverriders);
6070
6071 // Keep a set of seen pure methods so we won't diagnose the same method
6072 // more than once.
6074
6075 for (const auto &M : FinalOverriders) {
6076 for (const auto &SO : M.second) {
6077 // C++ [class.abstract]p4:
6078 // A class is abstract if it contains or inherits at least one
6079 // pure virtual function for which the final overrider is pure
6080 // virtual.
6081
6082 if (SO.second.size() != 1)
6083 continue;
6084 const CXXMethodDecl *Method = SO.second.front().Method;
6085
6086 if (!Method->isPureVirtual())
6087 continue;
6088
6089 if (!SeenPureMethods.insert(Method).second)
6090 continue;
6091
6092 Diag(Method->getLocation(), diag::note_pure_virtual_function)
6093 << Method->getDeclName() << RD->getDeclName();
6094 }
6095 }
6096
6099 PureVirtualClassDiagSet->insert(RD);
6100}
6101
6102namespace {
6103struct AbstractUsageInfo {
6104 Sema &S;
6106 CanQualType AbstractType;
6107 bool Invalid;
6108
6109 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6110 : S(S), Record(Record),
6111 AbstractType(S.Context.getCanonicalTagType(Record)), Invalid(false) {}
6112
6113 void DiagnoseAbstractType() {
6114 if (Invalid) return;
6116 Invalid = true;
6117 }
6118
6119 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6120};
6121
6122struct CheckAbstractUsage {
6123 AbstractUsageInfo &Info;
6124 const NamedDecl *Ctx;
6125
6126 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6127 : Info(Info), Ctx(Ctx) {}
6128
6129 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6130 switch (TL.getTypeLocClass()) {
6131#define ABSTRACT_TYPELOC(CLASS, PARENT)
6132#define TYPELOC(CLASS, PARENT) \
6133 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6134#include "clang/AST/TypeLocNodes.def"
6135 }
6136 }
6137
6138 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6140 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6141 if (!TL.getParam(I))
6142 continue;
6143
6144 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6145 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6146 }
6147 }
6148
6149 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6151 }
6152
6153 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6154 // Visit the type parameters from a permissive context.
6155 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6156 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6158 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6159 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6160 // TODO: other template argument types?
6161 }
6162 }
6163
6164 // Visit pointee types from a permissive context.
6165#define CheckPolymorphic(Type) \
6166 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6167 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6168 }
6174
6175 /// Handle all the types we haven't given a more specific
6176 /// implementation for above.
6177 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6178 // Every other kind of type that we haven't called out already
6179 // that has an inner type is either (1) sugar or (2) contains that
6180 // inner type in some way as a subobject.
6181 if (TypeLoc Next = TL.getNextTypeLoc())
6182 return Visit(Next, Sel);
6183
6184 // If there's no inner type and we're in a permissive context,
6185 // don't diagnose.
6186 if (Sel == Sema::AbstractNone) return;
6187
6188 // Check whether the type matches the abstract type.
6189 QualType T = TL.getType();
6190 if (T->isArrayType()) {
6192 T = Info.S.Context.getBaseElementType(T);
6193 }
6194 CanQualType CT = T->getCanonicalTypeUnqualified();
6195 if (CT != Info.AbstractType) return;
6196
6197 // It matched; do some magic.
6198 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6199 if (Sel == Sema::AbstractArrayType) {
6200 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6201 << T << TL.getSourceRange();
6202 } else {
6203 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6204 << Sel << T << TL.getSourceRange();
6205 }
6206 Info.DiagnoseAbstractType();
6207 }
6208};
6209
6210void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6212 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6213}
6214
6215}
6216
6217/// Check for invalid uses of an abstract type in a function declaration.
6218static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6219 FunctionDecl *FD) {
6220 // Only definitions are required to refer to complete and
6221 // non-abstract types.
6223 return;
6224
6225 // For safety's sake, just ignore it if we don't have type source
6226 // information. This should never happen for non-implicit methods,
6227 // but...
6228 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6229 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6230}
6231
6232/// Check for invalid uses of an abstract type in a variable0 declaration.
6233static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6234 VarDecl *VD) {
6235 // No need to do the check on definitions, which require that
6236 // the type is complete.
6238 return;
6239
6240 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6242}
6243
6244/// Check for invalid uses of an abstract type within a class definition.
6245static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6246 CXXRecordDecl *RD) {
6247 for (auto *D : RD->decls()) {
6248 if (D->isImplicit()) continue;
6249
6250 // Step through friends to the befriended declaration.
6251 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6252 D = FD->getFriendDecl();
6253 if (!D) continue;
6254 }
6255
6256 // Functions and function templates.
6257 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6258 CheckAbstractClassUsage(Info, FD);
6259 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6260 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6261
6262 // Fields and static variables.
6263 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6264 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6265 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6266 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6267 CheckAbstractClassUsage(Info, VD);
6268 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6269 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6270
6271 // Nested classes and class templates.
6272 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6273 CheckAbstractClassUsage(Info, RD);
6274 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6275 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6276 }
6277 }
6278}
6279
6281 Attr *ClassAttr = getDLLAttr(Class);
6282 if (!ClassAttr)
6283 return;
6284
6285 assert(ClassAttr->getKind() == attr::DLLExport);
6286
6287 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6288
6290 // Don't go any further if this is just an explicit instantiation
6291 // declaration.
6292 return;
6293
6294 // Add a context note to explain how we got to any diagnostics produced below.
6295 struct MarkingClassDllexported {
6296 Sema &S;
6297 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6298 SourceLocation AttrLoc)
6299 : S(S) {
6302 Ctx.PointOfInstantiation = AttrLoc;
6303 Ctx.Entity = Class;
6305 }
6306 ~MarkingClassDllexported() {
6308 }
6309 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6310
6311 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6312 S.MarkVTableUsed(Class->getLocation(), Class, true);
6313
6314 for (Decl *Member : Class->decls()) {
6315 // Skip members that were not marked exported.
6316 if (!Member->hasAttr<DLLExportAttr>())
6317 continue;
6318
6319 // Defined static variables that are members of an exported base
6320 // class must be marked export too.
6321 auto *VD = dyn_cast<VarDecl>(Member);
6322 if (VD && VD->getStorageClass() == SC_Static &&
6324 S.MarkVariableReferenced(VD->getLocation(), VD);
6325
6326 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6327 if (!MD)
6328 continue;
6329
6330 if (MD->isUserProvided()) {
6331 // Instantiate non-default class member functions ...
6332
6333 // .. except for certain kinds of template specializations.
6334 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6335 continue;
6336
6337 // If this is an MS ABI dllexport default constructor, instantiate any
6338 // default arguments.
6340 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6341 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6343 }
6344 }
6345
6346 S.MarkFunctionReferenced(Class->getLocation(), MD);
6347
6348 // The function will be passed to the consumer when its definition is
6349 // encountered.
6350 } else if (MD->isExplicitlyDefaulted()) {
6351 // Synthesize and instantiate explicitly defaulted methods.
6352 S.MarkFunctionReferenced(Class->getLocation(), MD);
6353
6355 // Except for explicit instantiation defs, we will not see the
6356 // definition again later, so pass it to the consumer now.
6358 }
6359 } else if (!MD->isTrivial() ||
6360 MD->isCopyAssignmentOperator() ||
6361 MD->isMoveAssignmentOperator()) {
6362 // Synthesize and instantiate non-trivial implicit methods, and the copy
6363 // and move assignment operators. The latter are exported even if they
6364 // are trivial, because the address of an operator can be taken and
6365 // should compare equal across libraries.
6366 S.MarkFunctionReferenced(Class->getLocation(), MD);
6367
6368 // There is no later point when we will see the definition of this
6369 // function, so pass it to the consumer now.
6371 }
6372 }
6373}
6374
6376 CXXRecordDecl *Class) {
6377 // Only the MS ABI has default constructor closures, so we don't need to do
6378 // this semantic checking anywhere else.
6380 return;
6381
6382 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6383 for (Decl *Member : Class->decls()) {
6384 // Look for exported default constructors.
6385 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6386 if (!CD || !CD->isDefaultConstructor())
6387 continue;
6388 auto *Attr = CD->getAttr<DLLExportAttr>();
6389 if (!Attr)
6390 continue;
6391
6392 // If the class is non-dependent, mark the default arguments as ODR-used so
6393 // that we can properly codegen the constructor closure.
6394 if (!Class->isDependentContext()) {
6395 for (ParmVarDecl *PD : CD->parameters()) {
6396 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6398 }
6399 }
6400
6401 if (LastExportedDefaultCtor) {
6402 S.Diag(LastExportedDefaultCtor->getLocation(),
6403 diag::err_attribute_dll_ambiguous_default_ctor)
6404 << Class;
6405 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6406 << CD->getDeclName();
6407 return;
6408 }
6409 LastExportedDefaultCtor = CD;
6410 }
6411}
6412
6414 CXXRecordDecl *Class) {
6415 bool ErrorReported = false;
6416 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6417 ClassTemplateDecl *TD) {
6418 if (ErrorReported)
6419 return;
6420 S.Diag(TD->getLocation(),
6421 diag::err_cuda_device_builtin_surftex_cls_template)
6422 << /*surface*/ 0 << TD;
6423 ErrorReported = true;
6424 };
6425
6426 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6427 if (!TD) {
6428 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6429 if (!SD) {
6430 S.Diag(Class->getLocation(),
6431 diag::err_cuda_device_builtin_surftex_ref_decl)
6432 << /*surface*/ 0 << Class;
6433 S.Diag(Class->getLocation(),
6434 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6435 << Class;
6436 return;
6437 }
6438 TD = SD->getSpecializedTemplate();
6439 }
6440
6442 unsigned N = Params->size();
6443
6444 if (N != 2) {
6445 reportIllegalClassTemplate(S, TD);
6446 S.Diag(TD->getLocation(),
6447 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6448 << TD << 2;
6449 }
6450 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6451 reportIllegalClassTemplate(S, TD);
6452 S.Diag(TD->getLocation(),
6453 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6454 << TD << /*1st*/ 0 << /*type*/ 0;
6455 }
6456 if (N > 1) {
6457 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6458 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6459 reportIllegalClassTemplate(S, TD);
6460 S.Diag(TD->getLocation(),
6461 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6462 << TD << /*2nd*/ 1 << /*integer*/ 1;
6463 }
6464 }
6465}
6466
6468 CXXRecordDecl *Class) {
6469 bool ErrorReported = false;
6470 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6471 ClassTemplateDecl *TD) {
6472 if (ErrorReported)
6473 return;
6474 S.Diag(TD->getLocation(),
6475 diag::err_cuda_device_builtin_surftex_cls_template)
6476 << /*texture*/ 1 << TD;
6477 ErrorReported = true;
6478 };
6479
6480 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6481 if (!TD) {
6482 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6483 if (!SD) {
6484 S.Diag(Class->getLocation(),
6485 diag::err_cuda_device_builtin_surftex_ref_decl)
6486 << /*texture*/ 1 << Class;
6487 S.Diag(Class->getLocation(),
6488 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6489 << Class;
6490 return;
6491 }
6492 TD = SD->getSpecializedTemplate();
6493 }
6494
6496 unsigned N = Params->size();
6497
6498 if (N != 3) {
6499 reportIllegalClassTemplate(S, TD);
6500 S.Diag(TD->getLocation(),
6501 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6502 << TD << 3;
6503 }
6504 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6505 reportIllegalClassTemplate(S, TD);
6506 S.Diag(TD->getLocation(),
6507 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6508 << TD << /*1st*/ 0 << /*type*/ 0;
6509 }
6510 if (N > 1) {
6511 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6512 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6513 reportIllegalClassTemplate(S, TD);
6514 S.Diag(TD->getLocation(),
6515 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6516 << TD << /*2nd*/ 1 << /*integer*/ 1;
6517 }
6518 }
6519 if (N > 2) {
6520 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6521 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6522 reportIllegalClassTemplate(S, TD);
6523 S.Diag(TD->getLocation(),
6524 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6525 << TD << /*3rd*/ 2 << /*integer*/ 1;
6526 }
6527 }
6528}
6529
6531 // Mark any compiler-generated routines with the implicit code_seg attribute.
6532 for (auto *Method : Class->methods()) {
6533 if (Method->isUserProvided())
6534 continue;
6535 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6536 Method->addAttr(A);
6537 }
6538}
6539
6541 Attr *ClassAttr = getDLLAttr(Class);
6542
6543 // MSVC inherits DLL attributes to partial class template specializations.
6544 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6545 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6546 if (Attr *TemplateAttr =
6547 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6548 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6549 A->setInherited(true);
6550 ClassAttr = A;
6551 }
6552 }
6553 }
6554
6555 if (!ClassAttr)
6556 return;
6557
6558 // MSVC allows imported or exported template classes that have UniqueExternal
6559 // linkage. This occurs when the template class has been instantiated with
6560 // a template parameter which itself has internal linkage.
6561 // We drop the attribute to avoid exporting or importing any members.
6562 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6563 Context.getTargetInfo().getTriple().isPS()) &&
6564 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6565 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6566 return;
6567 }
6568
6569 if (!Class->isExternallyVisible()) {
6570 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6571 << Class << ClassAttr;
6572 return;
6573 }
6574
6575 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6576 !ClassAttr->isInherited()) {
6577 // Diagnose dll attributes on members of class with dll attribute.
6578 for (Decl *Member : Class->decls()) {
6580 continue;
6581 InheritableAttr *MemberAttr = getDLLAttr(Member);
6582 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6583 continue;
6584
6585 Diag(MemberAttr->getLocation(),
6586 diag::err_attribute_dll_member_of_dll_class)
6587 << MemberAttr << ClassAttr;
6588 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6589 Member->setInvalidDecl();
6590 }
6591 }
6592
6593 if (Class->getDescribedClassTemplate())
6594 // Don't inherit dll attribute until the template is instantiated.
6595 return;
6596
6597 // The class is either imported or exported.
6598 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6599
6600 // Check if this was a dllimport attribute propagated from a derived class to
6601 // a base class template specialization. We don't apply these attributes to
6602 // static data members.
6603 const bool PropagatedImport =
6604 !ClassExported &&
6605 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6606
6607 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6608
6609 // Ignore explicit dllexport on explicit class template instantiation
6610 // declarations, except in MinGW mode.
6611 if (ClassExported && !ClassAttr->isInherited() &&
6613 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6614 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6615 Class->addAttr(DLLExportOnDeclAttr::Create(Context, DEA->getLoc()));
6616 Class->dropAttr<DLLExportAttr>();
6617 }
6618 return;
6619 }
6620
6621 // Force declaration of implicit members so they can inherit the attribute.
6623
6624 // Inherited constructors are created lazily; force their creation now so the
6625 // loop below can propagate the DLL attribute to them.
6626 if (ClassExported && getLangOpts().DllExportInlines) {
6628 for (Decl *D : Class->decls())
6629 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(D))
6630 Shadows.push_back(S);
6631 for (ConstructorUsingShadowDecl *S : Shadows) {
6632 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(S->getTargetDecl());
6633 if (!BC || BC->isDeleted())
6634 continue;
6635 // Skip constructors whose requires clause is not satisfied.
6636 // Normally overload resolution filters these, but we are bypassing
6637 // it to eagerly create inherited constructors for dllexport.
6638 if (BC->getTrailingRequiresClause()) {
6639 ConstraintSatisfaction Satisfaction;
6640 if (CheckFunctionConstraints(BC, Satisfaction) ||
6641 !Satisfaction.IsSatisfied)
6642 continue;
6643 }
6644 findInheritingConstructor(Class->getLocation(), BC, S);
6645 }
6646 }
6647
6648 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6649 // seem to be true in practice?
6650
6651 for (Decl *Member : Class->decls()) {
6652 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6653 continue;
6654
6655 VarDecl *VD = dyn_cast<VarDecl>(Member);
6656 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6657
6658 // Only methods and static fields inherit the attributes.
6659 if (!VD && !MD)
6660 continue;
6661
6662 if (MD) {
6663 // Don't process deleted methods.
6664 if (MD->isDeleted())
6665 continue;
6666
6667 if (ClassExported && getLangOpts().DllExportInlines) {
6668 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD);
6669 if (CD && CD->getInheritedConstructor()) {
6670 // Inherited constructors already had their base constructor's
6671 // constraints checked before creation via
6672 // findInheritingConstructor, so only ABI-compatibility checks
6673 // are needed here.
6674 //
6675 // Don't export inherited constructors whose parameters prevent
6676 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6677 // CodeGen) returns false, Clang inlines the constructor body
6678 // instead of emitting a forwarding thunk, producing code that
6679 // is not ABI-compatible with MSVC. Suppress the export and warn
6680 // so the user gets a linker error rather than a silent runtime
6681 // mismatch.
6682 if (CD->isVariadic()) {
6683 Diag(CD->getLocation(),
6684 diag::warn_dllexport_inherited_ctor_unsupported)
6685 << /*variadic=*/0;
6686 continue;
6687 }
6688 if (Context.getTargetInfo()
6689 .getCXXABI()
6690 .areArgsDestroyedLeftToRightInCallee()) {
6691 bool HasCalleeCleanupParam = false;
6692 for (const ParmVarDecl *P : CD->parameters())
6693 if (P->needsDestruction(Context)) {
6694 HasCalleeCleanupParam = true;
6695 break;
6696 }
6697 if (HasCalleeCleanupParam) {
6698 Diag(CD->getLocation(),
6699 diag::warn_dllexport_inherited_ctor_unsupported)
6700 << /*callee-cleanup=*/1;
6701 continue;
6702 }
6703 }
6704 } else if (MD->getTrailingRequiresClause()) {
6705 // Don't export methods whose requires clause is not satisfied.
6706 // For class template specializations, member constraints may
6707 // depend on template arguments and an unsatisfied constraint
6708 // means the member should not be available in this
6709 // specialization.
6710 ConstraintSatisfaction Satisfaction;
6711 if (CheckFunctionConstraints(MD, Satisfaction) ||
6712 !Satisfaction.IsSatisfied)
6713 continue;
6714 }
6715 }
6716
6717 if (MD->isInlined()) {
6718 // MinGW does not import or export inline methods. But do it for
6719 // template instantiations and inherited constructors (which are
6720 // marked inline but must be exported to match MSVC behavior).
6721 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6724 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6725 !CD || !CD->getInheritedConstructor())
6726 continue;
6727 }
6728
6729 // MSVC versions before 2015 don't export the move assignment operators
6730 // and move constructor, so don't attempt to import/export them if
6731 // we have a definition.
6732 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6733 if ((MD->isMoveAssignmentOperator() ||
6734 (Ctor && Ctor->isMoveConstructor())) &&
6735 getLangOpts().isCompatibleWithMSVC() &&
6736 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6737 continue;
6738
6739 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6740 // operator is exported anyway.
6741 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6742 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6743 continue;
6744 }
6745 }
6746
6747 // Don't apply dllimport attributes to static data members of class template
6748 // instantiations when the attribute is propagated from a derived class.
6749 if (VD && PropagatedImport)
6750 continue;
6751
6753 continue;
6754
6755 if (!getDLLAttr(Member)) {
6756 InheritableAttr *NewAttr = nullptr;
6757
6758 // Do not export/import inline function when -fno-dllexport-inlines is
6759 // passed. But add attribute for later local static var check.
6760 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6763 if (ClassExported) {
6764 NewAttr = ::new (getASTContext())
6765 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6766 } else {
6767 NewAttr = ::new (getASTContext())
6768 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6769 }
6770 } else {
6771 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6772 }
6773
6774 NewAttr->setInherited(true);
6775 Member->addAttr(NewAttr);
6776
6777 if (MD) {
6778 // Propagate DLLAttr to friend re-declarations of MD that have already
6779 // been constructed.
6780 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6781 FD = FD->getPreviousDecl()) {
6783 continue;
6784 assert(!getDLLAttr(FD) &&
6785 "friend re-decl should not already have a DLLAttr");
6786 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6787 NewAttr->setInherited(true);
6788 FD->addAttr(NewAttr);
6789 }
6790 }
6791 }
6792 }
6793
6794 if (ClassExported)
6795 DelayedDllExportClasses.push_back(Class);
6796}
6797
6799 CXXRecordDecl *Class, Attr *ClassAttr,
6800 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6801 if (getDLLAttr(
6802 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6803 // If the base class template has a DLL attribute, don't try to change it.
6804 return;
6805 }
6806
6807 auto TSK = BaseTemplateSpec->getSpecializationKind();
6808 if (!getDLLAttr(BaseTemplateSpec) &&
6810 TSK == TSK_ImplicitInstantiation)) {
6811 // The template hasn't been instantiated yet (or it has, but only as an
6812 // explicit instantiation declaration or implicit instantiation, which means
6813 // we haven't codegenned any members yet), so propagate the attribute.
6814 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6815 NewAttr->setInherited(true);
6816 BaseTemplateSpec->addAttr(NewAttr);
6817
6818 // If this was an import, mark that we propagated it from a derived class to
6819 // a base class template specialization.
6820 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6821 ImportAttr->setPropagatedToBaseTemplate();
6822
6823 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6824 // needs to be run again to work see the new attribute. Otherwise this will
6825 // get run whenever the template is instantiated.
6826 if (TSK != TSK_Undeclared)
6827 checkClassLevelDLLAttribute(BaseTemplateSpec);
6828
6829 return;
6830 }
6831
6832 if (getDLLAttr(BaseTemplateSpec)) {
6833 // The template has already been specialized or instantiated with an
6834 // attribute, explicitly or through propagation. We should not try to change
6835 // it.
6836 return;
6837 }
6838
6839 // The template was previously instantiated or explicitly specialized without
6840 // a dll attribute, It's too late for us to add an attribute, so warn that
6841 // this is unsupported.
6842 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6843 << BaseTemplateSpec->isExplicitSpecialization();
6844 Diag(ClassAttr->getLocation(), diag::note_attribute);
6845 if (BaseTemplateSpec->isExplicitSpecialization()) {
6846 Diag(BaseTemplateSpec->getLocation(),
6847 diag::note_template_class_explicit_specialization_was_here)
6848 << BaseTemplateSpec;
6849 } else {
6850 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6851 diag::note_template_class_instantiation_was_here)
6852 << BaseTemplateSpec;
6853 }
6854}
6855
6858 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6859 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6860 if (Ctor->isDefaultConstructor())
6862
6863 if (Ctor->isCopyConstructor())
6865
6866 if (Ctor->isMoveConstructor())
6868 }
6869
6870 if (MD->isCopyAssignmentOperator())
6872
6873 if (MD->isMoveAssignmentOperator())
6875
6876 if (isa<CXXDestructorDecl>(FD))
6878 }
6879
6880 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6881 case OO_EqualEqual:
6883
6884 case OO_ExclaimEqual:
6886
6887 case OO_Spaceship:
6888 // No point allowing this if <=> doesn't exist in the current language mode.
6889 if (!getLangOpts().CPlusPlus20)
6890 break;
6892
6893 case OO_Less:
6894 case OO_LessEqual:
6895 case OO_Greater:
6896 case OO_GreaterEqual:
6897 // No point allowing this if <=> doesn't exist in the current language mode.
6898 if (!getLangOpts().CPlusPlus20)
6899 break;
6901
6902 default:
6903 break;
6904 }
6905
6906 // Not defaultable.
6907 return DefaultedFunctionKind();
6908}
6909
6911 SourceLocation DefaultLoc) {
6913 if (DFK.isComparison())
6914 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6915
6916 switch (DFK.asSpecialMember()) {
6920 break;
6923 break;
6926 break;
6929 break;
6932 break;
6935 break;
6937 llvm_unreachable("Invalid special member.");
6938 }
6939}
6940
6941/// Determine whether a type is permitted to be passed or returned in
6942/// registers, per C++ [class.temporary]p3.
6945 if (D->isDependentType() || D->isInvalidDecl())
6946 return false;
6947
6948 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6949 // The PS4 platform ABI follows the behavior of Clang 3.2.
6951 return !D->hasNonTrivialDestructorForCall() &&
6953
6954 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6955 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6956 bool DtorIsTrivialForCall = false;
6957
6958 // If a class has at least one eligible, trivial copy constructor, it
6959 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6960 //
6961 // Note: This permits classes with non-trivial copy or move ctors to be
6962 // passed in registers, so long as they *also* have a trivial copy ctor,
6963 // which is non-conforming.
6967 CopyCtorIsTrivial = true;
6969 CopyCtorIsTrivialForCall = true;
6970 }
6971 } else {
6972 for (const CXXConstructorDecl *CD : D->ctors()) {
6973 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6974 !CD->isIneligibleOrNotSelected()) {
6975 if (CD->isTrivial())
6976 CopyCtorIsTrivial = true;
6977 if (CD->isTrivialForCall())
6978 CopyCtorIsTrivialForCall = true;
6979 }
6980 }
6981 }
6982
6983 if (D->needsImplicitDestructor()) {
6984 if (!D->defaultedDestructorIsDeleted() &&
6986 DtorIsTrivialForCall = true;
6987 } else if (const auto *DD = D->getDestructor()) {
6988 if (!DD->isDeleted() && DD->isTrivialForCall())
6989 DtorIsTrivialForCall = true;
6990 }
6991
6992 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6993 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6994 return true;
6995
6996 // If a class has a destructor, we'd really like to pass it indirectly
6997 // because it allows us to elide copies. Unfortunately, MSVC makes that
6998 // impossible for small types, which it will pass in a single register or
6999 // stack slot. Most objects with dtors are large-ish, so handle that early.
7000 // We can't call out all large objects as being indirect because there are
7001 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7002 // how we pass large POD types.
7003
7004 // Note: This permits small classes with nontrivial destructors to be
7005 // passed in registers, which is non-conforming.
7006 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7007 uint64_t TypeSize = isAArch64 ? 128 : 64;
7008
7009 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7010 S.Context.getCanonicalTagType(D)) <= TypeSize)
7011 return true;
7012 return false;
7013 }
7014
7015 // Per C++ [class.temporary]p3, the relevant condition is:
7016 // each copy constructor, move constructor, and destructor of X is
7017 // either trivial or deleted, and X has at least one non-deleted copy
7018 // or move constructor
7019 bool HasNonDeletedCopyOrMove = false;
7020
7024 return false;
7025 HasNonDeletedCopyOrMove = true;
7026 }
7027
7028 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7031 return false;
7032 HasNonDeletedCopyOrMove = true;
7033 }
7034
7037 return false;
7038
7039 for (const CXXMethodDecl *MD : D->methods()) {
7040 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7041 continue;
7042
7043 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
7044 if (CD && CD->isCopyOrMoveConstructor())
7045 HasNonDeletedCopyOrMove = true;
7046 else if (!isa<CXXDestructorDecl>(MD))
7047 continue;
7048
7049 if (!MD->isTrivialForCall())
7050 return false;
7051 }
7052
7053 return HasNonDeletedCopyOrMove;
7054}
7055
7056/// Report an error regarding overriding, along with any relevant
7057/// overridden methods.
7058///
7059/// \param DiagID the primary error to report.
7060/// \param MD the overriding method.
7061static bool
7062ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7063 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7064 bool IssuedDiagnostic = false;
7065 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7066 if (Report(O)) {
7067 if (!IssuedDiagnostic) {
7068 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7069 IssuedDiagnostic = true;
7070 }
7071 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7072 }
7073 }
7074 return IssuedDiagnostic;
7075}
7076
7078 if (!Record)
7079 return;
7080
7081 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7082 AbstractUsageInfo Info(*this, Record);
7084 }
7085
7086 // If this is not an aggregate type and has no user-declared constructor,
7087 // complain about any non-static data members of reference or const scalar
7088 // type, since they will never get initializers.
7089 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7090 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7091 !Record->isLambda()) {
7092 bool Complained = false;
7093 for (const auto *F : Record->fields()) {
7094 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7095 continue;
7096
7097 if (F->getType()->isReferenceType() ||
7098 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7099 if (!Complained) {
7100 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7101 << Record->getTagKind() << Record;
7102 Complained = true;
7103 }
7104
7105 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7106 << F->getType()->isReferenceType()
7107 << F->getDeclName();
7108 }
7109 }
7110 }
7111
7112 if (Record->getIdentifier()) {
7113 // C++ [class.mem]p13:
7114 // If T is the name of a class, then each of the following shall have a
7115 // name different from T:
7116 // - every member of every anonymous union that is a member of class T.
7117 //
7118 // C++ [class.mem]p14:
7119 // In addition, if class T has a user-declared constructor (12.1), every
7120 // non-static data member of class T shall have a name different from T.
7121 for (const NamedDecl *Element : Record->lookup(Record->getDeclName())) {
7122 const NamedDecl *D = Element->getUnderlyingDecl();
7123 // Invalid IndirectFieldDecls have already been diagnosed with
7124 // err_anonymous_record_member_redecl in
7125 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7127 Record->hasUserDeclaredConstructor()) ||
7128 (isa<IndirectFieldDecl>(D) && !D->isInvalidDecl())) {
7129 Diag(Element->getLocation(), diag::err_member_name_of_class)
7130 << D->getDeclName();
7131 break;
7132 }
7133 }
7134 }
7135
7136 // Warn if the class has virtual methods but non-virtual public destructor.
7137 if (Record->isPolymorphic() && !Record->isDependentType()) {
7138 CXXDestructorDecl *dtor = Record->getDestructor();
7139 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7140 !Record->hasAttr<FinalAttr>())
7141 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7142 diag::warn_non_virtual_dtor)
7143 << Context.getCanonicalTagType(Record);
7144 }
7145
7146 if (Record->isAbstract()) {
7147 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7148 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7149 << FA->isSpelledAsSealed();
7151 }
7152 }
7153
7154 // Warn if the class has a final destructor but is not itself marked final.
7155 if (!Record->hasAttr<FinalAttr>()) {
7156 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7157 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7158 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7159 << FA->isSpelledAsSealed()
7161 getLocForEndOfToken(Record->getLocation()),
7162 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7163 Diag(Record->getLocation(),
7164 diag::note_final_dtor_non_final_class_silence)
7165 << Context.getCanonicalTagType(Record) << FA->isSpelledAsSealed();
7166 }
7167 }
7168 }
7169
7170 // See if trivial_abi has to be dropped.
7171 if (Record->hasAttr<TrivialABIAttr>())
7173
7174 // Set HasTrivialSpecialMemberForCall if the record has attribute
7175 // "trivial_abi".
7176 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7177
7178 if (HasTrivialABI)
7179 Record->setHasTrivialSpecialMemberForCall();
7180
7181 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7182 // We check these last because they can depend on the properties of the
7183 // primary comparison functions (==, <=>).
7184 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7185
7186 // Perform checks that can't be done until we know all the properties of a
7187 // member function (whether it's defaulted, deleted, virtual, overriding,
7188 // ...).
7189 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7190 // A static function cannot override anything.
7191 if (MD->getStorageClass() == SC_Static) {
7192 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7193 [](const CXXMethodDecl *) { return true; }))
7194 return;
7195 }
7196
7197 // A deleted function cannot override a non-deleted function and vice
7198 // versa.
7199 if (ReportOverrides(*this,
7200 MD->isDeleted() ? diag::err_deleted_override
7201 : diag::err_non_deleted_override,
7202 MD, [&](const CXXMethodDecl *V) {
7203 return MD->isDeleted() != V->isDeleted();
7204 })) {
7205 if (MD->isDefaulted() && MD->isDeleted())
7206 // Explain why this defaulted function was deleted.
7208 return;
7209 }
7210
7211 // A consteval function cannot override a non-consteval function and vice
7212 // versa.
7213 if (ReportOverrides(*this,
7214 MD->isConsteval() ? diag::err_consteval_override
7215 : diag::err_non_consteval_override,
7216 MD, [&](const CXXMethodDecl *V) {
7217 return MD->isConsteval() != V->isConsteval();
7218 })) {
7219 if (MD->isDefaulted() && MD->isDeleted())
7220 // Explain why this defaulted function was deleted.
7222 return;
7223 }
7224 };
7225
7226 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7227 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7228 return false;
7229
7233 DefaultedSecondaryComparisons.push_back(FD);
7234 return true;
7235 }
7236
7238 return false;
7239 };
7240
7241 if (!Record->isInvalidDecl() &&
7242 Record->hasAttr<VTablePointerAuthenticationAttr>())
7244
7245 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7246 // Check whether the explicitly-defaulted members are valid.
7247 bool Incomplete = CheckForDefaultedFunction(M);
7248
7249 // Skip the rest of the checks for a member of a dependent class.
7250 if (Record->isDependentType())
7251 return;
7252
7253 // For an explicitly defaulted or deleted special member, we defer
7254 // determining triviality until the class is complete. That time is now!
7256 if (!M->isImplicit() && !M->isUserProvided()) {
7257 if (CSM != CXXSpecialMemberKind::Invalid) {
7258 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7259 // Inform the class that we've finished declaring this member.
7260 Record->finishedDefaultedOrDeletedMember(M);
7261 M->setTrivialForCall(
7262 HasTrivialABI ||
7265 Record->setTrivialForCallFlags(M);
7266 }
7267 }
7268
7269 // Set triviality for the purpose of calls if this is a user-provided
7270 // copy/move constructor or destructor.
7274 M->isUserProvided()) {
7275 M->setTrivialForCall(HasTrivialABI);
7276 Record->setTrivialForCallFlags(M);
7277 }
7278
7279 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7280 M->hasAttr<DLLExportAttr>()) {
7281 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7282 M->isTrivial() &&
7286 M->dropAttr<DLLExportAttr>();
7287
7288 if (M->hasAttr<DLLExportAttr>()) {
7289 // Define after any fields with in-class initializers have been parsed.
7291 }
7292 }
7293
7294 bool EffectivelyConstexprDestructor = true;
7295 // Avoid triggering vtable instantiation due to a dtor that is not
7296 // "effectively constexpr" for better compatibility.
7297 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7298 if (isa<CXXDestructorDecl>(M)) {
7299 llvm::SmallDenseSet<QualType> Visited;
7300 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7301 if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)
7302 return false;
7303 const CXXRecordDecl *RD =
7304 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7305 if (!RD || !RD->isCompleteDefinition())
7306 return true;
7307
7308 if (!RD->hasConstexprDestructor())
7309 return false;
7310
7311 for (const CXXBaseSpecifier &B : RD->bases())
7312 if (!Check(B.getType(), Check))
7313 return false;
7314 for (const FieldDecl *FD : RD->fields())
7315 if (!Check(FD->getType(), Check))
7316 return false;
7317 return true;
7318 };
7319 EffectivelyConstexprDestructor =
7320 Check(Context.getCanonicalTagType(Record), Check);
7321 }
7322
7323 // Define defaulted constexpr virtual functions that override a base class
7324 // function right away.
7325 // FIXME: We can defer doing this until the vtable is marked as used.
7326 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7327 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7328 EffectivelyConstexprDestructor)
7329 DefineDefaultedFunction(*this, M, M->getLocation());
7330
7331 if (!Incomplete)
7332 CheckCompletedMemberFunction(M);
7333 };
7334
7335 // Check the destructor before any other member function. We need to
7336 // determine whether it's trivial in order to determine whether the claas
7337 // type is a literal type, which is a prerequisite for determining whether
7338 // other special member functions are valid and whether they're implicitly
7339 // 'constexpr'.
7340 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7341 CompleteMemberFunction(Dtor);
7342
7343 bool HasMethodWithOverrideControl = false,
7344 HasOverridingMethodWithoutOverrideControl = false;
7345 for (auto *D : Record->decls()) {
7346 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7347 // FIXME: We could do this check for dependent types with non-dependent
7348 // bases.
7349 if (!Record->isDependentType()) {
7350 // See if a method overloads virtual methods in a base
7351 // class without overriding any.
7352 if (!M->isStatic())
7354
7355 if (M->hasAttr<OverrideAttr>()) {
7356 HasMethodWithOverrideControl = true;
7357 } else if (M->size_overridden_methods() > 0) {
7358 HasOverridingMethodWithoutOverrideControl = true;
7359 } else {
7360 // Warn on newly-declared virtual methods in `final` classes
7361 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7362 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7363 << M;
7364 }
7365 }
7366 }
7367
7368 if (!isa<CXXDestructorDecl>(M))
7369 CompleteMemberFunction(M);
7370 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7371 CheckForDefaultedFunction(
7372 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7373 }
7374 }
7375
7376 if (HasOverridingMethodWithoutOverrideControl) {
7377 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7378 for (auto *M : Record->methods())
7379 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7380 }
7381
7382 // Check the defaulted secondary comparisons after any other member functions.
7383 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7385
7386 // If this is a member function, we deferred checking it until now.
7387 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7388 CheckCompletedMemberFunction(MD);
7389 }
7390
7391 // {ms,gcc}_struct is a request to change ABI rules to either follow
7392 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7393 // present, we do not layout classes following foreign ABI rules, but
7394 // instead enter a special "compatibility mode", which only changes
7395 // alignments of fundamental types and layout of bit fields.
7396 // Check whether this class uses any C++ features that are implemented
7397 // completely differently in the requested ABI, and if so, emit a
7398 // diagnostic. That diagnostic defaults to an error, but we allow
7399 // projects to map it down to a warning (or ignore it). It's a fairly
7400 // common practice among users of the ms_struct pragma to
7401 // mass-annotate headers, sweeping up a bunch of types that the
7402 // project doesn't really rely on MSVC-compatible layout for. We must
7403 // therefore support "ms_struct except for C++ stuff" as a secondary
7404 // ABI.
7405 // Don't emit this diagnostic if the feature was enabled as a
7406 // language option (as opposed to via a pragma or attribute), as
7407 // the option -mms-bitfields otherwise essentially makes it impossible
7408 // to build C++ code, unless this diagnostic is turned off.
7409 if (Context.getLangOpts().getLayoutCompatibility() ==
7411 Record->isMsStruct(Context) != Context.defaultsToMsStruct() &&
7412 (Record->isPolymorphic() || Record->getNumBases())) {
7413 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7414 }
7415
7418
7419 bool ClangABICompat4 =
7420 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver4);
7422 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7423 bool CanPass = canPassInRegisters(*this, Record, CCK);
7424
7425 // Do not change ArgPassingRestrictions if it has already been set to
7426 // RecordArgPassingKind::CanNeverPassInRegs.
7427 if (Record->getArgPassingRestrictions() !=
7429 Record->setArgPassingRestrictions(
7432
7433 // If canPassInRegisters returns true despite the record having a non-trivial
7434 // destructor, the record is destructed in the callee. This happens only when
7435 // the record or one of its subobjects has a field annotated with trivial_abi
7436 // or a field qualified with ObjC __strong/__weak.
7437 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7438 Record->setParamDestroyedInCallee(true);
7439 else if (Record->hasNonTrivialDestructor())
7440 Record->setParamDestroyedInCallee(CanPass);
7441
7442 if (getLangOpts().ForceEmitVTables) {
7443 // If we want to emit all the vtables, we need to mark it as used. This
7444 // is especially required for cases like vtable assumption loads.
7445 MarkVTableUsed(Record->getInnerLocStart(), Record);
7446 }
7447
7448 if (getLangOpts().CUDA) {
7449 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7451 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7453 }
7454
7455 llvm::SmallDenseMap<OverloadedOperatorKind,
7457 TypeAwareDecls{{OO_New, {}},
7458 {OO_Array_New, {}},
7459 {OO_Delete, {}},
7460 {OO_Array_New, {}}};
7461 for (auto *D : Record->decls()) {
7462 const FunctionDecl *FnDecl = D->getAsFunction();
7463 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7464 continue;
7465 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7466 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7467 }
7468 auto CheckMismatchedTypeAwareAllocators =
7469 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7470 OverloadedOperatorKind DeleteKind) {
7471 auto &NewDecls = TypeAwareDecls[NewKind];
7472 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7473 if (NewDecls.empty() == DeleteDecls.empty())
7474 return;
7475 DeclarationName FoundOperator =
7476 Context.DeclarationNames.getCXXOperatorName(
7477 NewDecls.empty() ? DeleteKind : NewKind);
7478 DeclarationName MissingOperator =
7479 Context.DeclarationNames.getCXXOperatorName(
7480 NewDecls.empty() ? NewKind : DeleteKind);
7481 Diag(Record->getLocation(),
7482 diag::err_type_aware_allocator_missing_matching_operator)
7483 << FoundOperator << Context.getCanonicalTagType(Record)
7484 << MissingOperator;
7485 for (auto MD : NewDecls)
7486 Diag(MD->getLocation(),
7487 diag::note_unmatched_type_aware_allocator_declared)
7488 << MD;
7489 for (auto MD : DeleteDecls)
7490 Diag(MD->getLocation(),
7491 diag::note_unmatched_type_aware_allocator_declared)
7492 << MD;
7493 };
7494 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7495 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7496}
7497
7498/// Look up the special member function that would be called by a special
7499/// member function for a subobject of class type.
7500///
7501/// \param Class The class type of the subobject.
7502/// \param CSM The kind of special member function.
7503/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7504/// \param ConstRHS True if this is a copy operation with a const object
7505/// on its RHS, that is, if the argument to the outer special member
7506/// function is 'const' and this is not a field marked 'mutable'.
7509 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7510 bool ConstRHS) {
7511 unsigned LHSQuals = 0;
7514 LHSQuals = FieldQuals;
7515
7516 unsigned RHSQuals = FieldQuals;
7519 RHSQuals = 0;
7520 else if (ConstRHS)
7521 RHSQuals |= Qualifiers::Const;
7522
7523 return S.LookupSpecialMember(Class, CSM,
7524 RHSQuals & Qualifiers::Const,
7525 RHSQuals & Qualifiers::Volatile,
7526 false,
7527 LHSQuals & Qualifiers::Const,
7528 LHSQuals & Qualifiers::Volatile);
7529}
7530
7532 Sema &S;
7533 SourceLocation UseLoc;
7534
7535 /// A mapping from the base classes through which the constructor was
7536 /// inherited to the using shadow declaration in that base class (or a null
7537 /// pointer if the constructor was declared in that base class).
7538 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7539 InheritedFromBases;
7540
7541public:
7544 : S(S), UseLoc(UseLoc) {
7545 bool DiagnosedMultipleConstructedBases = false;
7546 CXXRecordDecl *ConstructedBase = nullptr;
7547 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7548
7549 // Find the set of such base class subobjects and check that there's a
7550 // unique constructed subobject.
7551 for (auto *D : Shadow->redecls()) {
7552 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7553 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7554 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7555
7556 InheritedFromBases.insert(
7557 std::make_pair(DNominatedBase->getCanonicalDecl(),
7558 DShadow->getNominatedBaseClassShadowDecl()));
7559 if (DShadow->constructsVirtualBase())
7560 InheritedFromBases.insert(
7561 std::make_pair(DConstructedBase->getCanonicalDecl(),
7562 DShadow->getConstructedBaseClassShadowDecl()));
7563 else
7564 assert(DNominatedBase == DConstructedBase);
7565
7566 // [class.inhctor.init]p2:
7567 // If the constructor was inherited from multiple base class subobjects
7568 // of type B, the program is ill-formed.
7569 if (!ConstructedBase) {
7570 ConstructedBase = DConstructedBase;
7571 ConstructedBaseIntroducer = D->getIntroducer();
7572 } else if (ConstructedBase != DConstructedBase &&
7573 !Shadow->isInvalidDecl()) {
7574 if (!DiagnosedMultipleConstructedBases) {
7575 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7576 << Shadow->getTargetDecl();
7577 S.Diag(ConstructedBaseIntroducer->getLocation(),
7578 diag::note_ambiguous_inherited_constructor_using)
7579 << ConstructedBase;
7580 DiagnosedMultipleConstructedBases = true;
7581 }
7582 S.Diag(D->getIntroducer()->getLocation(),
7583 diag::note_ambiguous_inherited_constructor_using)
7584 << DConstructedBase;
7585 }
7586 }
7587
7588 if (DiagnosedMultipleConstructedBases)
7589 Shadow->setInvalidDecl();
7590 }
7591
7592 /// Find the constructor to use for inherited construction of a base class,
7593 /// and whether that base class constructor inherits the constructor from a
7594 /// virtual base class (in which case it won't actually invoke it).
7595 std::pair<CXXConstructorDecl *, bool>
7597 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7598 if (It == InheritedFromBases.end())
7599 return std::make_pair(nullptr, false);
7600
7601 // This is an intermediary class.
7602 if (It->second)
7603 return std::make_pair(
7604 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7605 It->second->constructsVirtualBase());
7606
7607 // This is the base class from which the constructor was inherited.
7608 return std::make_pair(Ctor, false);
7609 }
7610};
7611
7612/// Is the special member function which would be selected to perform the
7613/// specified operation on the specified class type a constexpr constructor?
7615 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7616 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7617 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7618 // Suppress duplicate constraint checking here, in case a constraint check
7619 // caused us to decide to do this. Any truely recursive checks will get
7620 // caught during these checks anyway.
7622
7623 // If we're inheriting a constructor, see if we need to call it for this base
7624 // class.
7625 if (InheritedCtor) {
7627 auto BaseCtor =
7628 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7629 if (BaseCtor)
7630 return BaseCtor->isConstexpr();
7631 }
7632
7634 return ClassDecl->hasConstexprDefaultConstructor();
7636 return ClassDecl->hasConstexprDestructor();
7637
7639 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7640 if (!SMOR.getMethod())
7641 // A constructor we wouldn't select can't be "involved in initializing"
7642 // anything.
7643 return true;
7644 return SMOR.getMethod()->isConstexpr();
7645}
7646
7647/// Determine whether the specified special member function would be constexpr
7648/// if it were implicitly defined.
7650 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7651 CXXConstructorDecl *InheritedCtor = nullptr,
7652 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7653 if (!S.getLangOpts().CPlusPlus11)
7654 return false;
7655
7656 // C++11 [dcl.constexpr]p4:
7657 // In the definition of a constexpr constructor [...]
7658 bool Ctor = true;
7659 switch (CSM) {
7661 if (Inherited)
7662 break;
7663 // Since default constructor lookup is essentially trivial (and cannot
7664 // involve, for instance, template instantiation), we compute whether a
7665 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7666 //
7667 // This is important for performance; we need to know whether the default
7668 // constructor is constexpr to determine whether the type is a literal type.
7669 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7670
7673 // For copy or move constructors, we need to perform overload resolution.
7674 break;
7675
7678 if (!S.getLangOpts().CPlusPlus14)
7679 return false;
7680 // In C++1y, we need to perform overload resolution.
7681 Ctor = false;
7682 break;
7683
7685 return ClassDecl->defaultedDestructorIsConstexpr();
7686
7688 return false;
7689 }
7690
7691 // -- if the class is a non-empty union, or for each non-empty anonymous
7692 // union member of a non-union class, exactly one non-static data member
7693 // shall be initialized; [DR1359]
7694 //
7695 // If we squint, this is guaranteed, since exactly one non-static data member
7696 // will be initialized (if the constructor isn't deleted), we just don't know
7697 // which one.
7698 if (Ctor && ClassDecl->isUnion())
7700 ? ClassDecl->hasInClassInitializer() ||
7701 !ClassDecl->hasVariantMembers()
7702 : true;
7703
7704 // -- the class shall not have any virtual base classes;
7705 if (Ctor && ClassDecl->getNumVBases())
7706 return false;
7707
7708 // C++1y [class.copy]p26:
7709 // -- [the class] is a literal type, and
7710 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7711 return false;
7712
7713 // -- every constructor involved in initializing [...] base class
7714 // sub-objects shall be a constexpr constructor;
7715 // -- the assignment operator selected to copy/move each direct base
7716 // class is a constexpr function, and
7717 if (!S.getLangOpts().CPlusPlus23) {
7718 for (const auto &B : ClassDecl->bases()) {
7719 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7720 if (!BaseClassDecl)
7721 continue;
7722 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7723 InheritedCtor, Inherited))
7724 return false;
7725 }
7726 }
7727
7728 // -- every constructor involved in initializing non-static data members
7729 // [...] shall be a constexpr constructor;
7730 // -- every non-static data member and base class sub-object shall be
7731 // initialized
7732 // -- for each non-static data member of X that is of class type (or array
7733 // thereof), the assignment operator selected to copy/move that member is
7734 // a constexpr function
7735 if (!S.getLangOpts().CPlusPlus23) {
7736 for (const auto *F : ClassDecl->fields()) {
7737 if (F->isInvalidDecl())
7738 continue;
7740 F->hasInClassInitializer())
7741 continue;
7742 QualType BaseType = S.Context.getBaseElementType(F->getType());
7743 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7744 auto *FieldRecDecl =
7745 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
7746 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7747 BaseType.getCVRQualifiers(),
7748 ConstArg && !F->isMutable()))
7749 return false;
7750 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7751 return false;
7752 }
7753 }
7754 }
7755
7756 // All OK, it's constexpr!
7757 return true;
7758}
7759
7760namespace {
7761/// RAII object to register a defaulted function as having its exception
7762/// specification computed.
7763struct ComputingExceptionSpec {
7764 Sema &S;
7765
7766 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7767 : S(S) {
7768 Sema::CodeSynthesisContext Ctx;
7770 Ctx.PointOfInstantiation = Loc;
7771 Ctx.Entity = FD;
7773 }
7774 ~ComputingExceptionSpec() {
7776 }
7777};
7778}
7779
7780static Sema::ImplicitExceptionSpecification
7781ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7782 CXXMethodDecl *MD,
7784 Sema::InheritedConstructorInfo *ICI);
7785
7786static Sema::ImplicitExceptionSpecification
7787ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7788 FunctionDecl *FD,
7790
7791static Sema::ImplicitExceptionSpecification
7793 auto DFK = S.getDefaultedFunctionKind(FD);
7794 if (DFK.isSpecialMember())
7796 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7797 if (DFK.isComparison())
7799 DFK.asComparison());
7800
7801 auto *CD = cast<CXXConstructorDecl>(FD);
7802 assert(CD->getInheritedConstructor() &&
7803 "only defaulted functions and inherited constructors have implicit "
7804 "exception specs");
7806 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7809}
7810
7812 CXXMethodDecl *MD) {
7814
7815 // Build an exception specification pointing back at this member.
7817 EPI.ExceptionSpec.SourceDecl = MD;
7818
7819 // Set the calling convention to the default for C++ instance methods.
7821 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7822 /*IsCXXMethod=*/true));
7823 return EPI;
7824}
7825
7827 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7829 return;
7830
7831 // Evaluate the exception specification.
7832 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7833 auto ESI = IES.getExceptionSpec();
7834
7835 // Update the type of the special member to use it.
7836 UpdateExceptionSpec(FD, ESI);
7837}
7838
7840 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7841
7843 if (!DefKind) {
7844 assert(FD->getDeclContext()->isDependentContext());
7845 return;
7846 }
7847
7848 if (DefKind.isComparison()) {
7849 auto PT = FD->getParamDecl(0)->getType();
7850 if (const CXXRecordDecl *RD =
7851 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7852 for (FieldDecl *Field : RD->fields()) {
7853 UnusedPrivateFields.remove(Field);
7854 }
7855 }
7856 }
7857
7858 if (DefKind.isSpecialMember()
7860 DefKind.asSpecialMember(),
7861 FD->getDefaultLoc())
7863 FD->setInvalidDecl();
7864}
7865
7868 SourceLocation DefaultLoc) {
7869 CXXRecordDecl *RD = MD->getParent();
7870
7872 "not an explicitly-defaulted special member");
7873
7874 // Defer all checking for special members of a dependent type.
7875 if (RD->isDependentType())
7876 return false;
7877
7878 // Whether this was the first-declared instance of the constructor.
7879 // This affects whether we implicitly add an exception spec and constexpr.
7880 bool First = MD == MD->getCanonicalDecl();
7881
7882 bool HadError = false;
7883
7884 // C++11 [dcl.fct.def.default]p1:
7885 // A function that is explicitly defaulted shall
7886 // -- be a special member function [...] (checked elsewhere),
7887 // -- have the same type (except for ref-qualifiers, and except that a
7888 // copy operation can take a non-const reference) as an implicit
7889 // declaration, and
7890 // -- not have default arguments.
7891 // C++2a changes the second bullet to instead delete the function if it's
7892 // defaulted on its first declaration, unless it's "an assignment operator,
7893 // and its return type differs or its parameter type is not a reference".
7894 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7895 bool ShouldDeleteForTypeMismatch = false;
7896 unsigned ExpectedParams = 1;
7899 ExpectedParams = 0;
7900 if (MD->getNumExplicitParams() != ExpectedParams) {
7901 // This checks for default arguments: a copy or move constructor with a
7902 // default argument is classified as a default constructor, and assignment
7903 // operations and destructors can't have default arguments.
7904 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7905 << CSM << MD->getSourceRange();
7906 HadError = true;
7907 } else if (MD->isVariadic()) {
7908 if (DeleteOnTypeMismatch)
7909 ShouldDeleteForTypeMismatch = true;
7910 else {
7911 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7912 << CSM << MD->getSourceRange();
7913 HadError = true;
7914 }
7915 }
7916
7918
7919 bool CanHaveConstParam = false;
7921 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7923 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7924
7925 QualType ReturnType = Context.VoidTy;
7928 // Check for return type matching.
7929 ReturnType = Type->getReturnType();
7931
7932 QualType DeclType =
7934 /*Qualifier=*/std::nullopt, RD, /*OwnsTag=*/false);
7935 DeclType = Context.getAddrSpaceQualType(
7936 DeclType, ThisType.getQualifiers().getAddressSpace());
7937 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7938
7939 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7940 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7942 << ExpectedReturnType;
7943 HadError = true;
7944 }
7945
7946 // A defaulted special member cannot have cv-qualifiers.
7947 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7948 if (DeleteOnTypeMismatch)
7949 ShouldDeleteForTypeMismatch = true;
7950 else {
7951 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7953 << getLangOpts().CPlusPlus14;
7954 HadError = true;
7955 }
7956 }
7957 // [C++23][dcl.fct.def.default]/p2.2
7958 // if F2 has an implicit object parameter of type “reference to C”,
7959 // F1 may be an explicit object member function whose explicit object
7960 // parameter is of (possibly different) type “reference to C”,
7961 // in which case the type of F1 would differ from the type of F2
7962 // in that the type of F1 has an additional parameter;
7963 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7964 ? MD->getParamDecl(0)->getType()
7965 : QualType();
7966 if (!ExplicitObjectParameter.isNull() &&
7967 (!ExplicitObjectParameter->isReferenceType() ||
7968 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7969 Context.getCanonicalTagType(RD)))) {
7970 if (DeleteOnTypeMismatch)
7971 ShouldDeleteForTypeMismatch = true;
7972 else {
7973 Diag(MD->getLocation(),
7974 diag::err_defaulted_special_member_explicit_object_mismatch)
7975 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7976 << MD->getSourceRange();
7977 HadError = true;
7978 }
7979 }
7980 }
7981
7982 // Check for parameter type matching.
7984 ExpectedParams
7985 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7986 : QualType();
7987 bool HasConstParam = false;
7988 if (ExpectedParams && ArgType->isReferenceType()) {
7989 // Argument must be reference to possibly-const T.
7990 QualType ReferentType = ArgType->getPointeeType();
7991 HasConstParam = ReferentType.isConstQualified();
7992
7993 if (ReferentType.isVolatileQualified()) {
7994 if (DeleteOnTypeMismatch)
7995 ShouldDeleteForTypeMismatch = true;
7996 else {
7997 Diag(MD->getLocation(),
7998 diag::err_defaulted_special_member_volatile_param)
7999 << CSM;
8000 HadError = true;
8001 }
8002 }
8003
8004 if (HasConstParam && !CanHaveConstParam) {
8005 if (DeleteOnTypeMismatch)
8006 ShouldDeleteForTypeMismatch = true;
8007 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8009 Diag(MD->getLocation(),
8010 diag::err_defaulted_special_member_copy_const_param)
8012 // FIXME: Explain why this special member can't be const.
8013 HadError = true;
8014 } else {
8015 Diag(MD->getLocation(),
8016 diag::err_defaulted_special_member_move_const_param)
8018 HadError = true;
8019 }
8020 }
8021 } else if (ExpectedParams) {
8022 // A copy assignment operator can take its argument by value, but a
8023 // defaulted one cannot.
8025 "unexpected non-ref argument");
8026 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
8027 HadError = true;
8028 }
8029
8030 // C++11 [dcl.fct.def.default]p2:
8031 // An explicitly-defaulted function may be declared constexpr only if it
8032 // would have been implicitly declared as constexpr,
8033 // Do not apply this rule to members of class templates, since core issue 1358
8034 // makes such functions always instantiate to constexpr functions. For
8035 // functions which cannot be constexpr (for non-constructors in C++11 and for
8036 // destructors in C++14 and C++17), this is checked elsewhere.
8037 //
8038 // FIXME: This should not apply if the member is deleted.
8039 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
8040 HasConstParam);
8041
8042 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8043 // If the instantiated template specialization of a constexpr function
8044 // template or member function of a class template would fail to satisfy
8045 // the requirements for a constexpr function or constexpr constructor, that
8046 // specialization is still a constexpr function or constexpr constructor,
8047 // even though a call to such a function cannot appear in a constant
8048 // expression.
8049 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8050 Constexpr = true;
8051
8052 if ((getLangOpts().CPlusPlus20 ||
8054 : isa<CXXConstructorDecl>(MD))) &&
8055 MD->isConstexpr() && !Constexpr &&
8057 if (!MD->isConsteval() && RD->getNumVBases()) {
8058 Diag(MD->getBeginLoc(),
8059 diag::err_incorrect_defaulted_constexpr_with_vb)
8060 << CSM;
8061 for (const auto &I : RD->vbases())
8062 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
8063 } else {
8064 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
8065 << CSM << MD->isConsteval();
8066 }
8067 HadError = true;
8068 // FIXME: Explain why the special member can't be constexpr.
8069 }
8070
8071 if (First) {
8072 // C++2a [dcl.fct.def.default]p3:
8073 // If a function is explicitly defaulted on its first declaration, it is
8074 // implicitly considered to be constexpr if the implicit declaration
8075 // would be.
8080
8081 if (!Type->hasExceptionSpec()) {
8082 // C++2a [except.spec]p3:
8083 // If a declaration of a function does not have a noexcept-specifier
8084 // [and] is defaulted on its first declaration, [...] the exception
8085 // specification is as specified below
8086 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8088 EPI.ExceptionSpec.SourceDecl = MD;
8089 MD->setType(
8090 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
8091 }
8092 }
8093
8094 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8095 if (First) {
8096 SetDeclDeleted(MD, MD->getLocation());
8097 if (!inTemplateInstantiation() && !HadError) {
8098 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
8099 if (ShouldDeleteForTypeMismatch) {
8100 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
8101 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
8102 /*Diagnose*/ true) &&
8103 DefaultLoc.isValid()) {
8104 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
8105 << FixItHint::CreateReplacement(DefaultLoc, "delete");
8106 }
8107 }
8108 if (ShouldDeleteForTypeMismatch && !HadError) {
8109 Diag(MD->getLocation(),
8110 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8111 << CSM;
8112 }
8113 } else {
8114 // C++11 [dcl.fct.def.default]p4:
8115 // [For a] user-provided explicitly-defaulted function [...] if such a
8116 // function is implicitly defined as deleted, the program is ill-formed.
8117 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
8118 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8119 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
8120 HadError = true;
8121 }
8122 }
8123
8124 return HadError;
8125}
8126
8127namespace {
8128/// Helper class for building and checking a defaulted comparison.
8129///
8130/// Defaulted functions are built in two phases:
8131///
8132/// * First, the set of operations that the function will perform are
8133/// identified, and some of them are checked. If any of the checked
8134/// operations is invalid in certain ways, the comparison function is
8135/// defined as deleted and no body is built.
8136/// * Then, if the function is not defined as deleted, the body is built.
8137///
8138/// This is accomplished by performing two visitation steps over the eventual
8139/// body of the function.
8140template<typename Derived, typename ResultList, typename Result,
8141 typename Subobject>
8142class DefaultedComparisonVisitor {
8143public:
8144 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
8145
8146 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8147 DefaultedComparisonKind DCK)
8148 : S(S), RD(RD), FD(FD), DCK(DCK) {
8149 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8150 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8151 // UnresolvedSet to avoid this copy.
8152 Fns.assign(Info->getUnqualifiedLookups().begin(),
8153 Info->getUnqualifiedLookups().end());
8154 }
8155 }
8156
8157 ResultList visit() {
8158 // The type of an lvalue naming a parameter of this function.
8159 QualType ParamLvalType =
8161
8162 ResultList Results;
8163
8164 switch (DCK) {
8165 case DefaultedComparisonKind::None:
8166 llvm_unreachable("not a defaulted comparison");
8167
8168 case DefaultedComparisonKind::Equal:
8169 case DefaultedComparisonKind::ThreeWay:
8170 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8171 return Results;
8172
8173 case DefaultedComparisonKind::NotEqual:
8174 case DefaultedComparisonKind::Relational:
8175 Results.add(getDerived().visitExpandedSubobject(
8176 ParamLvalType, getDerived().getCompleteObject()));
8177 return Results;
8178 }
8179 llvm_unreachable("");
8180 }
8181
8182protected:
8183 Derived &getDerived() { return static_cast<Derived&>(*this); }
8184
8185 /// Visit the expanded list of subobjects of the given type, as specified in
8186 /// C++2a [class.compare.default].
8187 ///
8188 /// \return \c true if the ResultList object said we're done, \c false if not.
8189 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8190 Qualifiers Quals) {
8191 // C++2a [class.compare.default]p4:
8192 // The direct base class subobjects of C
8193 for (CXXBaseSpecifier &Base : Record->bases())
8194 if (Results.add(getDerived().visitSubobject(
8195 S.Context.getQualifiedType(Base.getType(), Quals),
8196 getDerived().getBase(&Base))))
8197 return true;
8198
8199 // followed by the non-static data members of C
8200 for (FieldDecl *Field : Record->fields()) {
8201 // C++23 [class.bit]p2:
8202 // Unnamed bit-fields are not members ...
8203 if (Field->isUnnamedBitField())
8204 continue;
8205 // Recursively expand anonymous structs.
8206 if (Field->isAnonymousStructOrUnion()) {
8207 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8208 Quals))
8209 return true;
8210 continue;
8211 }
8212
8213 // Figure out the type of an lvalue denoting this field.
8214 Qualifiers FieldQuals = Quals;
8215 if (Field->isMutable())
8216 FieldQuals.removeConst();
8217 QualType FieldType =
8218 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8219
8220 if (Results.add(getDerived().visitSubobject(
8221 FieldType, getDerived().getField(Field))))
8222 return true;
8223 }
8224
8225 // form a list of subobjects.
8226 return false;
8227 }
8228
8229 Result visitSubobject(QualType Type, Subobject Subobj) {
8230 // In that list, any subobject of array type is recursively expanded
8231 const ArrayType *AT = S.Context.getAsArrayType(Type);
8232 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8233 return getDerived().visitSubobjectArray(CAT->getElementType(),
8234 CAT->getSize(), Subobj);
8235 return getDerived().visitExpandedSubobject(Type, Subobj);
8236 }
8237
8238 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8239 Subobject Subobj) {
8240 return getDerived().visitSubobject(Type, Subobj);
8241 }
8242
8243protected:
8244 Sema &S;
8245 CXXRecordDecl *RD;
8246 FunctionDecl *FD;
8247 DefaultedComparisonKind DCK;
8248 UnresolvedSet<16> Fns;
8249};
8250
8251/// Information about a defaulted comparison, as determined by
8252/// DefaultedComparisonAnalyzer.
8253struct DefaultedComparisonInfo {
8254 bool Deleted = false;
8255 bool Constexpr = true;
8256 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8257
8258 static DefaultedComparisonInfo deleted() {
8259 DefaultedComparisonInfo Deleted;
8260 Deleted.Deleted = true;
8261 return Deleted;
8262 }
8263
8264 bool add(const DefaultedComparisonInfo &R) {
8265 Deleted |= R.Deleted;
8266 Constexpr &= R.Constexpr;
8267 Category = commonComparisonType(Category, R.Category);
8268 return Deleted;
8269 }
8270};
8271
8272/// An element in the expanded list of subobjects of a defaulted comparison, as
8273/// specified in C++2a [class.compare.default]p4.
8274struct DefaultedComparisonSubobject {
8275 enum { CompleteObject, Member, Base } Kind;
8276 NamedDecl *Decl;
8277 SourceLocation Loc;
8278};
8279
8280/// A visitor over the notional body of a defaulted comparison that determines
8281/// whether that body would be deleted or constexpr.
8282class DefaultedComparisonAnalyzer
8283 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8284 DefaultedComparisonInfo,
8285 DefaultedComparisonInfo,
8286 DefaultedComparisonSubobject> {
8287public:
8288 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8289
8290private:
8291 DiagnosticKind Diagnose;
8292
8293public:
8294 using Base = DefaultedComparisonVisitor;
8295 using Result = DefaultedComparisonInfo;
8296 using Subobject = DefaultedComparisonSubobject;
8297
8298 friend Base;
8299
8300 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8301 DefaultedComparisonKind DCK,
8302 DiagnosticKind Diagnose = NoDiagnostics)
8303 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8304
8305 Result visit() {
8306 if ((DCK == DefaultedComparisonKind::Equal ||
8307 DCK == DefaultedComparisonKind::ThreeWay) &&
8308 RD->hasVariantMembers()) {
8309 // C++2a [class.compare.default]p2 [P2002R0]:
8310 // A defaulted comparison operator function for class C is defined as
8311 // deleted if [...] C has variant members.
8312 if (Diagnose == ExplainDeleted) {
8313 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8314 << FD << RD->isUnion() << RD;
8315 }
8316 return Result::deleted();
8317 }
8318
8319 return Base::visit();
8320 }
8321
8322private:
8323 Subobject getCompleteObject() {
8324 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8325 }
8326
8327 Subobject getBase(CXXBaseSpecifier *Base) {
8328 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8329 Base->getBaseTypeLoc()};
8330 }
8331
8332 Subobject getField(FieldDecl *Field) {
8333 return Subobject{Subobject::Member, Field, Field->getLocation()};
8334 }
8335
8336 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8337 // C++2a [class.compare.default]p2 [P2002R0]:
8338 // A defaulted <=> or == operator function for class C is defined as
8339 // deleted if any non-static data member of C is of reference type
8340 if (Type->isReferenceType()) {
8341 if (Diagnose == ExplainDeleted) {
8342 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8343 << FD << RD;
8344 }
8345 return Result::deleted();
8346 }
8347
8348 // [...] Let xi be an lvalue denoting the ith element [...]
8349 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8350 Expr *Args[] = {&Xi, &Xi};
8351
8352 // All operators start by trying to apply that same operator recursively.
8354 assert(OO != OO_None && "not an overloaded operator!");
8355 return visitBinaryOperator(OO, Args, Subobj);
8356 }
8357
8358 Result
8359 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8360 Subobject Subobj,
8361 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8362 // Note that there is no need to consider rewritten candidates here if
8363 // we've already found there is no viable 'operator<=>' candidate (and are
8364 // considering synthesizing a '<=>' from '==' and '<').
8365 OverloadCandidateSet CandidateSet(
8367 OverloadCandidateSet::OperatorRewriteInfo(
8368 OO, FD->getLocation(),
8369 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8370
8371 /// C++2a [class.compare.default]p1 [P2002R0]:
8372 /// [...] the defaulted function itself is never a candidate for overload
8373 /// resolution [...]
8374 CandidateSet.exclude(FD);
8375
8376 if (Args[0]->getType()->isOverloadableType())
8377 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8378 else
8379 // FIXME: We determine whether this is a valid expression by checking to
8380 // see if there's a viable builtin operator candidate for it. That isn't
8381 // really what the rules ask us to do, but should give the right results.
8382 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8383
8384 Result R;
8385
8387 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8388 case OR_Success: {
8389 // C++2a [class.compare.secondary]p2 [P2002R0]:
8390 // The operator function [...] is defined as deleted if [...] the
8391 // candidate selected by overload resolution is not a rewritten
8392 // candidate.
8393 if ((DCK == DefaultedComparisonKind::NotEqual ||
8394 DCK == DefaultedComparisonKind::Relational) &&
8395 !Best->RewriteKind) {
8396 if (Diagnose == ExplainDeleted) {
8397 if (Best->Function) {
8398 S.Diag(Best->Function->getLocation(),
8399 diag::note_defaulted_comparison_not_rewritten_callee)
8400 << FD;
8401 } else {
8402 assert(Best->Conversions.size() == 2 &&
8403 Best->Conversions[0].isUserDefined() &&
8404 "non-user-defined conversion from class to built-in "
8405 "comparison");
8406 S.Diag(Best->Conversions[0]
8407 .UserDefined.FoundConversionFunction.getDecl()
8408 ->getLocation(),
8409 diag::note_defaulted_comparison_not_rewritten_conversion)
8410 << FD;
8411 }
8412 }
8413 return Result::deleted();
8414 }
8415
8416 // Throughout C++2a [class.compare]: if overload resolution does not
8417 // result in a usable function, the candidate function is defined as
8418 // deleted. This requires that we selected an accessible function.
8419 //
8420 // Note that this only considers the access of the function when named
8421 // within the type of the subobject, and not the access path for any
8422 // derived-to-base conversion.
8423 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8424 if (ArgClass && Best->FoundDecl.getDecl() &&
8425 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8426 QualType ObjectType = Subobj.Kind == Subobject::Member
8427 ? Args[0]->getType()
8430 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8431 Diagnose == ExplainDeleted
8432 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8433 << FD << Subobj.Kind << Subobj.Decl
8434 : S.PDiag()))
8435 return Result::deleted();
8436 }
8437
8438 bool NeedsDeducing =
8439 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8440
8441 if (FunctionDecl *BestFD = Best->Function) {
8442 // C++2a [class.compare.default]p3 [P2002R0]:
8443 // A defaulted comparison function is constexpr-compatible if
8444 // [...] no overlod resolution performed [...] results in a
8445 // non-constexpr function.
8446 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8447 // If it's not constexpr, explain why not.
8448 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8449 if (Subobj.Kind != Subobject::CompleteObject)
8450 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8451 << Subobj.Kind << Subobj.Decl;
8452 S.Diag(BestFD->getLocation(),
8453 diag::note_defaulted_comparison_not_constexpr_here);
8454 // Bail out after explaining; we don't want any more notes.
8455 return Result::deleted();
8456 }
8457 R.Constexpr &= BestFD->isConstexpr();
8458
8459 if (NeedsDeducing) {
8460 // If any callee has an undeduced return type, deduce it now.
8461 // FIXME: It's not clear how a failure here should be handled. For
8462 // now, we produce an eager diagnostic, because that is forward
8463 // compatible with most (all?) other reasonable options.
8464 if (BestFD->getReturnType()->isUndeducedType() &&
8465 S.DeduceReturnType(BestFD, FD->getLocation(),
8466 /*Diagnose=*/false)) {
8467 // Don't produce a duplicate error when asked to explain why the
8468 // comparison is deleted: we diagnosed that when initially checking
8469 // the defaulted operator.
8470 if (Diagnose == NoDiagnostics) {
8471 S.Diag(
8472 FD->getLocation(),
8473 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8474 << Subobj.Kind << Subobj.Decl;
8475 S.Diag(
8476 Subobj.Loc,
8477 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8478 << Subobj.Kind << Subobj.Decl;
8479 S.Diag(BestFD->getLocation(),
8480 diag::note_defaulted_comparison_cannot_deduce_callee)
8481 << Subobj.Kind << Subobj.Decl;
8482 }
8483 return Result::deleted();
8484 }
8486 BestFD->getCallResultType());
8487 if (!Info) {
8488 if (Diagnose == ExplainDeleted) {
8489 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8490 << Subobj.Kind << Subobj.Decl
8491 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8492 S.Diag(BestFD->getLocation(),
8493 diag::note_defaulted_comparison_cannot_deduce_callee)
8494 << Subobj.Kind << Subobj.Decl;
8495 }
8496 return Result::deleted();
8497 }
8498 R.Category = Info->Kind;
8499 }
8500 } else {
8501 QualType T = Best->BuiltinParamTypes[0];
8502 assert(T == Best->BuiltinParamTypes[1] &&
8503 "builtin comparison for different types?");
8504 assert(Best->BuiltinParamTypes[2].isNull() &&
8505 "invalid builtin comparison");
8506
8507 // FIXME: If the type we deduced is a vector type, we mark the
8508 // comparison as deleted because we don't yet support this.
8509 if (isa<VectorType>(T)) {
8510 if (Diagnose == ExplainDeleted) {
8511 S.Diag(FD->getLocation(),
8512 diag::note_defaulted_comparison_vector_types)
8513 << FD;
8514 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8515 }
8516 return Result::deleted();
8517 }
8518
8519 if (NeedsDeducing) {
8520 std::optional<ComparisonCategoryType> Cat =
8522 assert(Cat && "no category for builtin comparison?");
8523 R.Category = *Cat;
8524 }
8525 }
8526
8527 // Note that we might be rewriting to a different operator. That call is
8528 // not considered until we come to actually build the comparison function.
8529 break;
8530 }
8531
8532 case OR_Ambiguous:
8533 if (Diagnose == ExplainDeleted) {
8534 unsigned Kind = 0;
8535 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8536 Kind = OO == OO_EqualEqual ? 1 : 2;
8537 CandidateSet.NoteCandidates(
8539 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8540 << FD << Kind << Subobj.Kind << Subobj.Decl),
8541 S, OCD_AmbiguousCandidates, Args);
8542 }
8543 R = Result::deleted();
8544 break;
8545
8546 case OR_Deleted:
8547 if (Diagnose == ExplainDeleted) {
8548 if ((DCK == DefaultedComparisonKind::NotEqual ||
8549 DCK == DefaultedComparisonKind::Relational) &&
8550 !Best->RewriteKind) {
8551 S.Diag(Best->Function->getLocation(),
8552 diag::note_defaulted_comparison_not_rewritten_callee)
8553 << FD;
8554 } else {
8555 S.Diag(Subobj.Loc,
8556 diag::note_defaulted_comparison_calls_deleted)
8557 << FD << Subobj.Kind << Subobj.Decl;
8558 S.NoteDeletedFunction(Best->Function);
8559 }
8560 }
8561 R = Result::deleted();
8562 break;
8563
8565 // If there's no usable candidate, we're done unless we can rewrite a
8566 // '<=>' in terms of '==' and '<'.
8567 if (OO == OO_Spaceship &&
8569 // For any kind of comparison category return type, we need a usable
8570 // '==' and a usable '<'.
8571 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8572 &CandidateSet)))
8573 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8574 break;
8575 }
8576
8577 if (Diagnose == ExplainDeleted) {
8578 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8579 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8580 << Subobj.Kind << Subobj.Decl;
8581
8582 // For a three-way comparison, list both the candidates for the
8583 // original operator and the candidates for the synthesized operator.
8584 if (SpaceshipCandidates) {
8585 SpaceshipCandidates->NoteCandidates(
8586 S, Args,
8587 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8588 Args, FD->getLocation()));
8589 S.Diag(Subobj.Loc,
8590 diag::note_defaulted_comparison_no_viable_function_synthesized)
8591 << (OO == OO_EqualEqual ? 0 : 1);
8592 }
8593
8594 CandidateSet.NoteCandidates(
8595 S, Args,
8596 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8597 FD->getLocation()));
8598 }
8599 R = Result::deleted();
8600 break;
8601 }
8602
8603 return R;
8604 }
8605};
8606
8607/// A list of statements.
8608struct StmtListResult {
8609 bool IsInvalid = false;
8610 llvm::SmallVector<Stmt*, 16> Stmts;
8611
8612 bool add(const StmtResult &S) {
8613 IsInvalid |= S.isInvalid();
8614 if (IsInvalid)
8615 return true;
8616 Stmts.push_back(S.get());
8617 return false;
8618 }
8619};
8620
8621/// A visitor over the notional body of a defaulted comparison that synthesizes
8622/// the actual body.
8623class DefaultedComparisonSynthesizer
8624 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8625 StmtListResult, StmtResult,
8626 std::pair<ExprResult, ExprResult>> {
8627 SourceLocation Loc;
8628 unsigned ArrayDepth = 0;
8629
8630public:
8631 using Base = DefaultedComparisonVisitor;
8632 using ExprPair = std::pair<ExprResult, ExprResult>;
8633
8634 friend Base;
8635
8636 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8637 DefaultedComparisonKind DCK,
8638 SourceLocation BodyLoc)
8639 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8640
8641 /// Build a suitable function body for this defaulted comparison operator.
8642 StmtResult build() {
8643 Sema::CompoundScopeRAII CompoundScope(S);
8644
8645 StmtListResult Stmts = visit();
8646 if (Stmts.IsInvalid)
8647 return StmtError();
8648
8649 ExprResult RetVal;
8650 switch (DCK) {
8651 case DefaultedComparisonKind::None:
8652 llvm_unreachable("not a defaulted comparison");
8653
8654 case DefaultedComparisonKind::Equal: {
8655 // C++2a [class.eq]p3:
8656 // [...] compar[e] the corresponding elements [...] until the first
8657 // index i where xi == yi yields [...] false. If no such index exists,
8658 // V is true. Otherwise, V is false.
8659 //
8660 // Join the comparisons with '&&'s and return the result. Use a right
8661 // fold (traversing the conditions right-to-left), because that
8662 // short-circuits more naturally.
8663 auto OldStmts = std::move(Stmts.Stmts);
8664 Stmts.Stmts.clear();
8665 ExprResult CmpSoFar;
8666 // Finish a particular comparison chain.
8667 auto FinishCmp = [&] {
8668 if (Expr *Prior = CmpSoFar.get()) {
8669 // Convert the last expression to 'return ...;'
8670 if (RetVal.isUnset() && Stmts.Stmts.empty())
8671 RetVal = CmpSoFar;
8672 // Convert any prior comparison to 'if (!(...)) return false;'
8673 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8674 return true;
8675 CmpSoFar = ExprResult();
8676 }
8677 return false;
8678 };
8679 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8680 Expr *E = dyn_cast<Expr>(EAsStmt);
8681 if (!E) {
8682 // Found an array comparison.
8683 if (FinishCmp() || Stmts.add(EAsStmt))
8684 return StmtError();
8685 continue;
8686 }
8687
8688 if (CmpSoFar.isUnset()) {
8689 CmpSoFar = E;
8690 continue;
8691 }
8692 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8693 if (CmpSoFar.isInvalid())
8694 return StmtError();
8695 }
8696 if (FinishCmp())
8697 return StmtError();
8698 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8699 // If no such index exists, V is true.
8700 if (RetVal.isUnset())
8701 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8702 break;
8703 }
8704
8705 case DefaultedComparisonKind::ThreeWay: {
8706 // Per C++2a [class.spaceship]p3, as a fallback add:
8707 // return static_cast<R>(std::strong_ordering::equal);
8708 QualType StrongOrdering = S.CheckComparisonCategoryType(
8709 ComparisonCategoryType::StrongOrdering, Loc,
8710 Sema::ComparisonCategoryUsage::DefaultedOperator);
8711 if (StrongOrdering.isNull())
8712 return StmtError();
8713 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8714 .getValueInfo(ComparisonCategoryResult::Equal)
8715 ->VD;
8716 RetVal = getDecl(EqualVD);
8717 if (RetVal.isInvalid())
8718 return StmtError();
8719 RetVal = buildStaticCastToR(RetVal.get());
8720 break;
8721 }
8722
8723 case DefaultedComparisonKind::NotEqual:
8724 case DefaultedComparisonKind::Relational:
8725 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8726 break;
8727 }
8728
8729 // Build the final return statement.
8730 if (RetVal.isInvalid())
8731 return StmtError();
8732 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8733 if (ReturnStmt.isInvalid())
8734 return StmtError();
8735 Stmts.Stmts.push_back(ReturnStmt.get());
8736
8737 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8738 }
8739
8740private:
8741 ExprResult getDecl(ValueDecl *VD) {
8742 return S.BuildDeclarationNameExpr(
8743 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8744 }
8745
8746 ExprResult getParam(unsigned I) {
8747 ParmVarDecl *PD = FD->getParamDecl(I);
8748 return getDecl(PD);
8749 }
8750
8751 ExprPair getCompleteObject() {
8752 unsigned Param = 0;
8753 ExprResult LHS;
8754 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8755 MD && MD->isImplicitObjectMemberFunction()) {
8756 // LHS is '*this'.
8757 LHS = S.ActOnCXXThis(Loc);
8758 if (!LHS.isInvalid())
8759 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8760 } else {
8761 LHS = getParam(Param++);
8762 }
8763 ExprResult RHS = getParam(Param++);
8764 assert(Param == FD->getNumParams());
8765 return {LHS, RHS};
8766 }
8767
8768 ExprPair getBase(CXXBaseSpecifier *Base) {
8769 ExprPair Obj = getCompleteObject();
8770 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8771 return {ExprError(), ExprError()};
8772 CXXCastPath Path = {Base};
8773 const auto CastToBase = [&](Expr *E) {
8774 QualType ToType = S.Context.getQualifiedType(
8775 Base->getType(), E->getType().getQualifiers());
8776 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8777 };
8778 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8779 }
8780
8781 ExprPair getField(FieldDecl *Field) {
8782 ExprPair Obj = getCompleteObject();
8783 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8784 return {ExprError(), ExprError()};
8785
8786 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8787 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8788 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8789 CXXScopeSpec(), Field, Found, NameInfo),
8790 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8791 CXXScopeSpec(), Field, Found, NameInfo)};
8792 }
8793
8794 // FIXME: When expanding a subobject, register a note in the code synthesis
8795 // stack to say which subobject we're comparing.
8796
8797 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8798 if (Cond.isInvalid())
8799 return StmtError();
8800
8801 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8802 if (NotCond.isInvalid())
8803 return StmtError();
8804
8805 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8806 assert(!False.isInvalid() && "should never fail");
8807 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8808 if (ReturnFalse.isInvalid())
8809 return StmtError();
8810
8811 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8812 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8813 Sema::ConditionKind::Boolean),
8814 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8815 }
8816
8817 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8818 ExprPair Subobj) {
8819 QualType SizeType = S.Context.getSizeType();
8820 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8821
8822 // Build 'size_t i$n = 0'.
8823 IdentifierInfo *IterationVarName = nullptr;
8824 {
8825 SmallString<8> Str;
8826 llvm::raw_svector_ostream OS(Str);
8827 OS << "i" << ArrayDepth;
8828 IterationVarName = &S.Context.Idents.get(OS.str());
8829 }
8830 VarDecl *IterationVar = VarDecl::Create(
8831 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8832 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8833 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8834 IterationVar->setInit(
8835 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8836 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8837
8838 auto IterRef = [&] {
8839 ExprResult Ref = S.BuildDeclarationNameExpr(
8840 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8841 IterationVar);
8842 assert(!Ref.isInvalid() && "can't reference our own variable?");
8843 return Ref.get();
8844 };
8845
8846 // Build 'i$n != Size'.
8847 ExprResult Cond = S.CreateBuiltinBinOp(
8848 Loc, BO_NE, IterRef(),
8849 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8850 assert(!Cond.isInvalid() && "should never fail");
8851
8852 // Build '++i$n'.
8853 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8854 assert(!Inc.isInvalid() && "should never fail");
8855
8856 // Build 'a[i$n]' and 'b[i$n]'.
8857 auto Index = [&](ExprResult E) {
8858 if (E.isInvalid())
8859 return ExprError();
8860 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8861 };
8862 Subobj.first = Index(Subobj.first);
8863 Subobj.second = Index(Subobj.second);
8864
8865 // Compare the array elements.
8866 ++ArrayDepth;
8867 StmtResult Substmt = visitSubobject(Type, Subobj);
8868 --ArrayDepth;
8869
8870 if (Substmt.isInvalid())
8871 return StmtError();
8872
8873 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8874 // For outer levels or for an 'operator<=>' we already have a suitable
8875 // statement that returns as necessary.
8876 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8877 assert(DCK == DefaultedComparisonKind::Equal &&
8878 "should have non-expression statement");
8879 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8880 if (Substmt.isInvalid())
8881 return StmtError();
8882 }
8883
8884 // Build 'for (...) ...'
8885 return S.ActOnForStmt(Loc, Loc, Init,
8886 S.ActOnCondition(nullptr, Loc, Cond.get(),
8887 Sema::ConditionKind::Boolean),
8888 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8889 Substmt.get());
8890 }
8891
8892 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8893 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8894 return StmtError();
8895
8898 ExprResult Op;
8899 if (Type->isOverloadableType())
8900 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8901 Obj.second.get(), /*PerformADL=*/true,
8902 /*AllowRewrittenCandidates=*/true, FD);
8903 else
8904 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8905 if (Op.isInvalid())
8906 return StmtError();
8907
8908 switch (DCK) {
8909 case DefaultedComparisonKind::None:
8910 llvm_unreachable("not a defaulted comparison");
8911
8912 case DefaultedComparisonKind::Equal:
8913 // Per C++2a [class.eq]p2, each comparison is individually contextually
8914 // converted to bool.
8915 Op = S.PerformContextuallyConvertToBool(Op.get());
8916 if (Op.isInvalid())
8917 return StmtError();
8918 return Op.get();
8919
8920 case DefaultedComparisonKind::ThreeWay: {
8921 // Per C++2a [class.spaceship]p3, form:
8922 // if (R cmp = static_cast<R>(op); cmp != 0)
8923 // return cmp;
8924 QualType R = FD->getReturnType();
8925 Op = buildStaticCastToR(Op.get());
8926 if (Op.isInvalid())
8927 return StmtError();
8928
8929 // R cmp = ...;
8930 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8931 VarDecl *VD =
8932 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8933 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8934 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8935 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8936
8937 // cmp != 0
8938 ExprResult VDRef = getDecl(VD);
8939 if (VDRef.isInvalid())
8940 return StmtError();
8941 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8942 Expr *Zero =
8943 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8945 if (VDRef.get()->getType()->isOverloadableType())
8946 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8947 true, FD);
8948 else
8949 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8950 if (Comp.isInvalid())
8951 return StmtError();
8952 Sema::ConditionResult Cond = S.ActOnCondition(
8953 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8954 if (Cond.isInvalid())
8955 return StmtError();
8956
8957 // return cmp;
8958 VDRef = getDecl(VD);
8959 if (VDRef.isInvalid())
8960 return StmtError();
8961 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8962 if (ReturnStmt.isInvalid())
8963 return StmtError();
8964
8965 // if (...)
8966 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8967 Loc, ReturnStmt.get(),
8968 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8969 }
8970
8971 case DefaultedComparisonKind::NotEqual:
8972 case DefaultedComparisonKind::Relational:
8973 // C++2a [class.compare.secondary]p2:
8974 // Otherwise, the operator function yields x @ y.
8975 return Op.get();
8976 }
8977 llvm_unreachable("");
8978 }
8979
8980 /// Build "static_cast<R>(E)".
8981 ExprResult buildStaticCastToR(Expr *E) {
8982 QualType R = FD->getReturnType();
8983 assert(!R->isUndeducedType() && "type should have been deduced already");
8984
8985 // Don't bother forming a no-op cast in the common case.
8986 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8987 return E;
8988 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8989 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8990 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8991 }
8992};
8993}
8994
8995/// Perform the unqualified lookups that might be needed to form a defaulted
8996/// comparison function for the given operator.
8998 UnresolvedSetImpl &Operators,
9000 auto Lookup = [&](OverloadedOperatorKind OO) {
9001 Self.LookupOverloadedOperatorName(OO, S, Operators);
9002 };
9003
9004 // Every defaulted operator looks up itself.
9005 Lookup(Op);
9006 // ... and the rewritten form of itself, if any.
9008 Lookup(ExtraOp);
9009
9010 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9011 // synthesize a three-way comparison from '<' and '=='. In a dependent
9012 // context, we also need to look up '==' in case we implicitly declare a
9013 // defaulted 'operator=='.
9014 if (Op == OO_Spaceship) {
9015 Lookup(OO_ExclaimEqual);
9016 Lookup(OO_Less);
9017 Lookup(OO_EqualEqual);
9018 }
9019}
9020
9023 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9024
9025 // Perform any unqualified lookups we're going to need to default this
9026 // function.
9027 if (S) {
9028 UnresolvedSet<32> Operators;
9029 lookupOperatorsForDefaultedComparison(*this, S, Operators,
9030 FD->getOverloadedOperator());
9033 Context, Operators.pairs()));
9034 }
9035
9036 // C++2a [class.compare.default]p1:
9037 // A defaulted comparison operator function for some class C shall be a
9038 // non-template function declared in the member-specification of C that is
9039 // -- a non-static const non-volatile member of C having one parameter of
9040 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9041 // -- a friend of C having two parameters of type const C& or two
9042 // parameters of type C.
9043
9044 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
9045 bool IsMethod = isa<CXXMethodDecl>(FD);
9046 if (IsMethod) {
9047 auto *MD = cast<CXXMethodDecl>(FD);
9048 assert(!MD->isStatic() && "comparison function cannot be a static member");
9049
9050 if (MD->getRefQualifier() == RQ_RValue) {
9051 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
9052
9053 // Remove the ref qualifier to recover.
9054 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9055 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9056 EPI.RefQualifier = RQ_None;
9057 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9058 FPT->getParamTypes(), EPI));
9059 }
9060
9061 // If we're out-of-class, this is the class we're comparing.
9062 if (!RD)
9063 RD = MD->getParent();
9064 QualType T = MD->getFunctionObjectParameterReferenceType();
9065 if (!T.getNonReferenceType().isConstQualified() &&
9066 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9067 SourceLocation Loc, InsertLoc;
9068 if (MD->isExplicitObjectMemberFunction()) {
9069 Loc = MD->getParamDecl(0)->getBeginLoc();
9070 InsertLoc = getLocForEndOfToken(
9071 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
9072 } else {
9073 Loc = MD->getLocation();
9074 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9075 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
9076 }
9077 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9078 // corresponding defaulted 'operator<=>' already.
9079 if (!MD->isImplicit()) {
9080 Diag(Loc, diag::err_defaulted_comparison_non_const)
9081 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
9082 }
9083
9084 // Add the 'const' to the type to recover.
9085 if (MD->isExplicitObjectMemberFunction()) {
9086 assert(T->isLValueReferenceType());
9087 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
9088 T.getNonReferenceType().withConst()));
9089 } else {
9090 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9091 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9092 EPI.TypeQuals.addConst();
9093 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9094 FPT->getParamTypes(), EPI));
9095 }
9096 }
9097
9098 if (MD->isVolatile()) {
9099 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
9100
9101 // Remove the 'volatile' from the type to recover.
9102 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9103 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9105 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9106 FPT->getParamTypes(), EPI));
9107 }
9108 }
9109
9110 if ((FD->getNumParams() -
9111 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9112 (IsMethod ? 1 : 2)) {
9113 // Let's not worry about using a variadic template pack here -- who would do
9114 // such a thing?
9115 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
9116 << int(IsMethod) << int(DCK);
9117 return true;
9118 }
9119
9120 const ParmVarDecl *KnownParm = nullptr;
9121 for (const ParmVarDecl *Param : FD->parameters()) {
9122 QualType ParmTy = Param->getType();
9123 if (!KnownParm) {
9124 auto CTy = ParmTy;
9125 // Is it `T const &`?
9126 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9127 QualType ExpectedTy;
9128 if (RD)
9129 ExpectedTy = Context.getCanonicalTagType(RD);
9130 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9131 CTy = Ref->getPointeeType();
9132 if (RD)
9133 ExpectedTy.addConst();
9134 Ok = true;
9135 }
9136
9137 // Is T a class?
9138 if (RD) {
9139 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
9140 } else {
9141 RD = CTy->getAsCXXRecordDecl();
9142 Ok &= RD != nullptr;
9143 }
9144
9145 if (Ok) {
9146 KnownParm = Param;
9147 } else {
9148 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9149 // corresponding defaulted 'operator<=>' already.
9150 if (!FD->isImplicit()) {
9151 if (RD) {
9152 CanQualType PlainTy = Context.getCanonicalTagType(RD);
9153 QualType RefTy =
9154 Context.getLValueReferenceType(PlainTy.withConst());
9155 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9156 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9157 << Param->getSourceRange();
9158 } else {
9159 assert(!IsMethod && "should know expected type for method");
9160 Diag(FD->getLocation(),
9161 diag::err_defaulted_comparison_param_unknown)
9162 << int(DCK) << ParmTy << Param->getSourceRange();
9163 }
9164 }
9165 return true;
9166 }
9167 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9168 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9169 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9170 << ParmTy << Param->getSourceRange();
9171 return true;
9172 }
9173 }
9174
9175 assert(RD && "must have determined class");
9176 if (IsMethod) {
9177 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9178 // In-class, must be a friend decl.
9179 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9180 } else {
9181 // Out of class, require the defaulted comparison to be a friend (of a
9182 // complete type, per CWG2547).
9183 if (RequireCompleteType(FD->getLocation(), Context.getCanonicalTagType(RD),
9184 diag::err_defaulted_comparison_not_friend, int(DCK),
9185 int(1)))
9186 return true;
9187
9188 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9189 return declaresSameEntity(F->getFriendDecl(), FD);
9190 })) {
9191 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9192 << int(DCK) << int(0) << RD;
9193 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9194 return true;
9195 }
9196 }
9197
9198 // C++2a [class.eq]p1, [class.rel]p1:
9199 // A [defaulted comparison other than <=>] shall have a declared return
9200 // type bool.
9203 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9204 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9205 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9206 << FD->getReturnTypeSourceRange();
9207 return true;
9208 }
9209 // C++2a [class.spaceship]p2 [P2002R0]:
9210 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9211 // R shall not contain a placeholder type.
9212 if (QualType RT = FD->getDeclaredReturnType();
9214 RT->getContainedDeducedType() &&
9215 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
9216 RT->getContainedAutoType()->isConstrained())) {
9217 Diag(FD->getLocation(),
9218 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9219 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9220 << FD->getReturnTypeSourceRange();
9221 return true;
9222 }
9223
9224 // For a defaulted function in a dependent class, defer all remaining checks
9225 // until instantiation.
9226 if (RD->isDependentType())
9227 return false;
9228
9229 // Determine whether the function should be defined as deleted.
9230 DefaultedComparisonInfo Info =
9231 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9232
9233 bool First = FD == FD->getCanonicalDecl();
9234
9235 if (!First) {
9236 if (Info.Deleted) {
9237 // C++11 [dcl.fct.def.default]p4:
9238 // [For a] user-provided explicitly-defaulted function [...] if such a
9239 // function is implicitly defined as deleted, the program is ill-formed.
9240 //
9241 // This is really just a consequence of the general rule that you can
9242 // only delete a function on its first declaration.
9243 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9244 << FD->isImplicit() << (int)DCK;
9245 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9246 DefaultedComparisonAnalyzer::ExplainDeleted)
9247 .visit();
9248 return true;
9249 }
9251 // C++20 [class.compare.default]p1:
9252 // [...] A definition of a comparison operator as defaulted that appears
9253 // in a class shall be the first declaration of that function.
9254 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9255 << (int)DCK;
9257 diag::note_previous_declaration);
9258 return true;
9259 }
9260 }
9261
9262 // If we want to delete the function, then do so; there's nothing else to
9263 // check in that case.
9264 if (Info.Deleted) {
9265 SetDeclDeleted(FD, FD->getLocation());
9266 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9267 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9268 << (int)DCK;
9269 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9270 DefaultedComparisonAnalyzer::ExplainDeleted)
9271 .visit();
9272 if (FD->getDefaultLoc().isValid())
9273 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9274 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9275 }
9276 return false;
9277 }
9278
9279 // C++2a [class.spaceship]p2:
9280 // The return type is deduced as the common comparison type of R0, R1, ...
9284 if (RetLoc.isInvalid())
9285 RetLoc = FD->getBeginLoc();
9286 // FIXME: Should we really care whether we have the complete type and the
9287 // 'enumerator' constants here? A forward declaration seems sufficient.
9289 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9290 if (Cat.isNull())
9291 return true;
9292 Context.adjustDeducedFunctionResultType(
9293 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9294 }
9295
9296 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9297 // An explicitly-defaulted function that is not defined as deleted may be
9298 // declared constexpr or consteval only if it is constexpr-compatible.
9299 // C++2a [class.compare.default]p3 [P2002R0]:
9300 // A defaulted comparison function is constexpr-compatible if it satisfies
9301 // the requirements for a constexpr function [...]
9302 // The only relevant requirements are that the parameter and return types are
9303 // literal types. The remaining conditions are checked by the analyzer.
9304 //
9305 // We support P2448R2 in language modes earlier than C++23 as an extension.
9306 // The concept of constexpr-compatible was removed.
9307 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9308 // A function explicitly defaulted on its first declaration is implicitly
9309 // inline, and is implicitly constexpr if it is constexpr-suitable.
9310 // C++23 [dcl.constexpr]p3
9311 // A function is constexpr-suitable if
9312 // - it is not a coroutine, and
9313 // - if the function is a constructor or destructor, its class does not
9314 // have any virtual base classes.
9315 if (FD->isConstexpr()) {
9316 if (!getLangOpts().CPlusPlus23 &&
9319 !Info.Constexpr) {
9320 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9321 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9322 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9323 DefaultedComparisonAnalyzer::ExplainConstexpr)
9324 .visit();
9325 }
9326 }
9327
9328 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9329 // If a constexpr-compatible function is explicitly defaulted on its first
9330 // declaration, it is implicitly considered to be constexpr.
9331 // FIXME: Only applying this to the first declaration seems problematic, as
9332 // simple reorderings can affect the meaning of the program.
9333 if (First && !FD->isConstexpr() && Info.Constexpr)
9335
9336 // C++2a [except.spec]p3:
9337 // If a declaration of a function does not have a noexcept-specifier
9338 // [and] is defaulted on its first declaration, [...] the exception
9339 // specification is as specified below
9340 if (FD->getExceptionSpecType() == EST_None) {
9341 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9342 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9344 EPI.ExceptionSpec.SourceDecl = FD;
9345 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9346 FPT->getParamTypes(), EPI));
9347 }
9348
9349 return false;
9350}
9351
9353 FunctionDecl *Spaceship) {
9356 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9357 Ctx.Entity = Spaceship;
9359
9360 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9361 EqualEqual->setImplicit();
9362
9364}
9365
9368 assert(FD->isDefaulted() && !FD->isDeleted() &&
9370 if (FD->willHaveBody() || FD->isInvalidDecl())
9371 return;
9372
9374
9375 // Add a context note for diagnostics produced after this point.
9376 Scope.addContextNote(UseLoc);
9377
9378 {
9379 // Build and set up the function body.
9380 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9381 // the type of the class being compared.
9382 auto PT = FD->getParamDecl(0)->getType();
9383 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9384 SourceLocation BodyLoc =
9385 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9386 StmtResult Body =
9387 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9388 if (Body.isInvalid()) {
9389 FD->setInvalidDecl();
9390 return;
9391 }
9392 FD->setBody(Body.get());
9393 FD->markUsed(Context);
9394 }
9395
9396 // The exception specification is needed because we are defining the
9397 // function. Note that this will reuse the body we just built.
9399
9401 L->CompletedImplicitDefinition(FD);
9402}
9403
9406 FunctionDecl *FD,
9408 ComputingExceptionSpec CES(S, FD, Loc);
9410
9411 if (FD->isInvalidDecl())
9412 return ExceptSpec;
9413
9414 // The common case is that we just defined the comparison function. In that
9415 // case, just look at whether the body can throw.
9416 if (FD->hasBody()) {
9417 ExceptSpec.CalledStmt(FD->getBody());
9418 } else {
9419 // Otherwise, build a body so we can check it. This should ideally only
9420 // happen when we're not actually marking the function referenced. (This is
9421 // only really important for efficiency: we don't want to build and throw
9422 // away bodies for comparison functions more than we strictly need to.)
9423
9424 // Pretend to synthesize the function body in an unevaluated context.
9425 // Note that we can't actually just go ahead and define the function here:
9426 // we are not permitted to mark its callees as referenced.
9430
9431 CXXRecordDecl *RD =
9433 ? FD->getDeclContext()
9434 : FD->getLexicalDeclContext());
9435 SourceLocation BodyLoc =
9436 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9437 StmtResult Body =
9438 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9439 if (!Body.isInvalid())
9440 ExceptSpec.CalledStmt(Body.get());
9441
9442 // FIXME: Can we hold onto this body and just transform it to potentially
9443 // evaluated when we're asked to define the function rather than rebuilding
9444 // it? Either that, or we should only build the bits of the body that we
9445 // need (the expressions, not the statements).
9446 }
9447
9448 return ExceptSpec;
9449}
9450
9452 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9454
9455 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9457
9458 // Perform any deferred checking of exception specifications for virtual
9459 // destructors.
9460 for (auto &Check : Overriding)
9461 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9462
9463 // Perform any deferred checking of exception specifications for befriended
9464 // special members.
9465 for (auto &Check : Equivalent)
9466 CheckEquivalentExceptionSpec(Check.second, Check.first);
9467}
9468
9469namespace {
9470/// CRTP base class for visiting operations performed by a special member
9471/// function (or inherited constructor).
9472template<typename Derived>
9473struct SpecialMemberVisitor {
9474 Sema &S;
9475 CXXMethodDecl *MD;
9478
9479 // Properties of the special member, computed for convenience.
9480 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9481
9482 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9484 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9485 switch (CSM) {
9489 IsConstructor = true;
9490 break;
9493 IsAssignment = true;
9494 break;
9496 break;
9498 llvm_unreachable("invalid special member kind");
9499 }
9500
9501 if (MD->getNumExplicitParams()) {
9502 if (const ReferenceType *RT =
9503 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9504 ConstArg = RT->getPointeeType().isConstQualified();
9505 }
9506 }
9507
9508 Derived &getDerived() { return static_cast<Derived&>(*this); }
9509
9510 /// Is this a "move" special member?
9511 bool isMove() const {
9512 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9513 CSM == CXXSpecialMemberKind::MoveAssignment;
9514 }
9515
9516 /// Look up the corresponding special member in the given class.
9517 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9518 unsigned Quals, bool IsMutable) {
9519 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9520 ConstArg && !IsMutable);
9521 }
9522
9523 /// Look up the constructor for the specified base class to see if it's
9524 /// overridden due to this being an inherited constructor.
9525 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9526 if (!ICI)
9527 return {};
9528 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9529 auto *BaseCtor =
9530 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9531 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9532 return MD;
9533 return {};
9534 }
9535
9536 /// A base or member subobject.
9537 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9538
9539 /// Get the location to use for a subobject in diagnostics.
9540 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9541 // FIXME: For an indirect virtual base, the direct base leading to
9542 // the indirect virtual base would be a more useful choice.
9543 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
9544 return B->getBaseTypeLoc();
9545 else
9546 return cast<FieldDecl *>(Subobj)->getLocation();
9547 }
9548
9549 enum BasesToVisit {
9550 /// Visit all non-virtual (direct) bases.
9551 VisitNonVirtualBases,
9552 /// Visit all direct bases, virtual or not.
9553 VisitDirectBases,
9554 /// Visit all non-virtual bases, and all virtual bases if the class
9555 /// is not abstract.
9556 VisitPotentiallyConstructedBases,
9557 /// Visit all direct or virtual bases.
9558 VisitAllBases
9559 };
9560
9561 // Visit the bases and members of the class.
9562 bool visit(BasesToVisit Bases) {
9563 CXXRecordDecl *RD = MD->getParent();
9564
9565 if (Bases == VisitPotentiallyConstructedBases)
9566 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9567
9568 for (auto &B : RD->bases())
9569 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9570 getDerived().visitBase(&B))
9571 return true;
9572
9573 if (Bases == VisitAllBases)
9574 for (auto &B : RD->vbases())
9575 if (getDerived().visitBase(&B))
9576 return true;
9577
9578 for (auto *F : RD->fields())
9579 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9580 getDerived().visitField(F))
9581 return true;
9582
9583 return false;
9584 }
9585};
9586}
9587
9588namespace {
9589struct SpecialMemberDeletionInfo
9590 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9591 bool Diagnose;
9592
9593 SourceLocation Loc;
9594
9595 bool AllFieldsAreConst;
9596
9597 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9599 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9600 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9601 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9602
9603 bool inUnion() const { return MD->getParent()->isUnion(); }
9604
9605 CXXSpecialMemberKind getEffectiveCSM() {
9606 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9607 }
9608
9609 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9610
9611 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9612
9613 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9614 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9615
9616 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9617 bool shouldDeleteForField(FieldDecl *FD);
9618 bool shouldDeleteForAllConstMembers();
9619
9620 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9621 unsigned Quals);
9622 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9623 Sema::SpecialMemberOverloadResult SMOR,
9624 bool IsDtorCallInCtor);
9625
9626 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9627};
9628}
9629
9630/// Is the given special member inaccessible when used on the given
9631/// sub-object.
9632bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9633 CXXMethodDecl *target) {
9634 /// If we're operating on a base class, the object type is the
9635 /// type of this special member.
9636 CanQualType objectTy;
9637 AccessSpecifier access = target->getAccess();
9638 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9639 objectTy = S.Context.getCanonicalTagType(MD->getParent());
9640 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9641
9642 // If we're operating on a field, the object type is the type of the field.
9643 } else {
9644 objectTy = S.Context.getCanonicalTagType(target->getParent());
9645 }
9646
9648 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9649}
9650
9651/// Check whether we should delete a special member due to the implicit
9652/// definition containing a call to a special member of a subobject.
9653bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9654 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9655 bool IsDtorCallInCtor) {
9656 CXXMethodDecl *Decl = SMOR.getMethod();
9657 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9658
9659 enum {
9660 NotSet = -1,
9661 NoDecl,
9662 DeletedDecl,
9663 MultipleDecl,
9664 InaccessibleDecl,
9665 NonTrivialDecl
9666 } DiagKind = NotSet;
9667
9669 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9670 Field->getParent()->isUnion()) {
9671 // [class.default.ctor]p2:
9672 // A defaulted default constructor for class X is defined as deleted if
9673 // - X is a union that has a variant member with a non-trivial default
9674 // constructor and no variant member of X has a default member
9675 // initializer
9676 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9677 if (RD->hasInClassInitializer())
9678 return false;
9679 }
9680 DiagKind = !Decl ? NoDecl : DeletedDecl;
9682 DiagKind = MultipleDecl;
9683 else if (!isAccessible(Subobj, Decl))
9684 DiagKind = InaccessibleDecl;
9685 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9686 !Decl->isTrivial()) {
9687 // A member of a union must have a trivial corresponding special member.
9688 // As a weird special case, a destructor call from a union's constructor
9689 // must be accessible and non-deleted, but need not be trivial. Such a
9690 // destructor is never actually called, but is semantically checked as
9691 // if it were.
9692 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9693 // [class.default.ctor]p2:
9694 // A defaulted default constructor for class X is defined as deleted if
9695 // - X is a union that has a variant member with a non-trivial default
9696 // constructor and no variant member of X has a default member
9697 // initializer
9698 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9699 if (!RD->hasInClassInitializer())
9700 DiagKind = NonTrivialDecl;
9701 } else {
9702 DiagKind = NonTrivialDecl;
9703 }
9704 }
9705
9706 if (DiagKind == NotSet)
9707 return false;
9708
9709 if (Diagnose) {
9710 if (Field) {
9711 S.Diag(Field->getLocation(),
9712 diag::note_deleted_special_member_class_subobject)
9713 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9714 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9715 } else {
9716 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9717 S.Diag(Base->getBeginLoc(),
9718 diag::note_deleted_special_member_class_subobject)
9719 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9720 << Base->getType() << DiagKind << IsDtorCallInCtor
9721 << /*IsObjCPtr*/ false;
9722 }
9723
9724 if (DiagKind == DeletedDecl)
9725 S.NoteDeletedFunction(Decl);
9726 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9727 }
9728
9729 return true;
9730}
9731
9732/// Check whether we should delete a special member function due to having a
9733/// direct or virtual base class or non-static data member of class type M.
9734bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9735 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9736 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9737 bool IsMutable = Field && Field->isMutable();
9738
9739 // C++11 [class.ctor]p5:
9740 // -- any direct or virtual base class, or non-static data member with no
9741 // brace-or-equal-initializer, has class type M (or array thereof) and
9742 // either M has no default constructor or overload resolution as applied
9743 // to M's default constructor results in an ambiguity or in a function
9744 // that is deleted or inaccessible
9745 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9746 // -- a direct or virtual base class B that cannot be copied/moved because
9747 // overload resolution, as applied to B's corresponding special member,
9748 // results in an ambiguity or a function that is deleted or inaccessible
9749 // from the defaulted special member
9750 // C++11 [class.dtor]p5:
9751 // -- any direct or virtual base class [...] has a type with a destructor
9752 // that is deleted or inaccessible
9753 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9754 Field->hasInClassInitializer()) &&
9755 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9756 false))
9757 return true;
9758
9759 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9760 // -- any direct or virtual base class or non-static data member has a
9761 // type with a destructor that is deleted or inaccessible
9762 if (IsConstructor) {
9763 Sema::SpecialMemberOverloadResult SMOR =
9764 S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
9765 false, false, false, false);
9766 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9767 return true;
9768 }
9769
9770 return false;
9771}
9772
9773bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9774 FieldDecl *FD, QualType FieldType) {
9775 // The defaulted special functions are defined as deleted if this is a variant
9776 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9777 // type under ARC.
9778 if (!FieldType.hasNonTrivialObjCLifetime())
9779 return false;
9780
9781 // Don't make the defaulted default constructor defined as deleted if the
9782 // member has an in-class initializer.
9783 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9785 return false;
9786
9787 if (Diagnose) {
9788 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9789 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9790 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9791 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9792 }
9793
9794 return true;
9795}
9796
9797bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9798 const FieldDecl *FD) {
9799 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9800 // Copy/move constructors/assignment operators are deleted if the field has an
9801 // address-discriminated ptrauth qualifier.
9802 PointerAuthQualifier Q = FieldType.getPointerAuth();
9803
9804 if (!Q || !Q.isAddressDiscriminated())
9805 return false;
9806
9807 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9808 CSM == CXXSpecialMemberKind::Destructor)
9809 return false;
9810
9811 if (Diagnose) {
9812 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9813 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9814 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9815 << /*IsDtorCallInCtor*/ false << 2;
9816 }
9817
9818 return true;
9819}
9820
9821/// Check whether we should delete a special member function due to the class
9822/// having a particular direct or virtual base class.
9823bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9824 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9825 // If program is correct, BaseClass cannot be null, but if it is, the error
9826 // must be reported elsewhere.
9827 if (!BaseClass)
9828 return false;
9829 // If we have an inheriting constructor, check whether we're calling an
9830 // inherited constructor instead of a default constructor.
9831 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9832 if (auto *BaseCtor = SMOR.getMethod()) {
9833 // Note that we do not check access along this path; other than that,
9834 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9835 // FIXME: Check that the base has a usable destructor! Sink this into
9836 // shouldDeleteForClassSubobject.
9837 if (BaseCtor->isDeleted() && Diagnose) {
9838 S.Diag(Base->getBeginLoc(),
9839 diag::note_deleted_special_member_class_subobject)
9840 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9841 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9842 << /*IsObjCPtr*/ false;
9843 S.NoteDeletedFunction(BaseCtor);
9844 }
9845 return BaseCtor->isDeleted();
9846 }
9847 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9848}
9849
9850/// Check whether we should delete a special member function due to the class
9851/// having a particular non-static data member.
9852bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9853 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9854 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9855
9856 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9857 return true;
9858
9859 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9860 return true;
9861
9862 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9863 // For a default constructor, all references must be initialized in-class
9864 // and, if a union, it must have a non-const member.
9865 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9866 if (Diagnose)
9867 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9868 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9869 return true;
9870 }
9871 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9872 // data member of const-qualified type (or array thereof) with no
9873 // brace-or-equal-initializer is not const-default-constructible.
9874 if (!inUnion() && FieldType.isConstQualified() &&
9875 !FD->hasInClassInitializer() &&
9876 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9877 if (Diagnose)
9878 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9879 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9880 return true;
9881 }
9882
9883 if (inUnion() && !FieldType.isConstQualified())
9884 AllFieldsAreConst = false;
9885 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9886 // For a copy constructor, data members must not be of rvalue reference
9887 // type.
9888 if (FieldType->isRValueReferenceType()) {
9889 if (Diagnose)
9890 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9891 << MD->getParent() << FD << FieldType;
9892 return true;
9893 }
9894 } else if (IsAssignment) {
9895 // For an assignment operator, data members must not be of reference type.
9896 if (FieldType->isReferenceType()) {
9897 if (Diagnose)
9898 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9899 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9900 return true;
9901 }
9902 if (!FieldRecord && FieldType.isConstQualified()) {
9903 // C++11 [class.copy]p23:
9904 // -- a non-static data member of const non-class type (or array thereof)
9905 if (Diagnose)
9906 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9907 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9908 return true;
9909 }
9910 }
9911
9912 if (FieldRecord) {
9913 // Some additional restrictions exist on the variant members.
9914 if (!inUnion() && FieldRecord->isUnion() &&
9915 FieldRecord->isAnonymousStructOrUnion()) {
9916 bool AllVariantFieldsAreConst = true;
9917
9918 // FIXME: Handle anonymous unions declared within anonymous unions.
9919 for (auto *UI : FieldRecord->fields()) {
9920 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9921
9922 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9923 return true;
9924
9925 if (shouldDeleteForVariantPtrAuthMember(&*UI))
9926 return true;
9927
9928 if (!UnionFieldType.isConstQualified())
9929 AllVariantFieldsAreConst = false;
9930
9931 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9932 if (UnionFieldRecord &&
9933 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9934 UnionFieldType.getCVRQualifiers()))
9935 return true;
9936 }
9937
9938 // At least one member in each anonymous union must be non-const
9939 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9940 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9941 if (Diagnose)
9942 S.Diag(FieldRecord->getLocation(),
9943 diag::note_deleted_default_ctor_all_const)
9944 << !!ICI << MD->getParent() << /*anonymous union*/1;
9945 return true;
9946 }
9947
9948 // Don't check the implicit member of the anonymous union type.
9949 // This is technically non-conformant but supported, and we have a
9950 // diagnostic for this elsewhere.
9951 return false;
9952 }
9953
9954 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9955 FieldType.getCVRQualifiers()))
9956 return true;
9957 }
9958
9959 return false;
9960}
9961
9962/// C++11 [class.ctor] p5:
9963/// A defaulted default constructor for a class X is defined as deleted if
9964/// X is a union and all of its variant members are of const-qualified type.
9965bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9966 // This is a silly definition, because it gives an empty union a deleted
9967 // default constructor. Don't do that.
9968 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9969 AllFieldsAreConst) {
9970 bool AnyFields = false;
9971 for (auto *F : MD->getParent()->fields())
9972 if ((AnyFields = !F->isUnnamedBitField()))
9973 break;
9974 if (!AnyFields)
9975 return false;
9976 if (Diagnose)
9977 S.Diag(MD->getParent()->getLocation(),
9978 diag::note_deleted_default_ctor_all_const)
9979 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9980 return true;
9981 }
9982 return false;
9983}
9984
9985/// Determine whether a defaulted special member function should be defined as
9986/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9987/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9991 bool Diagnose) {
9992 if (MD->isInvalidDecl())
9993 return false;
9994 CXXRecordDecl *RD = MD->getParent();
9995 assert(!RD->isDependentType() && "do deletion after instantiation");
9996 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9997 RD->isInvalidDecl())
9998 return false;
9999
10000 // C++11 [expr.lambda.prim]p19:
10001 // The closure type associated with a lambda-expression has a
10002 // deleted (8.4.3) default constructor and a deleted copy
10003 // assignment operator.
10004 // C++2a adds back these operators if the lambda has no lambda-capture.
10008 if (Diagnose)
10009 Diag(RD->getLocation(), diag::note_lambda_decl);
10010 return true;
10011 }
10012
10013 // C++11 [class.copy]p7, p18:
10014 // If the class definition declares a move constructor or move assignment
10015 // operator, an implicitly declared copy constructor or copy assignment
10016 // operator is defined as deleted.
10019 CXXMethodDecl *UserDeclaredMove = nullptr;
10020
10021 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10022 // deletion of the corresponding copy operation, not both copy operations.
10023 // MSVC 2015 has adopted the standards conforming behavior.
10024 bool DeletesOnlyMatchingCopy =
10025 getLangOpts().MSVCCompat &&
10026 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
10027
10029 (!DeletesOnlyMatchingCopy ||
10031 if (!Diagnose) return true;
10032
10033 // Find any user-declared move constructor.
10034 for (auto *I : RD->ctors()) {
10035 if (I->isMoveConstructor()) {
10036 UserDeclaredMove = I;
10037 break;
10038 }
10039 }
10040 assert(UserDeclaredMove);
10041 } else if (RD->hasUserDeclaredMoveAssignment() &&
10042 (!DeletesOnlyMatchingCopy ||
10044 if (!Diagnose) return true;
10045
10046 // Find any user-declared move assignment operator.
10047 for (auto *I : RD->methods()) {
10048 if (I->isMoveAssignmentOperator()) {
10049 UserDeclaredMove = I;
10050 break;
10051 }
10052 }
10053 assert(UserDeclaredMove);
10054 }
10055
10056 if (UserDeclaredMove) {
10057 Diag(UserDeclaredMove->getLocation(),
10058 diag::note_deleted_copy_user_declared_move)
10059 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10060 << UserDeclaredMove->isMoveAssignmentOperator();
10061 return true;
10062 }
10063 }
10064
10065 // Do access control from the special member function
10066 ContextRAII MethodContext(*this, MD);
10067
10068 // C++11 [class.dtor]p5:
10069 // -- for a virtual destructor, lookup of the non-array deallocation function
10070 // results in an ambiguity or in a function that is deleted or inaccessible
10071 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10072 FunctionDecl *OperatorDelete = nullptr;
10073 CanQualType DeallocType = Context.getCanonicalTagType(RD);
10074 DeclarationName Name =
10075 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
10079 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
10080 OperatorDelete, IDP,
10081 /*Diagnose=*/false)) {
10082 if (Diagnose)
10083 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
10084 return true;
10085 }
10086 }
10087
10088 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10089
10090 // Per DR1611, do not consider virtual bases of constructors of abstract
10091 // classes, since we are not going to construct them.
10092 // Per DR1658, do not consider virtual bases of destructors of abstract
10093 // classes either.
10094 // Per DR2180, for assignment operators we only assign (and thus only
10095 // consider) direct bases.
10096 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
10097 : SMI.VisitPotentiallyConstructedBases))
10098 return true;
10099
10100 if (SMI.shouldDeleteForAllConstMembers())
10101 return true;
10102
10103 if (getLangOpts().CUDA) {
10104 // We should delete the special member in CUDA mode if target inference
10105 // failed.
10106 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10107 // is treated as certain special member, which may not reflect what special
10108 // member MD really is. However inferTargetForImplicitSpecialMember
10109 // expects CSM to match MD, therefore recalculate CSM.
10110 assert(ICI || CSM == getSpecialMember(MD));
10111 auto RealCSM = CSM;
10112 if (ICI)
10113 RealCSM = getSpecialMember(MD);
10114
10115 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
10116 SMI.ConstArg, Diagnose);
10117 }
10118
10119 return false;
10120}
10121
10124 assert(DFK && "not a defaultable function");
10125 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10126
10127 if (DFK.isSpecialMember()) {
10129 nullptr, /*Diagnose=*/true);
10130 } else {
10131 DefaultedComparisonAnalyzer(
10133 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10134 .visit();
10135 }
10136}
10137
10138/// Perform lookup for a special member of the specified kind, and determine
10139/// whether it is trivial. If the triviality can be determined without the
10140/// lookup, skip it. This is intended for use when determining whether a
10141/// special member of a containing object is trivial, and thus does not ever
10142/// perform overload resolution for default constructors.
10143///
10144/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10145/// member that was most likely to be intended to be trivial, if any.
10146///
10147/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10148/// determine whether the special member is trivial.
10150 CXXSpecialMemberKind CSM, unsigned Quals,
10151 bool ConstRHS, TrivialABIHandling TAH,
10152 CXXMethodDecl **Selected) {
10153 if (Selected)
10154 *Selected = nullptr;
10155
10156 switch (CSM) {
10158 llvm_unreachable("not a special member");
10159
10161 // C++11 [class.ctor]p5:
10162 // A default constructor is trivial if:
10163 // - all the [direct subobjects] have trivial default constructors
10164 //
10165 // Note, no overload resolution is performed in this case.
10167 return true;
10168
10169 if (Selected) {
10170 // If there's a default constructor which could have been trivial, dig it
10171 // out. Otherwise, if there's any user-provided default constructor, point
10172 // to that as an example of why there's not a trivial one.
10173 CXXConstructorDecl *DefCtor = nullptr;
10176 for (auto *CI : RD->ctors()) {
10177 if (!CI->isDefaultConstructor())
10178 continue;
10179 DefCtor = CI;
10180 if (!DefCtor->isUserProvided())
10181 break;
10182 }
10183
10184 *Selected = DefCtor;
10185 }
10186
10187 return false;
10188
10190 // C++11 [class.dtor]p5:
10191 // A destructor is trivial if:
10192 // - all the direct [subobjects] have trivial destructors
10193 if (RD->hasTrivialDestructor() ||
10196 return true;
10197
10198 if (Selected) {
10199 if (RD->needsImplicitDestructor())
10201 *Selected = RD->getDestructor();
10202 }
10203
10204 return false;
10205
10207 // C++11 [class.copy]p12:
10208 // A copy constructor is trivial if:
10209 // - the constructor selected to copy each direct [subobject] is trivial
10210 if (RD->hasTrivialCopyConstructor() ||
10213 if (Quals == Qualifiers::Const)
10214 // We must either select the trivial copy constructor or reach an
10215 // ambiguity; no need to actually perform overload resolution.
10216 return true;
10217 } else if (!Selected) {
10218 return false;
10219 }
10220 // In C++98, we are not supposed to perform overload resolution here, but we
10221 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10222 // cases like B as having a non-trivial copy constructor:
10223 // struct A { template<typename T> A(T&); };
10224 // struct B { mutable A a; };
10225 goto NeedOverloadResolution;
10226
10228 // C++11 [class.copy]p25:
10229 // A copy assignment operator is trivial if:
10230 // - the assignment operator selected to copy each direct [subobject] is
10231 // trivial
10232 if (RD->hasTrivialCopyAssignment()) {
10233 if (Quals == Qualifiers::Const)
10234 return true;
10235 } else if (!Selected) {
10236 return false;
10237 }
10238 // In C++98, we are not supposed to perform overload resolution here, but we
10239 // treat that as a language defect.
10240 goto NeedOverloadResolution;
10241
10244 NeedOverloadResolution:
10246 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10247
10248 // The standard doesn't describe how to behave if the lookup is ambiguous.
10249 // We treat it as not making the member non-trivial, just like the standard
10250 // mandates for the default constructor. This should rarely matter, because
10251 // the member will also be deleted.
10253 return true;
10254
10255 if (!SMOR.getMethod()) {
10256 assert(SMOR.getKind() ==
10258 return false;
10259 }
10260
10261 // We deliberately don't check if we found a deleted special member. We're
10262 // not supposed to!
10263 if (Selected)
10264 *Selected = SMOR.getMethod();
10265
10269 return SMOR.getMethod()->isTrivialForCall();
10270 return SMOR.getMethod()->isTrivial();
10271 }
10272
10273 llvm_unreachable("unknown special method kind");
10274}
10275
10277 for (auto *CI : RD->ctors())
10278 if (!CI->isImplicit())
10279 return CI;
10280
10281 // Look for constructor templates.
10283 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10284 if (CXXConstructorDecl *CD =
10285 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10286 return CD;
10287 }
10288
10289 return nullptr;
10290}
10291
10292/// The kind of subobject we are checking for triviality. The values of this
10293/// enumeration are used in diagnostics.
10295 /// The subobject is a base class.
10297 /// The subobject is a non-static data member.
10299 /// The object is actually the complete object.
10301};
10302
10303/// Check whether the special member selected for a given type would be trivial.
10305 QualType SubType, bool ConstRHS,
10308 TrivialABIHandling TAH, bool Diagnose) {
10309 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10310 if (!SubRD)
10311 return true;
10312
10313 CXXMethodDecl *Selected;
10314 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10315 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10316 return true;
10317
10318 if (Diagnose) {
10319 if (ConstRHS)
10320 SubType.addConst();
10321
10322 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10323 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10324 << Kind << SubType.getUnqualifiedType();
10326 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10327 } else if (!Selected)
10328 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10329 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10330 else if (Selected->isUserProvided()) {
10331 if (Kind == TSK_CompleteObject)
10332 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10333 << Kind << SubType.getUnqualifiedType() << CSM;
10334 else {
10335 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10336 << Kind << SubType.getUnqualifiedType() << CSM;
10337 S.Diag(Selected->getLocation(), diag::note_declared_at);
10338 }
10339 } else {
10340 if (Kind != TSK_CompleteObject)
10341 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10342 << Kind << SubType.getUnqualifiedType() << CSM;
10343
10344 // Explain why the defaulted or deleted special member isn't trivial.
10345 S.SpecialMemberIsTrivial(Selected, CSM,
10347 }
10348 }
10349
10350 return false;
10351}
10352
10353/// Check whether the members of a class type allow a special member to be
10354/// trivial.
10356 CXXSpecialMemberKind CSM, bool ConstArg,
10357 TrivialABIHandling TAH, bool Diagnose) {
10358 for (const auto *FI : RD->fields()) {
10359 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10360 continue;
10361
10362 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10363
10364 // Pretend anonymous struct or union members are members of this class.
10365 if (FI->isAnonymousStructOrUnion()) {
10366 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10367 CSM, ConstArg, TAH, Diagnose))
10368 return false;
10369 continue;
10370 }
10371
10372 // C++11 [class.ctor]p5:
10373 // A default constructor is trivial if [...]
10374 // -- no non-static data member of its class has a
10375 // brace-or-equal-initializer
10377 FI->hasInClassInitializer()) {
10378 if (Diagnose)
10379 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10380 << FI;
10381 return false;
10382 }
10383
10384 // Objective C ARC 4.3.5:
10385 // [...] nontrivally ownership-qualified types are [...] not trivially
10386 // default constructible, copy constructible, move constructible, copy
10387 // assignable, move assignable, or destructible [...]
10388 if (FieldType.hasNonTrivialObjCLifetime()) {
10389 if (Diagnose)
10390 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10391 << RD << FieldType.getObjCLifetime();
10392 return false;
10393 }
10394
10395 bool ConstRHS = ConstArg && !FI->isMutable();
10396 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10397 CSM, TSK_Field, TAH, Diagnose))
10398 return false;
10399 }
10400
10401 return true;
10402}
10403
10406 CanQualType Ty = Context.getCanonicalTagType(RD);
10407
10408 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10410 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10413 /*Diagnose*/ true);
10414}
10415
10417 TrivialABIHandling TAH, bool Diagnose) {
10418 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10419 "not special enough");
10420
10421 CXXRecordDecl *RD = MD->getParent();
10422
10423 bool ConstArg = false;
10424
10425 // C++11 [class.copy]p12, p25: [DR1593]
10426 // A [special member] is trivial if [...] its parameter-type-list is
10427 // equivalent to the parameter-type-list of an implicit declaration [...]
10428 switch (CSM) {
10431 // Trivial default constructors and destructors cannot have parameters.
10432 break;
10433
10436 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10437 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10438
10439 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10440 // if they are not user-provided and their parameter-type-list is equivalent
10441 // to the parameter-type-list of an implicit declaration. This maintains the
10442 // behavior before dr2171 was implemented.
10443 //
10444 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10445 // trivial, if they are not user-provided, regardless of the qualifiers on
10446 // the reference type.
10447 const bool ClangABICompat14 =
10448 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver14);
10449 if (!RT ||
10451 ClangABICompat14)) {
10452 if (Diagnose)
10453 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10454 << Param0->getSourceRange() << Param0->getType()
10455 << Context.getLValueReferenceType(
10456 Context.getCanonicalTagType(RD).withConst());
10457 return false;
10458 }
10459
10460 ConstArg = RT->getPointeeType().isConstQualified();
10461 break;
10462 }
10463
10466 // Trivial move operations always have non-cv-qualified parameters.
10467 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10468 const RValueReferenceType *RT =
10469 Param0->getType()->getAs<RValueReferenceType>();
10470 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10471 if (Diagnose)
10472 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10473 << Param0->getSourceRange() << Param0->getType()
10474 << Context.getRValueReferenceType(Context.getCanonicalTagType(RD));
10475 return false;
10476 }
10477 break;
10478 }
10479
10481 llvm_unreachable("not a special member");
10482 }
10483
10484 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10485 if (Diagnose)
10487 diag::note_nontrivial_default_arg)
10489 return false;
10490 }
10491 if (MD->isVariadic()) {
10492 if (Diagnose)
10493 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10494 return false;
10495 }
10496
10497 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10498 // A copy/move [constructor or assignment operator] is trivial if
10499 // -- the [member] selected to copy/move each direct base class subobject
10500 // is trivial
10501 //
10502 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10503 // A [default constructor or destructor] is trivial if
10504 // -- all the direct base classes have trivial [default constructors or
10505 // destructors]
10506 for (const auto &BI : RD->bases())
10507 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10508 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10509 return false;
10510
10511 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10512 // A copy/move [constructor or assignment operator] for a class X is
10513 // trivial if
10514 // -- for each non-static data member of X that is of class type (or array
10515 // thereof), the constructor selected to copy/move that member is
10516 // trivial
10517 //
10518 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10519 // A [default constructor or destructor] is trivial if
10520 // -- for all of the non-static data members of its class that are of class
10521 // type (or array thereof), each such class has a trivial [default
10522 // constructor or destructor]
10523 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10524 return false;
10525
10526 // C++11 [class.dtor]p5:
10527 // A destructor is trivial if [...]
10528 // -- the destructor is not virtual
10529 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10530 if (Diagnose)
10531 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10532 return false;
10533 }
10534
10535 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10536 // A [special member] for class X is trivial if [...]
10537 // -- class X has no virtual functions and no virtual base classes
10539 MD->getParent()->isDynamicClass()) {
10540 if (!Diagnose)
10541 return false;
10542
10543 if (RD->getNumVBases()) {
10544 // Check for virtual bases. We already know that the corresponding
10545 // member in all bases is trivial, so vbases must all be direct.
10546 CXXBaseSpecifier &BS = *RD->vbases_begin();
10547 assert(BS.isVirtual());
10548 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10549 return false;
10550 }
10551
10552 // Must have a virtual method.
10553 for (const auto *MI : RD->methods()) {
10554 if (MI->isVirtual()) {
10555 SourceLocation MLoc = MI->getBeginLoc();
10556 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10557 return false;
10558 }
10559 }
10560
10561 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10562 }
10563
10564 // Looks like it's trivial!
10565 return true;
10566}
10567
10568namespace {
10569struct FindHiddenVirtualMethod {
10570 Sema *S;
10572 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10573 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10574
10575private:
10576 /// Check whether any most overridden method from MD in Methods
10577 static bool CheckMostOverridenMethods(
10578 const CXXMethodDecl *MD,
10579 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10580 if (MD->size_overridden_methods() == 0)
10581 return Methods.count(MD->getCanonicalDecl());
10582 for (const CXXMethodDecl *O : MD->overridden_methods())
10583 if (CheckMostOverridenMethods(O, Methods))
10584 return true;
10585 return false;
10586 }
10587
10588public:
10589 /// Member lookup function that determines whether a given C++
10590 /// method overloads virtual methods in a base class without overriding any,
10591 /// to be used with CXXRecordDecl::lookupInBases().
10592 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10593 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10594 DeclarationName Name = Method->getDeclName();
10595 assert(Name.getNameKind() == DeclarationName::Identifier);
10596
10597 bool foundSameNameMethod = false;
10598 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10599 for (Path.Decls = BaseRecord->lookup(Name).begin();
10600 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10601 NamedDecl *D = *Path.Decls;
10602 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10603 MD = MD->getCanonicalDecl();
10604 foundSameNameMethod = true;
10605 // Interested only in hidden virtual methods.
10606 if (!MD->isVirtual())
10607 continue;
10608 // If the method we are checking overrides a method from its base
10609 // don't warn about the other overloaded methods. Clang deviates from
10610 // GCC by only diagnosing overloads of inherited virtual functions that
10611 // do not override any other virtual functions in the base. GCC's
10612 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10613 // function from a base class. These cases may be better served by a
10614 // warning (not specific to virtual functions) on call sites when the
10615 // call would select a different function from the base class, were it
10616 // visible.
10617 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10618 if (!S->IsOverload(Method, MD, false))
10619 return true;
10620 // Collect the overload only if its hidden.
10621 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10622 overloadedMethods.push_back(MD);
10623 }
10624 }
10625
10626 if (foundSameNameMethod)
10627 OverloadedMethods.append(overloadedMethods.begin(),
10628 overloadedMethods.end());
10629 return foundSameNameMethod;
10630 }
10631};
10632} // end anonymous namespace
10633
10634/// Add the most overridden methods from MD to Methods
10636 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10637 if (MD->size_overridden_methods() == 0)
10638 Methods.insert(MD->getCanonicalDecl());
10639 else
10640 for (const CXXMethodDecl *O : MD->overridden_methods())
10641 AddMostOverridenMethods(O, Methods);
10642}
10643
10645 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10646 if (!MD->getDeclName().isIdentifier())
10647 return;
10648
10649 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10650 /*bool RecordPaths=*/false,
10651 /*bool DetectVirtual=*/false);
10652 FindHiddenVirtualMethod FHVM;
10653 FHVM.Method = MD;
10654 FHVM.S = this;
10655
10656 // Keep the base methods that were overridden or introduced in the subclass
10657 // by 'using' in a set. A base method not in this set is hidden.
10658 CXXRecordDecl *DC = MD->getParent();
10659 for (NamedDecl *ND : DC->lookup(MD->getDeclName())) {
10660 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(ND))
10661 ND = shad->getTargetDecl();
10662 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10663 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10664 }
10665
10666 if (DC->lookupInBases(FHVM, Paths))
10667 OverloadedMethods = FHVM.OverloadedMethods;
10668}
10669
10671 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10672 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10674 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10675 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10676 Diag(overloadedMD->getLocation(), PD);
10677 }
10678}
10679
10681 if (MD->isInvalidDecl())
10682 return;
10683
10684 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10685 return;
10686
10687 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10688 FindHiddenVirtualMethods(MD, OverloadedMethods);
10689 if (!OverloadedMethods.empty()) {
10690 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10691 << MD << (OverloadedMethods.size() > 1);
10692
10693 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10694 }
10695}
10696
10698 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10699 // No diagnostics if this is a template instantiation.
10701 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10702 diag::ext_cannot_use_trivial_abi) << &RD;
10703 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10704 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10705 }
10706 RD.dropAttr<TrivialABIAttr>();
10707 };
10708
10709 // Ill-formed if the struct has virtual functions.
10710 if (RD.isPolymorphic()) {
10711 PrintDiagAndRemoveAttr(1);
10712 return;
10713 }
10714
10715 for (const auto &B : RD.bases()) {
10716 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10717 // virtual base.
10718 if (!B.getType()->isDependentType() &&
10719 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10720 PrintDiagAndRemoveAttr(2);
10721 return;
10722 }
10723
10724 if (B.isVirtual()) {
10725 PrintDiagAndRemoveAttr(3);
10726 return;
10727 }
10728 }
10729
10730 for (const auto *FD : RD.fields()) {
10731 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10732 // non-trivial for the purpose of calls.
10733 QualType FT = FD->getType();
10735 PrintDiagAndRemoveAttr(4);
10736 return;
10737 }
10738
10739 // Ill-formed if the field is an address-discriminated value.
10741 PrintDiagAndRemoveAttr(6);
10742 return;
10743 }
10744
10745 if (const auto *RT =
10746 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10747 if (!RT->isDependentType() &&
10748 !cast<CXXRecordDecl>(RT->getDecl()->getDefinitionOrSelf())
10749 ->canPassInRegisters()) {
10750 PrintDiagAndRemoveAttr(5);
10751 return;
10752 }
10753 }
10754
10756 return;
10757
10758 // Ill-formed if the copy and move constructors are deleted.
10759 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10760 // If the type is dependent, then assume it might have
10761 // implicit copy or move ctor because we won't know yet at this point.
10762 if (RD.isDependentType())
10763 return true;
10766 return true;
10769 return true;
10770 for (const CXXConstructorDecl *CD : RD.ctors())
10771 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10772 return true;
10773 return false;
10774 };
10775
10776 if (!HasNonDeletedCopyOrMoveConstructor()) {
10777 PrintDiagAndRemoveAttr(0);
10778 return;
10779 }
10780}
10781
10783 CXXRecordDecl &RD) {
10784 if (RequireCompleteType(RD.getLocation(), Context.getCanonicalTagType(&RD),
10785 diag::err_incomplete_type_vtable_pointer_auth))
10786 return;
10787
10788 const CXXRecordDecl *PrimaryBase = &RD;
10789 if (PrimaryBase->hasAnyDependentBases())
10790 return;
10791
10792 while (1) {
10793 assert(PrimaryBase);
10794 const CXXRecordDecl *Base = nullptr;
10795 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10796 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10797 continue;
10798 Base = BasePtr.getType()->getAsCXXRecordDecl();
10799 break;
10800 }
10801 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10802 break;
10803 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10804 diag::err_non_top_level_vtable_pointer_auth)
10805 << &RD << Base;
10806 PrimaryBase = Base;
10807 }
10808
10809 if (!RD.isPolymorphic())
10810 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10811 diag::err_non_polymorphic_vtable_pointer_auth)
10812 << &RD;
10813}
10814
10817 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10818 if (!TagDecl)
10819 return;
10820
10822
10823 for (const ParsedAttr &AL : AttrList) {
10824 if (AL.getKind() != ParsedAttr::AT_Visibility)
10825 continue;
10826 AL.setInvalid();
10827 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10828 }
10829
10830 ActOnFields(S, RLoc, TagDecl,
10832 // strict aliasing violation!
10833 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10834 FieldCollector->getCurNumFields()),
10835 LBrac, RBrac, AttrList);
10836
10838}
10839
10840/// Find the equality comparison functions that should be implicitly declared
10841/// in a given class definition, per C++2a [class.compare.default]p3.
10843 ASTContext &Ctx, CXXRecordDecl *RD,
10845 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10846 if (!RD->lookup(EqEq).empty())
10847 // Member operator== explicitly declared: no implicit operator==s.
10848 return;
10849
10850 // Traverse friends looking for an '==' or a '<=>'.
10851 for (FriendDecl *Friend : RD->friends()) {
10852 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10853 if (!FD) continue;
10854
10855 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10856 // Friend operator== explicitly declared: no implicit operator==s.
10857 Spaceships.clear();
10858 return;
10859 }
10860
10861 if (FD->getOverloadedOperator() == OO_Spaceship &&
10863 Spaceships.push_back(FD);
10864 }
10865
10866 // Look for members named 'operator<=>'.
10868 for (NamedDecl *ND : RD->lookup(Cmp)) {
10869 // Note that we could find a non-function here (either a function template
10870 // or a using-declaration). Neither case results in an implicit
10871 // 'operator=='.
10872 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10873 if (FD->isExplicitlyDefaulted())
10874 Spaceships.push_back(FD);
10875 }
10876}
10877
10879 // Don't add implicit special members to templated classes.
10880 // FIXME: This means unqualified lookups for 'operator=' within a class
10881 // template don't work properly.
10882 if (!ClassDecl->isDependentType()) {
10883 if (ClassDecl->needsImplicitDefaultConstructor()) {
10884 ++getASTContext().NumImplicitDefaultConstructors;
10885
10886 if (ClassDecl->hasInheritedConstructor())
10888 }
10889
10890 if (ClassDecl->needsImplicitCopyConstructor()) {
10891 ++getASTContext().NumImplicitCopyConstructors;
10892
10893 // If the properties or semantics of the copy constructor couldn't be
10894 // determined while the class was being declared, force a declaration
10895 // of it now.
10897 ClassDecl->hasInheritedConstructor())
10899 // For the MS ABI we need to know whether the copy ctor is deleted. A
10900 // prerequisite for deleting the implicit copy ctor is that the class has
10901 // a move ctor or move assignment that is either user-declared or whose
10902 // semantics are inherited from a subobject. FIXME: We should provide a
10903 // more direct way for CodeGen to ask whether the constructor was deleted.
10904 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10905 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10907 ClassDecl->hasUserDeclaredMoveAssignment() ||
10910 }
10911
10912 if (getLangOpts().CPlusPlus11 &&
10913 ClassDecl->needsImplicitMoveConstructor()) {
10914 ++getASTContext().NumImplicitMoveConstructors;
10915
10917 ClassDecl->hasInheritedConstructor())
10919 }
10920
10921 if (ClassDecl->needsImplicitCopyAssignment()) {
10922 ++getASTContext().NumImplicitCopyAssignmentOperators;
10923
10924 // If we have a dynamic class, then the copy assignment operator may be
10925 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10926 // it shows up in the right place in the vtable and that we diagnose
10927 // problems with the implicit exception specification.
10928 if (ClassDecl->isDynamicClass() ||
10930 ClassDecl->hasInheritedAssignment())
10932 }
10933
10934 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10935 ++getASTContext().NumImplicitMoveAssignmentOperators;
10936
10937 // Likewise for the move assignment operator.
10938 if (ClassDecl->isDynamicClass() ||
10940 ClassDecl->hasInheritedAssignment())
10942 }
10943
10944 if (ClassDecl->needsImplicitDestructor()) {
10945 ++getASTContext().NumImplicitDestructors;
10946
10947 // If we have a dynamic class, then the destructor may be virtual, so we
10948 // have to declare the destructor immediately. This ensures that, e.g., it
10949 // shows up in the right place in the vtable and that we diagnose problems
10950 // with the implicit exception specification.
10951 if (ClassDecl->isDynamicClass() ||
10953 DeclareImplicitDestructor(ClassDecl);
10954 }
10955 }
10956
10957 // C++2a [class.compare.default]p3:
10958 // If the member-specification does not explicitly declare any member or
10959 // friend named operator==, an == operator function is declared implicitly
10960 // for each defaulted three-way comparison operator function defined in
10961 // the member-specification
10962 // FIXME: Consider doing this lazily.
10963 // We do this during the initial parse for a class template, not during
10964 // instantiation, so that we can handle unqualified lookups for 'operator=='
10965 // when parsing the template.
10967 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10969 DefaultedSpaceships);
10970 for (auto *FD : DefaultedSpaceships)
10971 DeclareImplicitEqualityComparison(ClassDecl, FD);
10972 }
10973}
10974
10975unsigned
10977 llvm::function_ref<Scope *()> EnterScope) {
10978 if (!D)
10979 return 0;
10981
10982 // In order to get name lookup right, reenter template scopes in order from
10983 // outermost to innermost.
10985 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10986
10987 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10988 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
10989 ParameterLists.push_back(TPL);
10990
10991 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10992 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10993 ParameterLists.push_back(FTD->getTemplateParameters());
10994 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10995 LookupDC = VD->getDeclContext();
10996
10998 ParameterLists.push_back(VTD->getTemplateParameters());
10999 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
11000 ParameterLists.push_back(PSD->getTemplateParameters());
11001 }
11002 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
11003 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11004 ParameterLists.push_back(TPL);
11005
11006 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
11008 ParameterLists.push_back(CTD->getTemplateParameters());
11009 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
11010 ParameterLists.push_back(PSD->getTemplateParameters());
11011 }
11012 }
11013 // FIXME: Alias declarations and concepts.
11014
11015 unsigned Count = 0;
11016 Scope *InnermostTemplateScope = nullptr;
11017 for (TemplateParameterList *Params : ParameterLists) {
11018 // Ignore explicit specializations; they don't contribute to the template
11019 // depth.
11020 if (Params->size() == 0)
11021 continue;
11022
11023 InnermostTemplateScope = EnterScope();
11024 for (NamedDecl *Param : *Params) {
11025 if (Param->getDeclName()) {
11026 InnermostTemplateScope->AddDecl(Param);
11027 IdResolver.AddDecl(Param);
11028 }
11029 }
11030 ++Count;
11031 }
11032
11033 // Associate the new template scopes with the corresponding entities.
11034 if (InnermostTemplateScope) {
11035 assert(LookupDC && "no enclosing DeclContext for template lookup");
11036 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
11037 }
11038
11039 return Count;
11040}
11041
11043 if (!RecordD) return;
11044 AdjustDeclIfTemplate(RecordD);
11047}
11048
11050 if (!RecordD) return;
11052}
11053
11055 if (!Param)
11056 return;
11057
11058 S->AddDecl(Param);
11059 if (Param->getDeclName())
11060 IdResolver.AddDecl(Param);
11061}
11062
11065
11066/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11067/// C++ method declaration. We're (re-)introducing the given
11068/// function parameter into scope for use in parsing later parts of
11069/// the method declaration. For example, we could see an
11070/// ActOnParamDefaultArgument event for this parameter.
11072 if (!ParamD)
11073 return;
11074
11075 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
11076
11077 S->AddDecl(Param);
11078 if (Param->getDeclName())
11079 IdResolver.AddDecl(Param);
11080}
11081
11083 if (!MethodD)
11084 return;
11085
11086 AdjustDeclIfTemplate(MethodD);
11087
11089
11090 // Now that we have our default arguments, check the constructor
11091 // again. It could produce additional diagnostics or affect whether
11092 // the class has implicitly-declared destructors, among other
11093 // things.
11094 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
11096
11097 // Check the default arguments, which we may have added.
11098 if (!Method->isInvalidDecl())
11100}
11101
11102// Emit the given diagnostic for each non-address-space qualifier.
11103// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11104static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11106 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11107 bool DiagOccurred = false;
11109 [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11110 SourceLocation SL) {
11111 // This diagnostic should be emitted on any qualifier except an addr
11112 // space qualifier. However, forEachQualifier currently doesn't visit
11113 // addr space qualifiers, so there's no way to write this condition
11114 // right now; we just diagnose on everything.
11115 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
11116 DiagOccurred = true;
11117 });
11118 if (DiagOccurred)
11119 D.setInvalidType();
11120 }
11121}
11122
11124 unsigned Kind) {
11125 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11126 return;
11127
11129 if (Chunk.Kind == DeclaratorChunk::Paren ||
11131 return;
11132
11133 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11134 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
11135 << Kind << Chunk.getSourceRange();
11136 D.setInvalidType();
11137}
11138
11140 StorageClass &SC) {
11141 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11142
11143 // C++ [class.ctor]p3:
11144 // A constructor shall not be virtual (10.3) or static (9.4). A
11145 // constructor can be invoked for a const, volatile or const
11146 // volatile object. A constructor shall not be declared const,
11147 // volatile, or const volatile (9.3.2).
11148 if (isVirtual) {
11149 if (!D.isInvalidType())
11150 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11151 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11153 D.setInvalidType();
11154 }
11155 if (SC == SC_Static) {
11156 if (!D.isInvalidType())
11157 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11158 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11160 D.setInvalidType();
11161 SC = SC_None;
11162 }
11163
11164 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11166 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11170 D.setInvalidType();
11171 }
11172
11173 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11174 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
11175
11176 // C++0x [class.ctor]p4:
11177 // A constructor shall not be declared with a ref-qualifier.
11179 if (FTI.hasRefQualifier()) {
11180 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11183 D.setInvalidType();
11184 }
11185
11186 // Rebuild the function type "R" without any type qualifiers (in
11187 // case any of the errors above fired) and with "void" as the
11188 // return type, since constructors don't have return types.
11189 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11190 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11191 return R;
11192
11194 EPI.TypeQuals = Qualifiers();
11195 EPI.RefQualifier = RQ_None;
11196
11197 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
11198}
11199
11201 CXXRecordDecl *ClassDecl
11202 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11203 if (!ClassDecl)
11204 return Constructor->setInvalidDecl();
11205
11206 // C++ [class.copy]p3:
11207 // A declaration of a constructor for a class X is ill-formed if
11208 // its first parameter is of type (optionally cv-qualified) X and
11209 // either there are no other parameters or else all other
11210 // parameters have default arguments.
11211 if (!Constructor->isInvalidDecl() &&
11212 Constructor->hasOneParamOrDefaultArgs() &&
11213 !Constructor->isFunctionTemplateSpecialization()) {
11214 CanQualType ParamType =
11215 Constructor->getParamDecl(0)->getType()->getCanonicalTypeUnqualified();
11216 CanQualType ClassTy = Context.getCanonicalTagType(ClassDecl);
11217 if (ParamType == ClassTy) {
11218 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11219 const char *ConstRef
11220 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11221 : " const &";
11222 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11223 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11224
11225 // FIXME: Rather that making the constructor invalid, we should endeavor
11226 // to fix the type.
11227 Constructor->setInvalidDecl();
11228 }
11229 }
11230}
11231
11233 CXXRecordDecl *RD = Destructor->getParent();
11234
11235 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11236 SourceLocation Loc;
11237
11238 if (!Destructor->isImplicit())
11239 Loc = Destructor->getLocation();
11240 else
11241 Loc = RD->getLocation();
11242
11243 DeclarationName Name =
11244 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
11245 // If we have a virtual destructor, look up the deallocation function
11247 Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11248 Expr *ThisArg = nullptr;
11249
11250 // If the notional 'delete this' expression requires a non-trivial
11251 // conversion from 'this' to the type of a destroying operator delete's
11252 // first parameter, perform that conversion now.
11253 if (OperatorDelete->isDestroyingOperatorDelete()) {
11254 unsigned AddressParamIndex = 0;
11255 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11256 ++AddressParamIndex;
11257 QualType ParamType =
11258 OperatorDelete->getParamDecl(AddressParamIndex)->getType();
11259 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11260 // C++ [class.dtor]p13:
11261 // ... as if for the expression 'delete this' appearing in a
11262 // non-virtual destructor of the destructor's class.
11263 ContextRAII SwitchContext(*this, Destructor);
11265 OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());
11266 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11267 This = PerformImplicitConversion(This.get(), ParamType,
11269 if (This.isInvalid()) {
11270 // FIXME: Register this as a context note so that it comes out
11271 // in the right order.
11272 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11273 return true;
11274 }
11275 ThisArg = This.get();
11276 }
11277 }
11278
11279 DiagnoseUseOfDecl(OperatorDelete, Loc);
11280 MarkFunctionReferenced(Loc, OperatorDelete);
11281 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11282
11283 if (isa<CXXMethodDecl>(OperatorDelete) &&
11284 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11285 Context.getLangOpts())) {
11286 // In Microsoft ABI whenever a class has a defined operator delete,
11287 // scalar deleting destructors check the 3rd bit of the implicit
11288 // parameter and if it is set, then, global operator delete must be
11289 // called instead of the class-specific one. Find and save the global
11290 // operator delete for that case. Do not diagnose at this point because
11291 // the lack of a global operator delete is not an error if there are no
11292 // delete calls that require it.
11293 FunctionDecl *GlobalOperatorDelete =
11294 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11295 /*LookForGlobal*/ true, Name);
11296 if (GlobalOperatorDelete) {
11297 MarkFunctionReferenced(Loc, GlobalOperatorDelete);
11298 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11299 }
11300 }
11301
11302 if (Context.getTargetInfo().emitVectorDeletingDtors(
11303 Context.getLangOpts())) {
11304 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11305 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11306 DeclarationName VDeleteName =
11307 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
11309 Loc, RD, /*Diagnose*/ false,
11310 /*LookForGlobal*/ false, VDeleteName);
11311 if (ArrOperatorDelete && isa<CXXMethodDecl>(ArrOperatorDelete)) {
11312 FunctionDecl *GlobalArrOperatorDelete =
11313 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11314 /*LookForGlobal*/ true,
11315 VDeleteName);
11316 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11317 if (GlobalArrOperatorDelete &&
11318 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11319 DestructorIsExported))
11320 MarkFunctionReferenced(Loc, GlobalArrOperatorDelete);
11321 } else if (!ArrOperatorDelete) {
11322 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11323 Loc, RD, /*Diagnose*/ false,
11324 /*LookForGlobal*/ true, VDeleteName);
11325 }
11326 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11327 if (ArrOperatorDelete &&
11328 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11329 DestructorIsExported))
11330 MarkFunctionReferenced(Loc, ArrOperatorDelete);
11331 }
11332 }
11333 }
11334
11335 return false;
11336}
11337
11339 StorageClass& SC) {
11340 // C++ [class.dtor]p1:
11341 // [...] A typedef-name that names a class is a class-name
11342 // (7.1.3); however, a typedef-name that names a class shall not
11343 // be used as the identifier in the declarator for a destructor
11344 // declaration.
11345 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11346 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11347 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11348 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11349 else if (const TemplateSpecializationType *TST =
11350 DeclaratorType->getAs<TemplateSpecializationType>())
11351 if (TST->isTypeAlias())
11352 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11353 << DeclaratorType << 1;
11354
11355 // C++ [class.dtor]p2:
11356 // A destructor is used to destroy objects of its class type. A
11357 // destructor takes no parameters, and no return type can be
11358 // specified for it (not even void). The address of a destructor
11359 // shall not be taken. A destructor shall not be static. A
11360 // destructor can be invoked for a const, volatile or const
11361 // volatile object. A destructor shall not be declared const,
11362 // volatile or const volatile (9.3.2).
11363 if (SC == SC_Static) {
11364 if (!D.isInvalidType())
11365 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11366 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11369
11370 SC = SC_None;
11371 }
11372 if (!D.isInvalidType()) {
11373 // Destructors don't have return types, but the parser will
11374 // happily parse something like:
11375 //
11376 // class X {
11377 // float ~X();
11378 // };
11379 //
11380 // The return type will be eliminated later.
11381 if (D.getDeclSpec().hasTypeSpecifier())
11382 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11385 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11386 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11392 D.setInvalidType();
11393 }
11394 }
11395
11396 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11397 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11398
11399 // C++0x [class.dtor]p2:
11400 // A destructor shall not be declared with a ref-qualifier.
11402 if (FTI.hasRefQualifier()) {
11403 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11406 D.setInvalidType();
11407 }
11408
11409 // Make sure we don't have any parameters.
11410 if (FTIHasNonVoidParameters(FTI)) {
11411 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11412
11413 // Delete the parameters.
11414 FTI.freeParams();
11415 D.setInvalidType();
11416 }
11417
11418 // Make sure the destructor isn't variadic.
11419 if (FTI.isVariadic) {
11420 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11421 D.setInvalidType();
11422 }
11423
11424 // Rebuild the function type "R" without any type qualifiers or
11425 // parameters (in case any of the errors above fired) and with
11426 // "void" as the return type, since destructors don't have return
11427 // types.
11428 if (!D.isInvalidType())
11429 return R;
11430
11431 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11433 EPI.Variadic = false;
11434 EPI.TypeQuals = Qualifiers();
11435 EPI.RefQualifier = RQ_None;
11436 return Context.getFunctionType(Context.VoidTy, {}, EPI);
11437}
11438
11439static void extendLeft(SourceRange &R, SourceRange Before) {
11440 if (Before.isInvalid())
11441 return;
11442 R.setBegin(Before.getBegin());
11443 if (R.getEnd().isInvalid())
11444 R.setEnd(Before.getEnd());
11445}
11446
11447static void extendRight(SourceRange &R, SourceRange After) {
11448 if (After.isInvalid())
11449 return;
11450 if (R.getBegin().isInvalid())
11451 R.setBegin(After.getBegin());
11452 R.setEnd(After.getEnd());
11453}
11454
11456 StorageClass& SC) {
11457 // C++ [class.conv.fct]p1:
11458 // Neither parameter types nor return type can be specified. The
11459 // type of a conversion function (8.3.5) is "function taking no
11460 // parameter returning conversion-type-id."
11461 if (SC == SC_Static) {
11462 if (!D.isInvalidType())
11463 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11465 << D.getName().getSourceRange();
11466 D.setInvalidType();
11467 SC = SC_None;
11468 }
11469
11470 TypeSourceInfo *ConvTSI = nullptr;
11471 QualType ConvType =
11473
11474 const DeclSpec &DS = D.getDeclSpec();
11475 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11476 // Conversion functions don't have return types, but the parser will
11477 // happily parse something like:
11478 //
11479 // class X {
11480 // float operator bool();
11481 // };
11482 //
11483 // The return type will be changed later anyway.
11484 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11487 D.setInvalidType();
11488 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11489 // It's also plausible that the user writes type qualifiers in the wrong
11490 // place, such as:
11491 // struct S { const operator int(); };
11492 // FIXME: we could provide a fixit to move the qualifiers onto the
11493 // conversion type.
11494 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11495 << SourceRange(D.getIdentifierLoc()) << 0;
11496 D.setInvalidType();
11497 }
11498 const auto *Proto = R->castAs<FunctionProtoType>();
11499 // Make sure we don't have any parameters.
11501 unsigned NumParam = Proto->getNumParams();
11502
11503 // [C++2b]
11504 // A conversion function shall have no non-object parameters.
11505 if (NumParam == 1) {
11507 if (const auto *First =
11508 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11509 First && First->isExplicitObjectParameter())
11510 NumParam--;
11511 }
11512
11513 if (NumParam != 0) {
11514 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11515 // Delete the parameters.
11516 FTI.freeParams();
11517 D.setInvalidType();
11518 } else if (Proto->isVariadic()) {
11519 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11520 D.setInvalidType();
11521 }
11522
11523 // Diagnose "&operator bool()" and other such nonsense. This
11524 // is actually a gcc extension which we don't support.
11525 if (Proto->getReturnType() != ConvType) {
11526 bool NeedsTypedef = false;
11527 SourceRange Before, After;
11528
11529 // Walk the chunks and extract information on them for our diagnostic.
11530 bool PastFunctionChunk = false;
11531 for (auto &Chunk : D.type_objects()) {
11532 switch (Chunk.Kind) {
11534 if (!PastFunctionChunk) {
11535 if (Chunk.Fun.HasTrailingReturnType) {
11536 TypeSourceInfo *TRT = nullptr;
11537 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11538 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11539 }
11540 PastFunctionChunk = true;
11541 break;
11542 }
11543 [[fallthrough]];
11545 NeedsTypedef = true;
11546 extendRight(After, Chunk.getSourceRange());
11547 break;
11548
11554 extendLeft(Before, Chunk.getSourceRange());
11555 break;
11556
11558 extendLeft(Before, Chunk.Loc);
11559 extendRight(After, Chunk.EndLoc);
11560 break;
11561 }
11562 }
11563
11564 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11565 After.isValid() ? After.getBegin() :
11566 D.getIdentifierLoc();
11567 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11568 DB << Before << After;
11569
11570 if (!NeedsTypedef) {
11571 DB << /*don't need a typedef*/0;
11572
11573 // If we can provide a correct fix-it hint, do so.
11574 if (After.isInvalid() && ConvTSI) {
11575 SourceLocation InsertLoc =
11577 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11579 InsertLoc, CharSourceRange::getTokenRange(Before))
11580 << FixItHint::CreateRemoval(Before);
11581 }
11582 } else if (!Proto->getReturnType()->isDependentType()) {
11583 DB << /*typedef*/1 << Proto->getReturnType();
11584 } else if (getLangOpts().CPlusPlus11) {
11585 DB << /*alias template*/2 << Proto->getReturnType();
11586 } else {
11587 DB << /*might not be fixable*/3;
11588 }
11589
11590 // Recover by incorporating the other type chunks into the result type.
11591 // Note, this does *not* change the name of the function. This is compatible
11592 // with the GCC extension:
11593 // struct S { &operator int(); } s;
11594 // int &r = s.operator int(); // ok in GCC
11595 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11596 ConvType = Proto->getReturnType();
11597 }
11598
11599 // C++ [class.conv.fct]p4:
11600 // The conversion-type-id shall not represent a function type nor
11601 // an array type.
11602 if (ConvType->isArrayType()) {
11603 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11604 ConvType = Context.getPointerType(ConvType);
11605 D.setInvalidType();
11606 } else if (ConvType->isFunctionType()) {
11607 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11608 ConvType = Context.getPointerType(ConvType);
11609 D.setInvalidType();
11610 }
11611
11612 // Rebuild the function type "R" without any parameters (in case any
11613 // of the errors above fired) and with the conversion type as the
11614 // return type.
11615 if (D.isInvalidType())
11616 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11617
11618 // C++0x explicit conversion operators.
11622 ? diag::warn_cxx98_compat_explicit_conversion_functions
11623 : diag::ext_explicit_conversion_functions)
11625}
11626
11628 assert(Conversion && "Expected to receive a conversion function declaration");
11629
11630 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11631
11632 // Make sure we aren't redeclaring the conversion function.
11633 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11634 // C++ [class.conv.fct]p1:
11635 // [...] A conversion function is never used to convert a
11636 // (possibly cv-qualified) object to the (possibly cv-qualified)
11637 // same object type (or a reference to it), to a (possibly
11638 // cv-qualified) base class of that type (or a reference to it),
11639 // or to (possibly cv-qualified) void.
11640 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
11641 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11642 ConvType = ConvTypeRef->getPointeeType();
11643 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11645 /* Suppress diagnostics for instantiations. */;
11646 else if (Conversion->size_overridden_methods() != 0)
11647 /* Suppress diagnostics for overriding virtual function in a base class. */;
11648 else if (ConvType->isRecordType()) {
11649 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11650 if (ConvType == ClassType)
11651 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11652 << ClassType;
11653 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11654 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11655 << ClassType << ConvType;
11656 } else if (ConvType->isVoidType()) {
11657 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11658 << ClassType << ConvType;
11659 }
11660
11661 if (FunctionTemplateDecl *ConversionTemplate =
11662 Conversion->getDescribedFunctionTemplate()) {
11663 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11664 ConvType = ConvTypePtr->getPointeeType();
11665 }
11666 if (ConvType->isUndeducedAutoType()) {
11667 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11668 << getReturnTypeLoc(Conversion).getSourceRange()
11669 << ConvType->castAs<AutoType>()->getKeyword()
11670 << /* in declaration of conversion function template= */ 24;
11671 }
11672
11673 return ConversionTemplate;
11674 }
11675
11676 return Conversion;
11677}
11678
11683
11687
11689 DeclarationName Name, QualType R,
11690 bool IsLambda, DeclContext *DC) {
11691 if (!D.isFunctionDeclarator())
11692 return;
11693
11695 if (FTI.NumParams == 0)
11696 return;
11697 ParmVarDecl *ExplicitObjectParam = nullptr;
11698 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11699 const auto &ParamInfo = FTI.Params[Idx];
11700 if (!ParamInfo.Param)
11701 continue;
11702 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11703 if (!Param->isExplicitObjectParameter())
11704 continue;
11705 if (Idx == 0) {
11706 ExplicitObjectParam = Param;
11707 continue;
11708 } else {
11709 Diag(Param->getLocation(),
11710 diag::err_explicit_object_parameter_must_be_first)
11711 << IsLambda << Param->getSourceRange();
11712 }
11713 }
11714 if (!ExplicitObjectParam)
11715 return;
11716
11717 if (ExplicitObjectParam->hasDefaultArg()) {
11718 Diag(ExplicitObjectParam->getLocation(),
11719 diag::err_explicit_object_default_arg)
11720 << ExplicitObjectParam->getSourceRange();
11721 D.setInvalidType();
11722 }
11723
11726 D.isStaticMember())) {
11727 Diag(ExplicitObjectParam->getBeginLoc(),
11728 diag::err_explicit_object_parameter_nonmember)
11729 << D.getSourceRange() << /*static=*/0 << IsLambda;
11730 D.setInvalidType();
11731 }
11732
11733 if (D.getDeclSpec().isVirtualSpecified()) {
11734 Diag(ExplicitObjectParam->getBeginLoc(),
11735 diag::err_explicit_object_parameter_nonmember)
11736 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11737 D.setInvalidType();
11738 }
11739
11740 // Friend declarations require some care. Consider:
11741 //
11742 // namespace N {
11743 // struct A{};
11744 // int f(A);
11745 // }
11746 //
11747 // struct S {
11748 // struct T {
11749 // int f(this T);
11750 // };
11751 //
11752 // friend int T::f(this T); // Allow this.
11753 // friend int f(this S); // But disallow this.
11754 // friend int N::f(this A); // And disallow this.
11755 // };
11756 //
11757 // Here, it seems to suffice to check whether the scope
11758 // specifier designates a class type.
11759 if (D.getDeclSpec().isFriendSpecified() &&
11760 !isa_and_present<CXXRecordDecl>(
11762 Diag(ExplicitObjectParam->getBeginLoc(),
11763 diag::err_explicit_object_parameter_nonmember)
11764 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11765 D.setInvalidType();
11766 }
11767
11768 if (IsLambda && FTI.hasMutableQualifier()) {
11769 Diag(ExplicitObjectParam->getBeginLoc(),
11770 diag::err_explicit_object_parameter_mutable)
11771 << D.getSourceRange();
11772 }
11773
11774 if (IsLambda)
11775 return;
11776
11777 if (!DC || !DC->isRecord()) {
11778 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11779 "should have been diagnosed already");
11780 return;
11781 }
11782
11783 // CWG2674: constructors and destructors cannot have explicit parameters.
11786 Diag(ExplicitObjectParam->getBeginLoc(),
11787 diag::err_explicit_object_parameter_constructor)
11789 << D.getSourceRange();
11790 D.setInvalidType();
11791 }
11792}
11793
11794namespace {
11795/// Utility class to accumulate and print a diagnostic listing the invalid
11796/// specifier(s) on a declaration.
11797struct BadSpecifierDiagnoser {
11798 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11799 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11800 ~BadSpecifierDiagnoser() {
11801 Diagnostic << Specifiers;
11802 }
11803
11804 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11805 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11806 }
11807 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11808 return check(SpecLoc,
11810 }
11811 void check(SourceLocation SpecLoc, const char *Spec) {
11812 if (SpecLoc.isInvalid()) return;
11813 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11814 if (!Specifiers.empty()) Specifiers += " ";
11815 Specifiers += Spec;
11816 }
11817
11818 Sema &S;
11819 Sema::SemaDiagnosticBuilder Diagnostic;
11820 std::string Specifiers;
11821};
11822}
11823
11825 StorageClass &SC) {
11826 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11827 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11828 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11829
11830 // C++ [temp.deduct.guide]p3:
11831 // A deduction-gide shall be declared in the same scope as the
11832 // corresponding class template.
11833 if (!CurContext->getRedeclContext()->Equals(
11834 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11835 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11836 << GuidedTemplateDecl;
11837 NoteTemplateLocation(*GuidedTemplateDecl);
11838 }
11839
11840 auto &DS = D.getMutableDeclSpec();
11841 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11842 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11843 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11844 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11845 BadSpecifierDiagnoser Diagnoser(
11846 *this, D.getIdentifierLoc(),
11847 diag::err_deduction_guide_invalid_specifier);
11848
11849 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11850 DS.ClearStorageClassSpecs();
11851 SC = SC_None;
11852
11853 // 'explicit' is permitted.
11854 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11855 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11856 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11857 DS.ClearConstexprSpec();
11858
11859 Diagnoser.check(DS.getConstSpecLoc(), "const");
11860 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11861 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11862 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11863 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11864 DS.ClearTypeQualifiers();
11865
11866 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11867 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11868 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11869 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11870 DS.ClearTypeSpecType();
11871 }
11872
11873 if (D.isInvalidType())
11874 return true;
11875
11876 // Check the declarator is simple enough.
11877 bool FoundFunction = false;
11878 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11879 if (Chunk.Kind == DeclaratorChunk::Paren)
11880 continue;
11881 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11883 diag::err_deduction_guide_with_complex_decl)
11884 << D.getSourceRange();
11885 break;
11886 }
11887 if (!Chunk.Fun.hasTrailingReturnType())
11888 return Diag(D.getName().getBeginLoc(),
11889 diag::err_deduction_guide_no_trailing_return_type);
11890
11891 // Check that the return type is written as a specialization of
11892 // the template specified as the deduction-guide's name.
11893 // The template name may not be qualified. [temp.deduct.guide]
11894 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11895 TypeSourceInfo *TSI = nullptr;
11896 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11897 assert(TSI && "deduction guide has valid type but invalid return type?");
11898 bool AcceptableReturnType = false;
11899 bool MightInstantiateToSpecialization = false;
11900 if (auto RetTST =
11902 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11903 bool TemplateMatches = Context.hasSameTemplateName(
11904 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11905
11907 SpecifiedName.getAsQualifiedTemplateName();
11908 assert(Qualifiers && "expected QualifiedTemplate");
11909 bool SimplyWritten =
11910 !Qualifiers->hasTemplateKeyword() && !Qualifiers->getQualifier();
11911 if (SimplyWritten && TemplateMatches)
11912 AcceptableReturnType = true;
11913 else {
11914 // This could still instantiate to the right type, unless we know it
11915 // names the wrong class template.
11916 auto *TD = SpecifiedName.getAsTemplateDecl();
11917 MightInstantiateToSpecialization =
11918 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11919 }
11920 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11921 MightInstantiateToSpecialization = true;
11922 }
11923
11924 if (!AcceptableReturnType)
11925 return Diag(TSI->getTypeLoc().getBeginLoc(),
11926 diag::err_deduction_guide_bad_trailing_return_type)
11927 << GuidedTemplate << TSI->getType()
11928 << MightInstantiateToSpecialization
11929 << TSI->getTypeLoc().getSourceRange();
11930
11931 // Keep going to check that we don't have any inner declarator pieces (we
11932 // could still have a function returning a pointer to a function).
11933 FoundFunction = true;
11934 }
11935
11936 if (D.isFunctionDefinition())
11937 // we can still create a valid deduction guide here.
11938 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11939 return false;
11940}
11941
11942//===----------------------------------------------------------------------===//
11943// Namespace Handling
11944//===----------------------------------------------------------------------===//
11945
11946/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11947/// reopened.
11949 SourceLocation Loc,
11950 IdentifierInfo *II, bool *IsInline,
11951 NamespaceDecl *PrevNS) {
11952 assert(*IsInline != PrevNS->isInline());
11953
11954 // 'inline' must appear on the original definition, but not necessarily
11955 // on all extension definitions, so the note should point to the first
11956 // definition to avoid confusion.
11957 PrevNS = PrevNS->getFirstDecl();
11958
11959 if (PrevNS->isInline())
11960 // The user probably just forgot the 'inline', so suggest that it
11961 // be added back.
11962 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11963 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11964 else
11965 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11966
11967 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11968 *IsInline = PrevNS->isInline();
11969}
11970
11971/// ActOnStartNamespaceDef - This is called at the start of a namespace
11972/// definition.
11974 SourceLocation InlineLoc,
11975 SourceLocation NamespaceLoc,
11976 SourceLocation IdentLoc, IdentifierInfo *II,
11977 SourceLocation LBrace,
11978 const ParsedAttributesView &AttrList,
11979 UsingDirectiveDecl *&UD, bool IsNested) {
11980 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11981 // For anonymous namespace, take the location of the left brace.
11982 SourceLocation Loc = II ? IdentLoc : LBrace;
11983 bool IsInline = InlineLoc.isValid();
11984 bool IsInvalid = false;
11985 bool IsStd = false;
11986 bool AddToKnown = false;
11987 Scope *DeclRegionScope = NamespcScope->getParent();
11988
11989 NamespaceDecl *PrevNS = nullptr;
11990 if (II) {
11991 // C++ [namespace.std]p7:
11992 // A translation unit shall not declare namespace std to be an inline
11993 // namespace (9.8.2).
11994 //
11995 // Precondition: the std namespace is in the file scope and is declared to
11996 // be inline
11997 auto DiagnoseInlineStdNS = [&]() {
11998 assert(IsInline && II->isStr("std") &&
11999 CurContext->getRedeclContext()->isTranslationUnit() &&
12000 "Precondition of DiagnoseInlineStdNS not met");
12001 Diag(InlineLoc, diag::err_inline_namespace_std)
12002 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
12003 IsInline = false;
12004 };
12005 // C++ [namespace.def]p2:
12006 // The identifier in an original-namespace-definition shall not
12007 // have been previously defined in the declarative region in
12008 // which the original-namespace-definition appears. The
12009 // identifier in an original-namespace-definition is the name of
12010 // the namespace. Subsequently in that declarative region, it is
12011 // treated as an original-namespace-name.
12012 //
12013 // Since namespace names are unique in their scope, and we don't
12014 // look through using directives, just look for any ordinary names
12015 // as if by qualified name lookup.
12016 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12018 LookupQualifiedName(R, CurContext->getRedeclContext());
12019 NamedDecl *PrevDecl =
12020 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12021 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
12022
12023 if (PrevNS) {
12024 // This is an extended namespace definition.
12025 if (IsInline && II->isStr("std") &&
12026 CurContext->getRedeclContext()->isTranslationUnit())
12027 DiagnoseInlineStdNS();
12028 else if (IsInline != PrevNS->isInline())
12029 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
12030 &IsInline, PrevNS);
12031 } else if (PrevDecl) {
12032 // This is an invalid name redefinition.
12033 Diag(Loc, diag::err_redefinition_different_kind)
12034 << II;
12035 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12036 IsInvalid = true;
12037 // Continue on to push Namespc as current DeclContext and return it.
12038 } else if (II->isStr("std") &&
12039 CurContext->getRedeclContext()->isTranslationUnit()) {
12040 if (IsInline)
12041 DiagnoseInlineStdNS();
12042 // This is the first "real" definition of the namespace "std", so update
12043 // our cache of the "std" namespace to point at this definition.
12044 PrevNS = getStdNamespace();
12045 IsStd = true;
12046 AddToKnown = !IsInline;
12047 } else {
12048 // We've seen this namespace for the first time.
12049 AddToKnown = !IsInline;
12050 }
12051 } else {
12052 // Anonymous namespaces.
12053
12054 // Determine whether the parent already has an anonymous namespace.
12055 DeclContext *Parent = CurContext->getRedeclContext();
12056 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12057 PrevNS = TU->getAnonymousNamespace();
12058 } else {
12059 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
12060 PrevNS = ND->getAnonymousNamespace();
12061 }
12062
12063 if (PrevNS && IsInline != PrevNS->isInline())
12064 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
12065 &IsInline, PrevNS);
12066 }
12067
12069 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
12070 if (IsInvalid)
12071 Namespc->setInvalidDecl();
12072
12073 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
12074 AddPragmaAttributes(DeclRegionScope, Namespc);
12075 ProcessAPINotes(Namespc);
12076
12077 // FIXME: Should we be merging attributes?
12078 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12080
12081 if (IsStd)
12082 StdNamespace = Namespc;
12083 if (AddToKnown)
12084 KnownNamespaces[Namespc] = false;
12085
12086 if (II) {
12087 PushOnScopeChains(Namespc, DeclRegionScope);
12088 } else {
12089 // Link the anonymous namespace into its parent.
12090 DeclContext *Parent = CurContext->getRedeclContext();
12091 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12092 TU->setAnonymousNamespace(Namespc);
12093 } else {
12094 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
12095 }
12096
12097 CurContext->addDecl(Namespc);
12098
12099 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12100 // behaves as if it were replaced by
12101 // namespace unique { /* empty body */ }
12102 // using namespace unique;
12103 // namespace unique { namespace-body }
12104 // where all occurrences of 'unique' in a translation unit are
12105 // replaced by the same identifier and this identifier differs
12106 // from all other identifiers in the entire program.
12107
12108 // We just create the namespace with an empty name and then add an
12109 // implicit using declaration, just like the standard suggests.
12110 //
12111 // CodeGen enforces the "universally unique" aspect by giving all
12112 // declarations semantically contained within an anonymous
12113 // namespace internal linkage.
12114
12115 if (!PrevNS) {
12117 /* 'using' */ LBrace,
12118 /* 'namespace' */ SourceLocation(),
12119 /* qualifier */ NestedNameSpecifierLoc(),
12120 /* identifier */ SourceLocation(),
12121 Namespc,
12122 /* Ancestor */ Parent);
12123 UD->setImplicit();
12124 Parent->addDecl(UD);
12125 }
12126 }
12127
12128 ActOnDocumentableDecl(Namespc);
12129
12130 // Although we could have an invalid decl (i.e. the namespace name is a
12131 // redefinition), push it as current DeclContext and try to continue parsing.
12132 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12133 // for the namespace has the declarations that showed up in that particular
12134 // namespace definition.
12135 PushDeclContext(NamespcScope, Namespc);
12136 return Namespc;
12137}
12138
12139/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12140/// is a namespace alias, returns the namespace it points to.
12142 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
12143 return AD->getNamespace();
12144 return dyn_cast_or_null<NamespaceDecl>(D);
12145}
12146
12148 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
12149 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12150 Namespc->setRBraceLoc(RBrace);
12152 if (Namespc->hasAttr<VisibilityAttr>())
12153 PopPragmaVisibility(true, RBrace);
12154 // If this namespace contains an export-declaration, export it now.
12155 if (DeferredExportedNamespaces.erase(Namespc))
12157}
12158
12160 return cast_or_null<CXXRecordDecl>(
12161 StdBadAlloc.get(Context.getExternalSource()));
12162}
12163
12165 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
12166}
12167
12169 return cast_or_null<NamespaceDecl>(
12170 StdNamespace.get(Context.getExternalSource()));
12171}
12172
12173namespace {
12174
12175enum UnsupportedSTLSelect {
12176 USS_InvalidMember,
12177 USS_MissingMember,
12178 USS_NonTrivial,
12179 USS_Other
12180};
12181
12182struct InvalidSTLDiagnoser {
12183 Sema &S;
12184 SourceLocation Loc;
12185 QualType TyForDiags;
12186
12187 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12188 const VarDecl *VD = nullptr) {
12189 {
12190 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
12191 << TyForDiags << ((int)Sel);
12192 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12193 assert(!Name.empty());
12194 D << Name;
12195 }
12196 }
12197 if (Sel == USS_InvalidMember) {
12198 S.Diag(VD->getLocation(), diag::note_var_declared_here)
12199 << VD << VD->getSourceRange();
12200 }
12201 return QualType();
12202 }
12203};
12204} // namespace
12205
12207 SourceLocation Loc,
12209 assert(getLangOpts().CPlusPlus &&
12210 "Looking for comparison category type outside of C++.");
12211
12212 // Use an elaborated type for diagnostics which has a name containing the
12213 // prepended 'std' namespace but not any inline namespace names.
12214 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12216 /*Prefix=*/std::nullopt);
12217 return Context.getTagType(ElaboratedTypeKeyword::None, Qualifier,
12218 Info->Record,
12219 /*OwnsTag=*/false);
12220 };
12221
12222 // Check if we've already successfully checked the comparison category type
12223 // before. If so, skip checking it again.
12224 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12225 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12226 // The only thing we need to check is that the type has a reachable
12227 // definition in the current context.
12228 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12229 return QualType();
12230
12231 return Info->getType();
12232 }
12233
12234 // If lookup failed
12235 if (!Info) {
12236 std::string NameForDiags = "std::";
12237 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12238 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12239 << NameForDiags << (int)Usage;
12240 return QualType();
12241 }
12242
12243 assert(Info->Kind == Kind);
12244 assert(Info->Record);
12245
12246 // Update the Record decl in case we encountered a forward declaration on our
12247 // first pass. FIXME: This is a bit of a hack.
12248 if (Info->Record->hasDefinition())
12249 Info->Record = Info->Record->getDefinition();
12250
12251 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12252 return QualType();
12253
12254 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12255
12256 if (!Info->Record->isTriviallyCopyable())
12257 return UnsupportedSTLError(USS_NonTrivial);
12258
12259 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12260 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12261 // Tolerate empty base classes.
12262 if (Base->isEmpty())
12263 continue;
12264 // Reject STL implementations which have at least one non-empty base.
12265 return UnsupportedSTLError();
12266 }
12267
12268 // Check that the STL has implemented the types using a single integer field.
12269 // This expectation allows better codegen for builtin operators. We require:
12270 // (1) The class has exactly one field.
12271 // (2) The field is an integral or enumeration type.
12272 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12273 if (std::distance(FIt, FEnd) != 1 ||
12274 !FIt->getType()->isIntegralOrEnumerationType()) {
12275 return UnsupportedSTLError();
12276 }
12277
12278 // Build each of the require values and store them in Info.
12279 for (ComparisonCategoryResult CCR :
12281 StringRef MemName = ComparisonCategories::getResultString(CCR);
12282 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12283
12284 if (!ValInfo)
12285 return UnsupportedSTLError(USS_MissingMember, MemName);
12286
12287 VarDecl *VD = ValInfo->VD;
12288 assert(VD && "should not be null!");
12289
12290 // Attempt to diagnose reasons why the STL definition of this type
12291 // might be foobar, including it failing to be a constant expression.
12292 // TODO Handle more ways the lookup or result can be invalid.
12293 if (!VD->isStaticDataMember() ||
12295 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12296
12297 // Attempt to evaluate the var decl as a constant expression and extract
12298 // the value of its first field as a ICE. If this fails, the STL
12299 // implementation is not supported.
12300 if (!ValInfo->hasValidIntValue())
12301 return UnsupportedSTLError();
12302
12303 MarkVariableReferenced(Loc, VD);
12304 }
12305
12306 // We've successfully built the required types and expressions. Update
12307 // the cache and return the newly cached value.
12308 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12309 return Info->getType();
12310}
12311
12313 if (!StdNamespace) {
12314 // The "std" namespace has not yet been defined, so build one implicitly.
12316 Context, Context.getTranslationUnitDecl(),
12317 /*Inline=*/false, SourceLocation(), SourceLocation(),
12318 &PP.getIdentifierTable().get("std"),
12319 /*PrevDecl=*/nullptr, /*Nested=*/false);
12320 getStdNamespace()->setImplicit(true);
12321 // We want the created NamespaceDecl to be available for redeclaration
12322 // lookups, but not for regular name lookups.
12323 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12324 getStdNamespace()->clearIdentifierNamespace();
12325 }
12326
12327 return getStdNamespace();
12328}
12329
12330static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12331 const char *ClassName,
12332 ClassTemplateDecl **CachedDecl,
12333 const Decl **MalformedDecl) {
12334 // We're looking for implicit instantiations of
12335 // template <typename U> class std::{ClassName}.
12336
12337 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12338 // it.
12339 return false;
12340
12341 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12342 if (!MalformedDecl)
12343 return;
12344 if (!D)
12345 D = SugaredType->getAsTagDecl();
12346 if (!D || !D->isInStdNamespace())
12347 return;
12348 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12349 if (II && II == &S.PP.getIdentifierTable().get(ClassName))
12350 *MalformedDecl = D;
12351 };
12352
12353 ClassTemplateDecl *Template = nullptr;
12355 if (const TemplateSpecializationType *TST =
12357 Template = dyn_cast_or_null<ClassTemplateDecl>(
12358 TST->getTemplateName().getAsTemplateDecl());
12359 Arguments = TST->template_arguments();
12360 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12361 Template = TT->getTemplateDecl();
12362 Arguments = TT->getTemplateArgs(S.Context);
12363 }
12364
12365 if (!Template) {
12366 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12367 return false;
12368 }
12369
12370 if (!*CachedDecl) {
12371 // Haven't recognized std::{ClassName} yet, maybe this is it.
12372 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12373 // semantics of this are slightly different, most notably the existing
12374 // "lookup" semantics explicitly diagnose an invalid definition as an
12375 // error.
12376 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12377 if (TemplateClass->getIdentifier() !=
12378 &S.PP.getIdentifierTable().get(ClassName) ||
12380 TemplateClass->getNonTransparentDeclContext()))
12381 return false;
12382 // This is a template called std::{ClassName}, but is it the right
12383 // template?
12384 TemplateParameterList *Params = Template->getTemplateParameters();
12385 if (Params->getMinRequiredArguments() != 1 ||
12386 !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||
12387 Params->getParam(0)->isTemplateParameterPack()) {
12388 if (MalformedDecl)
12389 *MalformedDecl = TemplateClass;
12390 return false;
12391 }
12392
12393 // It's the right template.
12394 *CachedDecl = Template;
12395 }
12396
12397 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12398 return false;
12399
12400 // This is an instance of std::{ClassName}. Find the argument type.
12401 if (TypeArg) {
12402 QualType ArgType = Arguments[0].getAsType();
12403 // FIXME: Since TST only has as-written arguments, we have to perform the
12404 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12405 // - If an explicitly-specified template argument type is a lifetime type
12406 // with no lifetime qualifier, the __strong lifetime qualifier is
12407 // inferred.
12408 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12409 !ArgType.getObjCLifetime()) {
12410 Qualifiers Qs;
12412 ArgType = S.Context.getQualifiedType(ArgType, Qs);
12413 }
12414 *TypeArg = ArgType;
12415 }
12416
12417 return true;
12418}
12419
12421 assert(getLangOpts().CPlusPlus &&
12422 "Looking for std::initializer_list outside of C++.");
12423
12424 // We're looking for implicit instantiations of
12425 // template <typename E> class std::initializer_list.
12426
12427 return isStdClassTemplate(*this, Ty, Element, "initializer_list",
12428 &StdInitializerList, /*MalformedDecl=*/nullptr);
12429}
12430
12432 const Decl **MalformedDecl) {
12433 assert(getLangOpts().CPlusPlus &&
12434 "Looking for std::type_identity outside of C++.");
12435
12436 // We're looking for implicit instantiations of
12437 // template <typename T> struct std::type_identity.
12438
12439 return isStdClassTemplate(*this, Ty, Element, "type_identity",
12440 &StdTypeIdentity, MalformedDecl);
12441}
12442
12444 const char *ClassName,
12445 bool *WasMalformed) {
12446 if (!S.StdNamespace)
12447 return nullptr;
12448
12449 LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,
12452 return nullptr;
12453
12455 if (!Template) {
12456 Result.suppressDiagnostics();
12457 // We found something weird. Complain about the first thing we found.
12458 NamedDecl *Found = *Result.begin();
12459 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
12460 << ClassName;
12461 if (WasMalformed)
12462 *WasMalformed = true;
12463 return nullptr;
12464 }
12465
12466 // We found some template with the correct name. Now verify that it's
12467 // correct.
12468 TemplateParameterList *Params = Template->getTemplateParameters();
12469 if (Params->getMinRequiredArguments() != 1 ||
12470 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12471 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
12472 << ClassName;
12473 if (WasMalformed)
12474 *WasMalformed = true;
12475 return nullptr;
12476 }
12477
12478 return Template;
12479}
12480
12482 QualType TypeParam, SourceLocation Loc) {
12483 assert(S.getStdNamespace());
12484 TemplateArgumentListInfo Args(Loc, Loc);
12485 auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);
12486 Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12487
12489 Loc, Args, /*Scope=*/nullptr,
12490 /*ForNestedNameSpecifier=*/false);
12491}
12492
12494 if (!StdInitializerList) {
12495 bool WasMalformed = false;
12497 LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);
12498 if (!StdInitializerList) {
12499 if (!WasMalformed)
12500 Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12501 return QualType();
12502 }
12503 }
12504 return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);
12505}
12506
12508 if (!StdTypeIdentity) {
12509 StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",
12510 /*WasMalformed=*/nullptr);
12511 if (!StdTypeIdentity)
12512 return QualType();
12513 }
12514 return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);
12515}
12516
12518 // C++ [dcl.init.list]p2:
12519 // A constructor is an initializer-list constructor if its first parameter
12520 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12521 // std::initializer_list<E> for some type E, and either there are no other
12522 // parameters or else all other parameters have default arguments.
12523 if (!Ctor->hasOneParamOrDefaultArgs())
12524 return false;
12525
12526 QualType ArgType = Ctor->getParamDecl(0)->getType();
12527 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12528 ArgType = RT->getPointeeType().getUnqualifiedType();
12529
12530 return isStdInitializerList(ArgType, nullptr);
12531}
12532
12533/// Determine whether a using statement is in a context where it will be
12534/// apply in all contexts.
12536 switch (CurContext->getDeclKind()) {
12537 case Decl::TranslationUnit:
12538 return true;
12539 case Decl::LinkageSpec:
12540 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12541 default:
12542 return false;
12543 }
12544}
12545
12546namespace {
12547
12548// Callback to only accept typo corrections that are namespaces.
12549class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12550public:
12551 bool ValidateCandidate(const TypoCorrection &candidate) override {
12552 if (NamedDecl *ND = candidate.getCorrectionDecl())
12554 return false;
12555 }
12556
12557 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12558 return std::make_unique<NamespaceValidatorCCC>(*this);
12559 }
12560};
12561
12562}
12563
12564static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12565 Sema &S) {
12566 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12567 Module *M = ND->getOwningModule();
12568 assert(M && "hidden namespace definition not in a module?");
12569
12570 if (M->isExplicitGlobalModule())
12571 S.Diag(Corrected.getCorrectionRange().getBegin(),
12572 diag::err_module_unimported_use_header)
12574 << /*Header Name*/ false;
12575 else
12576 S.Diag(Corrected.getCorrectionRange().getBegin(),
12577 diag::err_module_unimported_use)
12579 << M->getTopLevelModuleName();
12580}
12581
12583 CXXScopeSpec &SS,
12584 SourceLocation IdentLoc,
12585 IdentifierInfo *Ident) {
12586 R.clear();
12587 NamespaceValidatorCCC CCC{};
12588 if (TypoCorrection Corrected =
12589 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12591 // Generally we find it is confusing more than helpful to diagnose the
12592 // invisible namespace.
12593 // See https://github.com/llvm/llvm-project/issues/73893.
12594 //
12595 // However, we should diagnose when the users are trying to using an
12596 // invisible namespace. So we handle the case specially here.
12597 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12598 Corrected.requiresImport()) {
12599 DiagnoseInvisibleNamespace(Corrected, S);
12600 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12601 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12602 bool DroppedSpecifier =
12603 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12604 S.diagnoseTypo(Corrected,
12605 S.PDiag(diag::err_using_directive_member_suggest)
12606 << Ident << DC << DroppedSpecifier << SS.getRange(),
12607 S.PDiag(diag::note_namespace_defined_here));
12608 } else {
12609 S.diagnoseTypo(Corrected,
12610 S.PDiag(diag::err_using_directive_suggest) << Ident,
12611 S.PDiag(diag::note_namespace_defined_here));
12612 }
12613 R.addDecl(Corrected.getFoundDecl());
12614 return true;
12615 }
12616 return false;
12617}
12618
12620 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12621 SourceLocation IdentLoc,
12622 IdentifierInfo *NamespcName,
12623 const ParsedAttributesView &AttrList) {
12624 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12625 assert(NamespcName && "Invalid NamespcName.");
12626 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12627
12628 // Get the innermost enclosing declaration scope.
12629 S = S->getDeclParent();
12630
12631 UsingDirectiveDecl *UDir = nullptr;
12632 NestedNameSpecifier Qualifier = SS.getScopeRep();
12633
12634 // Lookup namespace name.
12635 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12636 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12637 if (R.isAmbiguous())
12638 return nullptr;
12639
12640 if (R.empty()) {
12641 R.clear();
12642 // Allow "using namespace std;" or "using namespace ::std;" even if
12643 // "std" hasn't been defined yet, for GCC compatibility.
12644 if ((!Qualifier ||
12645 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12646 NamespcName->isStr("std")) {
12647 Diag(IdentLoc, diag::ext_using_undefined_std);
12648 R.addDecl(getOrCreateStdNamespace());
12649 R.resolveKind();
12650 }
12651 // Otherwise, attempt typo correction.
12652 else
12653 TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12654 }
12655
12656 if (!R.empty()) {
12657 NamedDecl *Named = R.getRepresentativeDecl();
12658 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12659 assert(NS && "expected namespace decl");
12660
12661 // The use of a nested name specifier may trigger deprecation warnings.
12662 DiagnoseUseOfDecl(Named, IdentLoc);
12663
12664 // C++ [namespace.udir]p1:
12665 // A using-directive specifies that the names in the nominated
12666 // namespace can be used in the scope in which the
12667 // using-directive appears after the using-directive. During
12668 // unqualified name lookup (3.4.1), the names appear as if they
12669 // were declared in the nearest enclosing namespace which
12670 // contains both the using-directive and the nominated
12671 // namespace. [Note: in this context, "contains" means "contains
12672 // directly or indirectly". ]
12673
12674 // Find enclosing context containing both using-directive and
12675 // nominated namespace.
12676 DeclContext *CommonAncestor = NS;
12677 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12678 CommonAncestor = CommonAncestor->getParent();
12679
12680 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12682 IdentLoc, Named, CommonAncestor);
12683
12685 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12686 Diag(IdentLoc, diag::warn_using_directive_in_header);
12687 }
12688
12689 PushUsingDirective(S, UDir);
12690 } else {
12691 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12692 }
12693
12694 if (UDir) {
12695 ProcessDeclAttributeList(S, UDir, AttrList);
12696 ProcessAPINotes(UDir);
12697 }
12698
12699 return UDir;
12700}
12701
12703 // If the scope has an associated entity and the using directive is at
12704 // namespace or translation unit scope, add the UsingDirectiveDecl into
12705 // its lookup structure so qualified name lookup can find it.
12706 DeclContext *Ctx = S->getEntity();
12707 if (Ctx && !Ctx->isFunctionOrMethod())
12708 Ctx->addDecl(UDir);
12709 else
12710 // Otherwise, it is at block scope. The using-directives will affect lookup
12711 // only to the end of the scope.
12712 S->PushUsingDirective(UDir);
12713}
12714
12716 SourceLocation UsingLoc,
12717 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12718 UnqualifiedId &Name,
12719 SourceLocation EllipsisLoc,
12720 const ParsedAttributesView &AttrList) {
12721 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12722
12723 if (SS.isEmpty()) {
12724 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12725 return nullptr;
12726 }
12727
12728 switch (Name.getKind()) {
12734 break;
12735
12738 // C++11 inheriting constructors.
12739 Diag(Name.getBeginLoc(),
12741 ? diag::warn_cxx98_compat_using_decl_constructor
12742 : diag::err_using_decl_constructor)
12743 << SS.getRange();
12744
12745 if (getLangOpts().CPlusPlus11) break;
12746
12747 return nullptr;
12748
12750 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12751 return nullptr;
12752
12754 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12756 return nullptr;
12757
12759 llvm_unreachable("cannot parse qualified deduction guide name");
12760 }
12761
12762 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12763 DeclarationName TargetName = TargetNameInfo.getName();
12764 if (!TargetName)
12765 return nullptr;
12766
12767 // Warn about access declarations.
12768 if (UsingLoc.isInvalid()) {
12770 ? diag::err_access_decl
12771 : diag::warn_access_decl_deprecated)
12772 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12773 }
12774
12775 if (EllipsisLoc.isInvalid()) {
12778 return nullptr;
12779 } else {
12781 !TargetNameInfo.containsUnexpandedParameterPack()) {
12782 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12783 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12784 EllipsisLoc = SourceLocation();
12785 }
12786 }
12787
12788 NamedDecl *UD =
12789 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12790 SS, TargetNameInfo, EllipsisLoc, AttrList,
12791 /*IsInstantiation*/ false,
12792 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12793 if (UD)
12794 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12795
12796 return UD;
12797}
12798
12800 SourceLocation UsingLoc,
12801 SourceLocation EnumLoc, SourceRange TyLoc,
12802 const IdentifierInfo &II, ParsedType Ty,
12803 const CXXScopeSpec &SS) {
12804 TypeSourceInfo *TSI = nullptr;
12805 SourceLocation IdentLoc = TyLoc.getBegin();
12806 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12807 if (EnumTy.isNull()) {
12808 Diag(IdentLoc, isDependentScopeSpecifier(SS)
12809 ? diag::err_using_enum_is_dependent
12810 : diag::err_unknown_typename)
12811 << II.getName()
12812 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12813 TyLoc.getEnd());
12814 return nullptr;
12815 }
12816
12817 if (EnumTy->isDependentType()) {
12818 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12819 return nullptr;
12820 }
12821
12822 auto *Enum = EnumTy->getAsEnumDecl();
12823 if (!Enum) {
12824 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12825 return nullptr;
12826 }
12827
12828 if (TSI == nullptr)
12829 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12830
12831 auto *UD =
12832 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12833
12834 if (UD)
12835 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12836
12837 return UD;
12838}
12839
12840/// Determine whether a using declaration considers the given
12841/// declarations as "equivalent", e.g., if they are redeclarations of
12842/// the same entity or are both typedefs of the same type.
12843static bool
12845 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12846 return true;
12847
12848 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12849 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12850 return Context.hasSameType(TD1->getUnderlyingType(),
12851 TD2->getUnderlyingType());
12852
12853 // Two using_if_exists using-declarations are equivalent if both are
12854 // unresolved.
12857 return true;
12858
12859 return false;
12860}
12861
12863 const LookupResult &Previous,
12864 UsingShadowDecl *&PrevShadow) {
12865 // Diagnose finding a decl which is not from a base class of the
12866 // current class. We do this now because there are cases where this
12867 // function will silently decide not to build a shadow decl, which
12868 // will pre-empt further diagnostics.
12869 //
12870 // We don't need to do this in C++11 because we do the check once on
12871 // the qualifier.
12872 //
12873 // FIXME: diagnose the following if we care enough:
12874 // struct A { int foo; };
12875 // struct B : A { using A::foo; };
12876 // template <class T> struct C : A {};
12877 // template <class T> struct D : C<T> { using B::foo; } // <---
12878 // This is invalid (during instantiation) in C++03 because B::foo
12879 // resolves to the using decl in B, which is not a base class of D<T>.
12880 // We can't diagnose it immediately because C<T> is an unknown
12881 // specialization. The UsingShadowDecl in D<T> then points directly
12882 // to A::foo, which will look well-formed when we instantiate.
12883 // The right solution is to not collapse the shadow-decl chain.
12884 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12885 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12886 DeclContext *OrigDC = Orig->getDeclContext();
12887
12888 // Handle enums and anonymous structs.
12889 if (isa<EnumDecl>(OrigDC))
12890 OrigDC = OrigDC->getParent();
12891 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12892 while (OrigRec->isAnonymousStructOrUnion())
12893 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12894
12896 if (OrigDC == CurContext) {
12897 Diag(Using->getLocation(),
12898 diag::err_using_decl_nested_name_specifier_is_current_class)
12899 << Using->getQualifierLoc().getSourceRange();
12900 Diag(Orig->getLocation(), diag::note_using_decl_target);
12901 Using->setInvalidDecl();
12902 return true;
12903 }
12904
12905 Diag(Using->getQualifierLoc().getBeginLoc(),
12906 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12907 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12908 << Using->getQualifierLoc().getSourceRange();
12909 Diag(Orig->getLocation(), diag::note_using_decl_target);
12910 Using->setInvalidDecl();
12911 return true;
12912 }
12913 }
12914
12915 if (Previous.empty()) return false;
12916
12917 NamedDecl *Target = Orig;
12919 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12920
12921 // If the target happens to be one of the previous declarations, we
12922 // don't have a conflict.
12923 //
12924 // FIXME: but we might be increasing its access, in which case we
12925 // should redeclare it.
12926 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12927 bool FoundEquivalentDecl = false;
12928 for (NamedDecl *Element : Previous) {
12929 NamedDecl *D = Element->getUnderlyingDecl();
12930 // We can have UsingDecls in our Previous results because we use the same
12931 // LookupResult for checking whether the UsingDecl itself is a valid
12932 // redeclaration.
12934 continue;
12935
12936 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12937 // C++ [class.mem]p19:
12938 // If T is the name of a class, then [every named member other than
12939 // a non-static data member] shall have a name different from T
12940 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12944 CurContext,
12946 return true;
12947 }
12948
12950 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Element))
12951 PrevShadow = Shadow;
12952 FoundEquivalentDecl = true;
12954 // We don't conflict with an existing using shadow decl of an equivalent
12955 // declaration, but we're not a redeclaration of it.
12956 FoundEquivalentDecl = true;
12957 }
12958
12959 if (isVisible(D))
12960 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12961 }
12962
12963 if (FoundEquivalentDecl)
12964 return false;
12965
12966 // Always emit a diagnostic for a mismatch between an unresolved
12967 // using_if_exists and a resolved using declaration in either direction.
12969 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12970 if (!NonTag && !Tag)
12971 return false;
12972 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12973 Diag(Target->getLocation(), diag::note_using_decl_target);
12974 Diag((NonTag ? NonTag : Tag)->getLocation(),
12975 diag::note_using_decl_conflict);
12976 BUD->setInvalidDecl();
12977 return true;
12978 }
12979
12980 if (FunctionDecl *FD = Target->getAsFunction()) {
12981 NamedDecl *OldDecl = nullptr;
12982 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12983 /*IsForUsingDecl*/ true)) {
12985 return false;
12986
12988 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12989 break;
12990
12991 // We found a decl with the exact signature.
12993 // If we're in a record, we want to hide the target, so we
12994 // return true (without a diagnostic) to tell the caller not to
12995 // build a shadow decl.
12996 if (CurContext->isRecord())
12997 return true;
12998
12999 // If we're not in a record, this is an error.
13000 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13001 break;
13002 }
13003
13004 Diag(Target->getLocation(), diag::note_using_decl_target);
13005 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
13006 BUD->setInvalidDecl();
13007 return true;
13008 }
13009
13010 // Target is not a function.
13011
13012 if (isa<TagDecl>(Target)) {
13013 // No conflict between a tag and a non-tag.
13014 if (!Tag) return false;
13015
13016 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13017 Diag(Target->getLocation(), diag::note_using_decl_target);
13018 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
13019 BUD->setInvalidDecl();
13020 return true;
13021 }
13022
13023 // No conflict between a tag and a non-tag.
13024 if (!NonTag) return false;
13025
13026 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13027 Diag(Target->getLocation(), diag::note_using_decl_target);
13028 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
13029 BUD->setInvalidDecl();
13030 return true;
13031}
13032
13033/// Determine whether a direct base class is a virtual base class.
13035 if (!Derived->getNumVBases())
13036 return false;
13037 for (auto &B : Derived->bases())
13038 if (B.getType()->getAsCXXRecordDecl() == Base)
13039 return B.isVirtual();
13040 llvm_unreachable("not a direct base class");
13041}
13042
13044 NamedDecl *Orig,
13045 UsingShadowDecl *PrevDecl) {
13046 // If we resolved to another shadow declaration, just coalesce them.
13047 NamedDecl *Target = Orig;
13049 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
13050 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13051 }
13052
13053 NamedDecl *NonTemplateTarget = Target;
13054 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
13055 NonTemplateTarget = TargetTD->getTemplatedDecl();
13056
13057 UsingShadowDecl *Shadow;
13058 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
13059 UsingDecl *Using = cast<UsingDecl>(BUD);
13060 bool IsVirtualBase =
13062 Using->getQualifier().getAsRecordDecl());
13064 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
13065 } else {
13067 Target->getDeclName(), BUD, Target);
13068 }
13069 BUD->addShadowDecl(Shadow);
13070
13071 Shadow->setAccess(BUD->getAccess());
13072 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13073 Shadow->setInvalidDecl();
13074
13075 Shadow->setPreviousDecl(PrevDecl);
13076
13077 if (S)
13078 PushOnScopeChains(Shadow, S);
13079 else
13080 CurContext->addDecl(Shadow);
13081
13082
13083 return Shadow;
13084}
13085
13087 if (Shadow->getDeclName().getNameKind() ==
13089 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
13090
13091 // Remove it from the DeclContext...
13092 Shadow->getDeclContext()->removeDecl(Shadow);
13093
13094 // ...and the scope, if applicable...
13095 if (S) {
13096 S->RemoveDecl(Shadow);
13097 IdResolver.RemoveDecl(Shadow);
13098 }
13099
13100 // ...and the using decl.
13101 Shadow->getIntroducer()->removeShadowDecl(Shadow);
13102
13103 // TODO: complain somehow if Shadow was used. It shouldn't
13104 // be possible for this to happen, because...?
13105}
13106
13107/// Find the base specifier for a base class with the given type.
13109 QualType DesiredBase,
13110 bool &AnyDependentBases) {
13111 // Check whether the named type is a direct base class.
13112 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13113 for (auto &Base : Derived->bases()) {
13114 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13115 if (CanonicalDesiredBase == BaseType)
13116 return &Base;
13117 if (BaseType->isDependentType())
13118 AnyDependentBases = true;
13119 }
13120 return nullptr;
13121}
13122
13123namespace {
13124class UsingValidatorCCC final : public CorrectionCandidateCallback {
13125public:
13126 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13127 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13128 : HasTypenameKeyword(HasTypenameKeyword),
13129 IsInstantiation(IsInstantiation), OldNNS(NNS),
13130 RequireMemberOf(RequireMemberOf) {}
13131
13132 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13133 NamedDecl *ND = Candidate.getCorrectionDecl();
13134
13135 // Keywords are not valid here.
13136 if (!ND || isa<NamespaceDecl>(ND))
13137 return false;
13138
13139 // Completely unqualified names are invalid for a 'using' declaration.
13140 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13141 return false;
13142
13143 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13144 // reject.
13145
13146 if (RequireMemberOf) {
13147 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13148 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13149 // No-one ever wants a using-declaration to name an injected-class-name
13150 // of a base class, unless they're declaring an inheriting constructor.
13151 ASTContext &Ctx = ND->getASTContext();
13152 if (!Ctx.getLangOpts().CPlusPlus11)
13153 return false;
13154 CanQualType FoundType = Ctx.getCanonicalTagType(FoundRecord);
13155
13156 // Check that the injected-class-name is named as a member of its own
13157 // type; we don't want to suggest 'using Derived::Base;', since that
13158 // means something else.
13159 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13160 ? Candidate.getCorrectionSpecifier()
13161 : OldNNS;
13162 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13163 !Ctx.hasSameType(QualType(Specifier.getAsType(), 0), FoundType))
13164 return false;
13165
13166 // Check that this inheriting constructor declaration actually names a
13167 // direct base class of the current class.
13168 bool AnyDependentBases = false;
13169 if (!findDirectBaseWithType(RequireMemberOf,
13170 Ctx.getCanonicalTagType(FoundRecord),
13171 AnyDependentBases) &&
13172 !AnyDependentBases)
13173 return false;
13174 } else {
13175 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
13176 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
13177 return false;
13178
13179 // FIXME: Check that the base class member is accessible?
13180 }
13181 } else {
13182 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13183 if (FoundRecord && FoundRecord->isInjectedClassName())
13184 return false;
13185 }
13186
13187 if (isa<TypeDecl>(ND))
13188 return HasTypenameKeyword || !IsInstantiation;
13189
13190 return !HasTypenameKeyword;
13191 }
13192
13193 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13194 return std::make_unique<UsingValidatorCCC>(*this);
13195 }
13196
13197private:
13198 bool HasTypenameKeyword;
13199 bool IsInstantiation;
13200 NestedNameSpecifier OldNNS;
13201 CXXRecordDecl *RequireMemberOf;
13202};
13203} // end anonymous namespace
13204
13206 // It is really dumb that we have to do this.
13207 LookupResult::Filter F = Previous.makeFilter();
13208 while (F.hasNext()) {
13209 NamedDecl *D = F.next();
13210 if (!isDeclInScope(D, CurContext, S))
13211 F.erase();
13212 // If we found a local extern declaration that's not ordinarily visible,
13213 // and this declaration is being added to a non-block scope, ignore it.
13214 // We're only checking for scope conflicts here, not also for violations
13215 // of the linkage rules.
13216 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13218 F.erase();
13219 }
13220 F.done();
13221}
13222
13224 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13225 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13226 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13227 const ParsedAttributesView &AttrList, bool IsInstantiation,
13228 bool IsUsingIfExists) {
13229 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13230 SourceLocation IdentLoc = NameInfo.getLoc();
13231 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13232
13233 // FIXME: We ignore attributes for now.
13234
13235 // For an inheriting constructor declaration, the name of the using
13236 // declaration is the name of a constructor in this class, not in the
13237 // base class.
13238 DeclarationNameInfo UsingName = NameInfo;
13240 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
13241 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13242 Context.getCanonicalTagType(RD)));
13243
13244 // Do the redeclaration lookup in the current scope.
13245 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13247 Previous.setHideTags(false);
13248 if (S) {
13249 LookupName(Previous, S);
13250
13252 } else {
13253 assert(IsInstantiation && "no scope in non-instantiation");
13254 if (CurContext->isRecord())
13256 else {
13257 // No redeclaration check is needed here; in non-member contexts we
13258 // diagnosed all possible conflicts with other using-declarations when
13259 // building the template:
13260 //
13261 // For a dependent non-type using declaration, the only valid case is
13262 // if we instantiate to a single enumerator. We check for conflicts
13263 // between shadow declarations we introduce, and we check in the template
13264 // definition for conflicts between a non-type using declaration and any
13265 // other declaration, which together covers all cases.
13266 //
13267 // A dependent typename using declaration will never successfully
13268 // instantiate, since it will always name a class member, so we reject
13269 // that in the template definition.
13270 }
13271 }
13272
13273 // Check for invalid redeclarations.
13274 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13275 SS, IdentLoc, Previous))
13276 return nullptr;
13277
13278 // 'using_if_exists' doesn't make sense on an inherited constructor.
13279 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13281 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13282 return nullptr;
13283 }
13284
13285 DeclContext *LookupContext = computeDeclContext(SS);
13287 if (!LookupContext || EllipsisLoc.isValid()) {
13288 NamedDecl *D;
13289 // Dependent scope, or an unexpanded pack
13290 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
13291 SS, NameInfo, IdentLoc))
13292 return nullptr;
13293
13294 if (Previous.isSingleResult() &&
13295 Previous.getFoundDecl()->isTemplateParameter())
13296 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13297
13298 if (HasTypenameKeyword) {
13299 // FIXME: not all declaration name kinds are legal here
13301 UsingLoc, TypenameLoc,
13302 QualifierLoc,
13303 IdentLoc, NameInfo.getName(),
13304 EllipsisLoc);
13305 } else {
13307 QualifierLoc, NameInfo, EllipsisLoc);
13308 }
13309 D->setAccess(AS);
13310 CurContext->addDecl(D);
13311 ProcessDeclAttributeList(S, D, AttrList);
13312 return D;
13313 }
13314
13315 auto Build = [&](bool Invalid) {
13316 UsingDecl *UD =
13317 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13318 UsingName, HasTypenameKeyword);
13319 UD->setAccess(AS);
13320 CurContext->addDecl(UD);
13321 ProcessDeclAttributeList(S, UD, AttrList);
13323 return UD;
13324 };
13325 auto BuildInvalid = [&]{ return Build(true); };
13326 auto BuildValid = [&]{ return Build(false); };
13327
13328 if (RequireCompleteDeclContext(SS, LookupContext))
13329 return BuildInvalid();
13330
13331 // Look up the target name.
13332 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13333
13334 // Unlike most lookups, we don't always want to hide tag
13335 // declarations: tag names are visible through the using declaration
13336 // even if hidden by ordinary names, *except* in a dependent context
13337 // where they may be used by two-phase lookup.
13338 if (!IsInstantiation)
13339 R.setHideTags(false);
13340
13341 // For the purposes of this lookup, we have a base object type
13342 // equal to that of the current context.
13343 if (CurContext->isRecord()) {
13344 R.setBaseObjectType(
13345 Context.getCanonicalTagType(cast<CXXRecordDecl>(CurContext)));
13346 }
13347
13348 LookupQualifiedName(R, LookupContext);
13349
13350 // Validate the context, now we have a lookup
13351 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13352 IdentLoc, &R))
13353 return nullptr;
13354
13355 if (R.empty() && IsUsingIfExists)
13357 UsingName.getName()),
13358 AS_public);
13359
13360 // Try to correct typos if possible. If constructor name lookup finds no
13361 // results, that means the named class has no explicit constructors, and we
13362 // suppressed declaring implicit ones (probably because it's dependent or
13363 // invalid).
13364 if (R.empty() &&
13366 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13367 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13368 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13369 auto *II = NameInfo.getName().getAsIdentifierInfo();
13370 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13371 CurContext->isStdNamespace() &&
13372 isa<TranslationUnitDecl>(LookupContext) &&
13373 PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&
13374 getSourceManager().isInSystemHeader(UsingLoc))
13375 return nullptr;
13376 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13377 dyn_cast<CXXRecordDecl>(CurContext));
13378 if (TypoCorrection Corrected =
13379 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13381 // We reject candidates where DroppedSpecifier == true, hence the
13382 // literal '0' below.
13383 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13384 << NameInfo.getName() << LookupContext << 0
13385 << SS.getRange());
13386
13387 // If we picked a correction with no attached Decl we can't do anything
13388 // useful with it, bail out.
13389 NamedDecl *ND = Corrected.getCorrectionDecl();
13390 if (!ND)
13391 return BuildInvalid();
13392
13393 // If we corrected to an inheriting constructor, handle it as one.
13394 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13395 if (RD && RD->isInjectedClassName()) {
13396 // The parent of the injected class name is the class itself.
13397 RD = cast<CXXRecordDecl>(RD->getParent());
13398
13399 // Fix up the information we'll use to build the using declaration.
13400 if (Corrected.WillReplaceSpecifier()) {
13402 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13403 QualifierLoc.getSourceRange());
13404 QualifierLoc = Builder.getWithLocInContext(Context);
13405 }
13406
13407 // In this case, the name we introduce is the name of a derived class
13408 // constructor.
13409 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13410 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13411 Context.getCanonicalTagType(CurClass)));
13412 UsingName.setNamedTypeInfo(nullptr);
13413 for (auto *Ctor : LookupConstructors(RD))
13414 R.addDecl(Ctor);
13415 R.resolveKind();
13416 } else {
13417 // FIXME: Pick up all the declarations if we found an overloaded
13418 // function.
13419 UsingName.setName(ND->getDeclName());
13420 R.addDecl(ND);
13421 }
13422 } else {
13423 Diag(IdentLoc, diag::err_no_member)
13424 << NameInfo.getName() << LookupContext << SS.getRange();
13425 return BuildInvalid();
13426 }
13427 }
13428
13429 if (R.isAmbiguous())
13430 return BuildInvalid();
13431
13432 if (HasTypenameKeyword) {
13433 // If we asked for a typename and got a non-type decl, error out.
13434 if (!R.getAsSingle<TypeDecl>() &&
13435 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13436 Diag(IdentLoc, diag::err_using_typename_non_type);
13437 for (const NamedDecl *D : R)
13438 Diag(D->getUnderlyingDecl()->getLocation(),
13439 diag::note_using_decl_target);
13440 return BuildInvalid();
13441 }
13442 } else {
13443 // If we asked for a non-typename and we got a type, error out,
13444 // but only if this is an instantiation of an unresolved using
13445 // decl. Otherwise just silently find the type name.
13446 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13447 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13448 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13449 return BuildInvalid();
13450 }
13451 }
13452
13453 // C++14 [namespace.udecl]p6:
13454 // A using-declaration shall not name a namespace.
13455 if (R.getAsSingle<NamespaceDecl>()) {
13456 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13457 << SS.getRange();
13458 // Suggest using 'using namespace ...' instead.
13459 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13460 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13461 return BuildInvalid();
13462 }
13463
13464 UsingDecl *UD = BuildValid();
13465
13466 // Some additional rules apply to inheriting constructors.
13467 if (UsingName.getName().getNameKind() ==
13469 // Suppress access diagnostics; the access check is instead performed at the
13470 // point of use for an inheriting constructor.
13471 R.suppressDiagnostics();
13473 return UD;
13474 }
13475
13476 for (NamedDecl *D : R) {
13477 UsingShadowDecl *PrevDecl = nullptr;
13478 if (!CheckUsingShadowDecl(UD, D, Previous, PrevDecl))
13479 BuildUsingShadowDecl(S, UD, D, PrevDecl);
13480 }
13481
13482 return UD;
13483}
13484
13486 SourceLocation UsingLoc,
13487 SourceLocation EnumLoc,
13488 SourceLocation NameLoc,
13489 TypeSourceInfo *EnumType,
13490 EnumDecl *ED) {
13491 bool Invalid = false;
13492
13493 if (CurContext->getRedeclContext()->isRecord()) {
13494 /// In class scope, check if this is a duplicate, for better a diagnostic.
13495 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13496 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13498
13500
13501 for (NamedDecl *D : Previous)
13502 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13503 if (UED->getEnumDecl() == ED) {
13504 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13505 << SourceRange(EnumLoc, NameLoc);
13506 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13507 Invalid = true;
13508 break;
13509 }
13510 }
13511
13512 if (RequireCompleteEnumDecl(ED, NameLoc))
13513 Invalid = true;
13514
13516 EnumLoc, NameLoc, EnumType);
13517 UD->setAccess(AS);
13518 CurContext->addDecl(UD);
13519
13520 if (Invalid) {
13521 UD->setInvalidDecl();
13522 return UD;
13523 }
13524
13525 // Create the shadow decls for each enumerator
13526 for (EnumConstantDecl *EC : ED->enumerators()) {
13527 UsingShadowDecl *PrevDecl = nullptr;
13528 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13531 LookupName(Previous, S);
13533
13534 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13535 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13536 }
13537
13538 return UD;
13539}
13540
13542 ArrayRef<NamedDecl *> Expansions) {
13543 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13544 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13545 isa<UsingPackDecl>(InstantiatedFrom));
13546
13547 auto *UPD =
13548 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13549 UPD->setAccess(InstantiatedFrom->getAccess());
13550 CurContext->addDecl(UPD);
13551 return UPD;
13552}
13553
13555 assert(!UD->hasTypename() && "expecting a constructor name");
13556
13557 QualType SourceType(UD->getQualifier().getAsType(), 0);
13559
13560 // Check whether the named type is a direct base class.
13561 bool AnyDependentBases = false;
13562 auto *Base =
13563 findDirectBaseWithType(TargetClass, SourceType, AnyDependentBases);
13564 if (!Base && !AnyDependentBases) {
13565 Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base)
13566 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13567 UD->setInvalidDecl();
13568 return true;
13569 }
13570
13571 if (Base)
13572 Base->setInheritConstructors();
13573
13574 return false;
13575}
13576
13578 bool HasTypenameKeyword,
13579 const CXXScopeSpec &SS,
13580 SourceLocation NameLoc,
13581 const LookupResult &Prev) {
13582 NestedNameSpecifier Qual = SS.getScopeRep();
13583
13584 // C++03 [namespace.udecl]p8:
13585 // C++0x [namespace.udecl]p10:
13586 // A using-declaration is a declaration and can therefore be used
13587 // repeatedly where (and only where) multiple declarations are
13588 // allowed.
13589 //
13590 // That's in non-member contexts.
13591 if (!CurContext->getRedeclContext()->isRecord()) {
13592 // A dependent qualifier outside a class can only ever resolve to an
13593 // enumeration type. Therefore it conflicts with any other non-type
13594 // declaration in the same scope.
13595 // FIXME: How should we check for dependent type-type conflicts at block
13596 // scope?
13597 if (Qual.isDependent() && !HasTypenameKeyword) {
13598 for (auto *D : Prev) {
13599 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13600 bool OldCouldBeEnumerator =
13602 Diag(NameLoc,
13603 OldCouldBeEnumerator ? diag::err_redefinition
13604 : diag::err_redefinition_different_kind)
13605 << Prev.getLookupName();
13606 Diag(D->getLocation(), diag::note_previous_definition);
13607 return true;
13608 }
13609 }
13610 }
13611 return false;
13612 }
13613
13614 NestedNameSpecifier CNNS = Qual.getCanonical();
13615 for (const NamedDecl *D : Prev) {
13616 bool DTypename;
13617 NestedNameSpecifier DQual = std::nullopt;
13618 if (const auto *UD = dyn_cast<UsingDecl>(D)) {
13619 DTypename = UD->hasTypename();
13620 DQual = UD->getQualifier();
13621 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13622 DTypename = false;
13623 DQual = UD->getQualifier();
13624 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13625 DTypename = true;
13626 DQual = UD->getQualifier();
13627 } else
13628 continue;
13629
13630 // using decls differ if one says 'typename' and the other doesn't.
13631 // FIXME: non-dependent using decls?
13632 if (HasTypenameKeyword != DTypename) continue;
13633
13634 // using decls differ if they name different scopes (but note that
13635 // template instantiation can cause this check to trigger when it
13636 // didn't before instantiation).
13637 if (CNNS != DQual.getCanonical())
13638 continue;
13639
13640 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13641 Diag(D->getLocation(), diag::note_using_decl) << 1;
13642 return true;
13643 }
13644
13645 return false;
13646}
13647
13648bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13649 const CXXScopeSpec &SS,
13650 const DeclarationNameInfo &NameInfo,
13651 SourceLocation NameLoc,
13652 const LookupResult *R, const UsingDecl *UD) {
13653 DeclContext *NamedContext = computeDeclContext(SS);
13654 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13655 "resolvable context must have exactly one set of decls");
13656
13657 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13658 // relationship.
13659 bool Cxx20Enumerator = false;
13660 if (NamedContext) {
13661 EnumConstantDecl *EC = nullptr;
13662 if (R)
13663 EC = R->getAsSingle<EnumConstantDecl>();
13664 else if (UD && UD->shadow_size() == 1)
13665 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13666 if (EC)
13667 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13668
13669 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13670 // C++14 [namespace.udecl]p7:
13671 // A using-declaration shall not name a scoped enumerator.
13672 // C++20 p1099 permits enumerators.
13673 if (EC && R && ED->isScoped())
13674 Diag(SS.getBeginLoc(),
13676 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13677 : diag::ext_using_decl_scoped_enumerator)
13678 << SS.getRange();
13679
13680 // We want to consider the scope of the enumerator
13681 NamedContext = ED->getDeclContext();
13682 }
13683 }
13684
13685 if (!CurContext->isRecord()) {
13686 // C++03 [namespace.udecl]p3:
13687 // C++0x [namespace.udecl]p8:
13688 // A using-declaration for a class member shall be a member-declaration.
13689 // C++20 [namespace.udecl]p7
13690 // ... other than an enumerator ...
13691
13692 // If we weren't able to compute a valid scope, it might validly be a
13693 // dependent class or enumeration scope. If we have a 'typename' keyword,
13694 // the scope must resolve to a class type.
13695 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13696 : !HasTypename)
13697 return false; // OK
13698
13699 Diag(NameLoc,
13700 Cxx20Enumerator
13701 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13702 : diag::err_using_decl_can_not_refer_to_class_member)
13703 << SS.getRange();
13704
13705 if (Cxx20Enumerator)
13706 return false; // OK
13707
13708 auto *RD = NamedContext
13709 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13710 : nullptr;
13711 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13712 // See if there's a helpful fixit
13713
13714 if (!R) {
13715 // We will have already diagnosed the problem on the template
13716 // definition, Maybe we should do so again?
13717 } else if (R->getAsSingle<TypeDecl>()) {
13718 if (getLangOpts().CPlusPlus11) {
13719 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13720 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13721 << diag::MemClassWorkaround::AliasDecl
13723 NameInfo.getName().getAsString() +
13724 " = ");
13725 } else {
13726 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13727 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13728 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13729 << diag::MemClassWorkaround::TypedefDecl
13730 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13732 InsertLoc, " " + NameInfo.getName().getAsString());
13733 }
13734 } else if (R->getAsSingle<VarDecl>()) {
13735 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13736 // repeating the type of the static data member here.
13737 FixItHint FixIt;
13738 if (getLangOpts().CPlusPlus11) {
13739 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13741 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13742 }
13743
13744 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13745 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13746 } else if (R->getAsSingle<EnumConstantDecl>()) {
13747 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13748 // repeating the type of the enumeration here, and we can't do so if
13749 // the type is anonymous.
13750 FixItHint FixIt;
13751 if (getLangOpts().CPlusPlus11) {
13752 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13754 UsingLoc,
13755 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13756 }
13757
13758 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13759 << (getLangOpts().CPlusPlus11
13760 ? diag::MemClassWorkaround::ConstexprVar
13761 : diag::MemClassWorkaround::ConstVar)
13762 << FixIt;
13763 }
13764 }
13765
13766 return true; // Fail
13767 }
13768
13769 // If the named context is dependent, we can't decide much.
13770 if (!NamedContext) {
13771 // FIXME: in C++0x, we can diagnose if we can prove that the
13772 // nested-name-specifier does not refer to a base class, which is
13773 // still possible in some cases.
13774
13775 // Otherwise we have to conservatively report that things might be
13776 // okay.
13777 return false;
13778 }
13779
13780 // The current scope is a record.
13781 if (!NamedContext->isRecord()) {
13782 // Ideally this would point at the last name in the specifier,
13783 // but we don't have that level of source info.
13784 Diag(SS.getBeginLoc(),
13785 Cxx20Enumerator
13786 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13787 : diag::err_using_decl_nested_name_specifier_is_not_class)
13788 << SS.getScopeRep() << SS.getRange();
13789
13790 if (Cxx20Enumerator)
13791 return false; // OK
13792
13793 return true;
13794 }
13795
13796 if (!NamedContext->isDependentContext() &&
13797 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13798 return true;
13799
13800 // C++26 [namespace.udecl]p3:
13801 // In a using-declaration used as a member-declaration, each
13802 // using-declarator shall either name an enumerator or have a
13803 // nested-name-specifier naming a base class of the current class
13804 // ([expr.prim.this]). ...
13805 // "have a nested-name-specifier naming a base class of the current class"
13806 // was introduced by CWG400.
13807
13810
13811 if (Cxx20Enumerator) {
13812 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13813 << SS.getScopeRep() << SS.getRange();
13814 return false;
13815 }
13816
13817 if (CurContext == NamedContext) {
13818 Diag(SS.getBeginLoc(),
13819 diag::err_using_decl_nested_name_specifier_is_current_class)
13820 << SS.getRange();
13821 return true;
13822 }
13823
13824 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13825 Diag(SS.getBeginLoc(),
13826 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13828 << SS.getRange();
13829 }
13830 return true;
13831 }
13832
13833 return false;
13834}
13835
13837 MultiTemplateParamsArg TemplateParamLists,
13838 SourceLocation UsingLoc, UnqualifiedId &Name,
13839 const ParsedAttributesView &AttrList,
13840 TypeResult Type, Decl *DeclFromDeclSpec) {
13841
13842 if (Type.isInvalid())
13843 return nullptr;
13844
13845 bool Invalid = false;
13847 TypeSourceInfo *TInfo = nullptr;
13848 GetTypeFromParser(Type.get(), &TInfo);
13849
13850 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13851 return nullptr;
13852
13855 Invalid = true;
13856 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13857 TInfo->getTypeLoc().getBeginLoc());
13858 }
13859
13860 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13861 TemplateParamLists.size()
13864 LookupName(Previous, S);
13865
13866 // Warn about shadowing the name of a template parameter.
13867 if (Previous.isSingleResult() &&
13868 Previous.getFoundDecl()->isTemplateParameter()) {
13870 Previous.clear();
13871 }
13872
13873 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13874 "name in alias declaration must be an identifier");
13876 Name.StartLocation,
13877 Name.Identifier, TInfo);
13878
13879 NewTD->setAccess(AS);
13880
13881 if (Invalid)
13882 NewTD->setInvalidDecl();
13883
13884 ProcessDeclAttributeList(S, NewTD, AttrList);
13885 AddPragmaAttributes(S, NewTD);
13886 ProcessAPINotes(NewTD);
13887
13889 Invalid |= NewTD->isInvalidDecl();
13890
13891 // Get the innermost enclosing declaration scope.
13892 S = S->getDeclParent();
13893
13894 bool Redeclaration = false;
13895
13896 NamedDecl *NewND;
13897 if (TemplateParamLists.size()) {
13898 TypeAliasTemplateDecl *OldDecl = nullptr;
13899 TemplateParameterList *OldTemplateParams = nullptr;
13900
13901 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13902 if (TemplateParamLists.size() != 1) {
13903 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13904 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13905 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13906 Invalid = true;
13907
13908 // Recover by picking the last non-empty template parameter list.
13909 auto It = llvm::find_if(
13910 llvm::reverse(TemplateParamLists),
13911 [](TemplateParameterList *TPL) { return !TPL->empty(); });
13912 assert(It != TemplateParamLists.rend() &&
13913 "if all template parameter lists were empty, this should have "
13914 "been rejected as an explicit specialization");
13915 TemplateParams = *It;
13916 }
13917
13918 // Check that we can declare a template here.
13919 if (CheckTemplateDeclScope(S, TemplateParams))
13920 return nullptr;
13921
13922 // Only consider previous declarations in the same scope.
13923 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13924 /*ExplicitInstantiationOrSpecialization*/false);
13925 if (!Previous.empty()) {
13926 Redeclaration = true;
13927
13928 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13929 if (!OldDecl && !Invalid) {
13930 Diag(UsingLoc, diag::err_redefinition_different_kind)
13931 << Name.Identifier;
13932
13933 NamedDecl *OldD = Previous.getRepresentativeDecl();
13934 if (OldD->getLocation().isValid())
13935 Diag(OldD->getLocation(), diag::note_previous_definition);
13936
13937 Invalid = true;
13938 }
13939
13940 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13941 if (TemplateParameterListsAreEqual(TemplateParams,
13942 OldDecl->getTemplateParameters(),
13943 /*Complain=*/true,
13945 OldTemplateParams =
13947 else
13948 Invalid = true;
13949
13950 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13951 if (!Invalid &&
13952 !Context.hasSameType(OldTD->getUnderlyingType(),
13953 NewTD->getUnderlyingType())) {
13954 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13955 // but we can't reasonably accept it.
13956 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13957 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13958 if (OldTD->getLocation().isValid())
13959 Diag(OldTD->getLocation(), diag::note_previous_definition);
13960 Invalid = true;
13961 }
13962 }
13963 }
13964
13965 // Merge any previous default template arguments into our parameters,
13966 // and check the parameter list.
13967 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13968 TPC_Other))
13969 return nullptr;
13970
13971 TypeAliasTemplateDecl *NewDecl =
13973 Name.Identifier, TemplateParams,
13974 NewTD);
13975 NewTD->setDescribedAliasTemplate(NewDecl);
13976
13977 NewDecl->setAccess(AS);
13978
13979 if (Invalid)
13980 NewDecl->setInvalidDecl();
13981 else if (OldDecl) {
13982 NewDecl->setPreviousDecl(OldDecl);
13983 CheckRedeclarationInModule(NewDecl, OldDecl);
13984 }
13985
13986 NewND = NewDecl;
13987 } else {
13988 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13990 handleTagNumbering(TD, S);
13991 }
13993 NewND = NewTD;
13994 }
13995
13996 PushOnScopeChains(NewND, S);
13997 ActOnDocumentableDecl(NewND);
13998 return NewND;
13999}
14000
14002 SourceLocation AliasLoc,
14003 IdentifierInfo *Alias, CXXScopeSpec &SS,
14004 SourceLocation IdentLoc,
14005 IdentifierInfo *Ident) {
14006
14007 // Lookup the namespace name.
14008 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14009 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
14010
14011 if (R.isAmbiguous())
14012 return nullptr;
14013
14014 if (R.empty()) {
14015 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
14016 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
14017 return nullptr;
14018 }
14019 }
14020 assert(!R.isAmbiguous() && !R.empty());
14021 auto *ND = cast<NamespaceBaseDecl>(R.getRepresentativeDecl());
14022
14023 // Check if we have a previous declaration with the same name.
14024 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14026 LookupName(PrevR, S);
14027
14028 // Check we're not shadowing a template parameter.
14029 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14031 PrevR.clear();
14032 }
14033
14034 // Filter out any other lookup result from an enclosing scope.
14035 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
14036 /*AllowInlineNamespace*/false);
14037
14038 // Find the previous declaration and check that we can redeclare it.
14039 NamespaceAliasDecl *Prev = nullptr;
14040 if (PrevR.isSingleResult()) {
14041 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14042 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
14043 // We already have an alias with the same name that points to the same
14044 // namespace; check that it matches.
14045 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
14046 Prev = AD;
14047 } else if (isVisible(PrevDecl)) {
14048 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
14049 << Alias;
14050 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
14051 << AD->getNamespace();
14052 return nullptr;
14053 }
14054 } else if (isVisible(PrevDecl)) {
14055 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
14056 ? diag::err_redefinition
14057 : diag::err_redefinition_different_kind;
14058 Diag(AliasLoc, DiagID) << Alias;
14059 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14060 return nullptr;
14061 }
14062 }
14063
14064 // The use of a nested name specifier may trigger deprecation warnings.
14065 DiagnoseUseOfDecl(ND, IdentLoc);
14066
14068 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
14069 Alias, SS.getWithLocInContext(Context),
14070 IdentLoc, ND);
14071 if (Prev)
14072 AliasDecl->setPreviousDecl(Prev);
14073
14075 return AliasDecl;
14076}
14077
14078namespace {
14079struct SpecialMemberExceptionSpecInfo
14080 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14081 SourceLocation Loc;
14083
14084 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14087 SourceLocation Loc)
14088 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14089
14090 bool visitBase(CXXBaseSpecifier *Base);
14091 bool visitField(FieldDecl *FD);
14092
14093 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14094 unsigned Quals);
14095
14096 void visitSubobjectCall(Subobject Subobj,
14098};
14099}
14100
14101bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14102 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14103 if (!BaseClass)
14104 return false;
14105
14106 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
14107 if (auto *BaseCtor = SMOR.getMethod()) {
14108 visitSubobjectCall(Base, BaseCtor);
14109 return false;
14110 }
14111
14112 visitClassSubobject(BaseClass, Base, 0);
14113 return false;
14114}
14115
14116bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14117 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14118 FD->hasInClassInitializer()) {
14119 Expr *E = FD->getInClassInitializer();
14120 if (!E)
14121 // FIXME: It's a little wasteful to build and throw away a
14122 // CXXDefaultInitExpr here.
14123 // FIXME: We should have a single context note pointing at Loc, and
14124 // this location should be MD->getLocation() instead, since that's
14125 // the location where we actually use the default init expression.
14126 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
14127 if (E)
14128 ExceptSpec.CalledExpr(E);
14129 } else if (auto *RD = S.Context.getBaseElementType(FD->getType())
14130 ->getAsCXXRecordDecl()) {
14131 visitClassSubobject(RD, FD, FD->getType().getCVRQualifiers());
14132 }
14133 return false;
14134}
14135
14136void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14137 Subobject Subobj,
14138 unsigned Quals) {
14139 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14140 bool IsMutable = Field && Field->isMutable();
14141 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
14142}
14143
14144void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14145 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14146 // Note, if lookup fails, it doesn't matter what exception specification we
14147 // choose because the special member will be deleted.
14148 if (CXXMethodDecl *MD = SMOR.getMethod())
14149 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
14150}
14151
14153 llvm::APSInt Result;
14155 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
14156 ExplicitSpec.setExpr(Converted.get());
14157 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14158 ExplicitSpec.setKind(Result.getBoolValue()
14161 return true;
14162 }
14164 return false;
14165}
14166
14169 if (!ExplicitExpr->isTypeDependent())
14171 return ES;
14172}
14173
14178 ComputingExceptionSpec CES(S, MD, Loc);
14179
14180 CXXRecordDecl *ClassDecl = MD->getParent();
14181
14182 // C++ [except.spec]p14:
14183 // An implicitly declared special member function (Clause 12) shall have an
14184 // exception-specification. [...]
14185 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14186 if (ClassDecl->isInvalidDecl())
14187 return Info.ExceptSpec;
14188
14189 // FIXME: If this diagnostic fires, we're probably missing a check for
14190 // attempting to resolve an exception specification before it's known
14191 // at a higher level.
14192 if (S.RequireCompleteType(MD->getLocation(),
14193 S.Context.getCanonicalTagType(ClassDecl),
14194 diag::err_exception_spec_incomplete_type))
14195 return Info.ExceptSpec;
14196
14197 // C++1z [except.spec]p7:
14198 // [Look for exceptions thrown by] a constructor selected [...] to
14199 // initialize a potentially constructed subobject,
14200 // C++1z [except.spec]p8:
14201 // The exception specification for an implicitly-declared destructor, or a
14202 // destructor without a noexcept-specifier, is potentially-throwing if and
14203 // only if any of the destructors for any of its potentially constructed
14204 // subojects is potentially throwing.
14205 // FIXME: We respect the first rule but ignore the "potentially constructed"
14206 // in the second rule to resolve a core issue (no number yet) that would have
14207 // us reject:
14208 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14209 // struct B : A {};
14210 // struct C : B { void f(); };
14211 // ... due to giving B::~B() a non-throwing exception specification.
14212 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14213 : Info.VisitAllBases);
14214
14215 return Info.ExceptSpec;
14216}
14217
14218namespace {
14219/// RAII object to register a special member as being currently declared.
14220struct DeclaringSpecialMember {
14221 Sema &S;
14223 Sema::ContextRAII SavedContext;
14224 bool WasAlreadyBeingDeclared;
14225
14226 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14227 : S(S), D(RD, CSM), SavedContext(S, RD) {
14228 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
14229 if (WasAlreadyBeingDeclared)
14230 // This almost never happens, but if it does, ensure that our cache
14231 // doesn't contain a stale result.
14232 S.SpecialMemberCache.clear();
14233 else {
14234 // Register a note to be produced if we encounter an error while
14235 // declaring the special member.
14236 Sema::CodeSynthesisContext Ctx;
14237 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14238 // FIXME: We don't have a location to use here. Using the class's
14239 // location maintains the fiction that we declare all special members
14240 // with the class, but (1) it's not clear that lying about that helps our
14241 // users understand what's going on, and (2) there may be outer contexts
14242 // on the stack (some of which are relevant) and printing them exposes
14243 // our lies.
14244 Ctx.PointOfInstantiation = RD->getLocation();
14245 Ctx.Entity = RD;
14246 Ctx.SpecialMember = CSM;
14247 S.pushCodeSynthesisContext(Ctx);
14248 }
14249 }
14250 ~DeclaringSpecialMember() {
14251 if (!WasAlreadyBeingDeclared) {
14252 S.SpecialMembersBeingDeclared.erase(D);
14254 }
14255 }
14256
14257 /// Are we already trying to declare this special member?
14258 bool isAlreadyBeingDeclared() const {
14259 return WasAlreadyBeingDeclared;
14260 }
14261};
14262}
14263
14265 // Look up any existing declarations, but don't trigger declaration of all
14266 // implicit special members with this name.
14267 DeclarationName Name = FD->getDeclName();
14270 for (auto *D : FD->getParent()->lookup(Name))
14271 if (auto *Acceptable = R.getAcceptableDecl(D))
14272 R.addDecl(Acceptable);
14273 R.resolveKind();
14274 R.suppressDiagnostics();
14275
14276 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14278}
14279
14280void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14281 QualType ResultTy,
14282 ArrayRef<QualType> Args) {
14283 // Build an exception specification pointing back at this constructor.
14285
14286 LangAS AS = getDefaultCXXMethodAddrSpace();
14287 if (AS != LangAS::Default) {
14288 EPI.TypeQuals.addAddressSpace(AS);
14289 }
14290
14291 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14292 SpecialMem->setType(QT);
14293
14294 // During template instantiation of implicit special member functions we need
14295 // a reliable TypeSourceInfo for the function prototype in order to allow
14296 // functions to be substituted.
14297 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14298 TypeSourceInfo *TSI =
14299 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14300 SpecialMem->setTypeSourceInfo(TSI);
14301 }
14302}
14303
14305 CXXRecordDecl *ClassDecl) {
14306 // C++ [class.ctor]p5:
14307 // A default constructor for a class X is a constructor of class X
14308 // that can be called without an argument. If there is no
14309 // user-declared constructor for class X, a default constructor is
14310 // implicitly declared. An implicitly-declared default constructor
14311 // is an inline public member of its class.
14312 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14313 "Should not build implicit default constructor!");
14314
14315 DeclaringSpecialMember DSM(*this, ClassDecl,
14317 if (DSM.isAlreadyBeingDeclared())
14318 return nullptr;
14319
14321 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14322
14323 // Create the actual constructor declaration.
14324 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14325 SourceLocation ClassLoc = ClassDecl->getLocation();
14326 DeclarationName Name
14327 = Context.DeclarationNames.getCXXConstructorName(ClassType);
14328 DeclarationNameInfo NameInfo(Name, ClassLoc);
14330 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14331 /*TInfo=*/nullptr, ExplicitSpecifier(),
14332 getCurFPFeatures().isFPConstrained(),
14333 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14336 DefaultCon->setAccess(AS_public);
14337 DefaultCon->setDefaulted();
14338
14339 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
14340
14341 if (getLangOpts().CUDA)
14342 CUDA().inferTargetForImplicitSpecialMember(
14343 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14344 /* ConstRHS */ false,
14345 /* Diagnose */ false);
14346
14347 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14348 // constructors is easy to compute.
14349 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14350
14351 // Note that we have declared this constructor.
14352 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14353
14354 Scope *S = getScopeForContext(ClassDecl);
14356
14357 if (ShouldDeleteSpecialMember(DefaultCon,
14359 SetDeclDeleted(DefaultCon, ClassLoc);
14360
14361 if (S)
14362 PushOnScopeChains(DefaultCon, S, false);
14363 ClassDecl->addDecl(DefaultCon);
14364
14365 return DefaultCon;
14366}
14367
14370 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14371 !Constructor->doesThisDeclarationHaveABody() &&
14372 !Constructor->isDeleted()) &&
14373 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14374 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14375 return;
14376
14377 CXXRecordDecl *ClassDecl = Constructor->getParent();
14378 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14379 if (ClassDecl->isInvalidDecl()) {
14380 return;
14381 }
14382
14384
14385 // The exception specification is needed because we are defining the
14386 // function.
14387 ResolveExceptionSpec(CurrentLocation,
14388 Constructor->getType()->castAs<FunctionProtoType>());
14389 MarkVTableUsed(CurrentLocation, ClassDecl);
14390
14391 // Add a context note for diagnostics produced after this point.
14392 Scope.addContextNote(CurrentLocation);
14393
14394 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14395 Constructor->setInvalidDecl();
14396 return;
14397 }
14398
14399 SourceLocation Loc = Constructor->getEndLoc().isValid()
14400 ? Constructor->getEndLoc()
14401 : Constructor->getLocation();
14402 Constructor->setBody(new (Context) CompoundStmt(Loc));
14403 Constructor->markUsed(Context);
14404
14406 L->CompletedImplicitDefinition(Constructor);
14407 }
14408
14409 DiagnoseUninitializedFields(*this, Constructor);
14410}
14411
14413 // Perform any delayed checks on exception specifications.
14415}
14416
14417/// Find or create the fake constructor we synthesize to model constructing an
14418/// object of a derived class via a constructor of a base class.
14421 CXXConstructorDecl *BaseCtor,
14423 CXXRecordDecl *Derived = Shadow->getParent();
14424 SourceLocation UsingLoc = Shadow->getLocation();
14425
14426 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14427 // For now we use the name of the base class constructor as a member of the
14428 // derived class to indicate a (fake) inherited constructor name.
14429 DeclarationName Name = BaseCtor->getDeclName();
14430
14431 // Check to see if we already have a fake constructor for this inherited
14432 // constructor call.
14433 for (NamedDecl *Ctor : Derived->lookup(Name))
14435 ->getInheritedConstructor()
14436 .getConstructor(),
14437 BaseCtor))
14438 return cast<CXXConstructorDecl>(Ctor);
14439
14440 DeclarationNameInfo NameInfo(Name, UsingLoc);
14441 TypeSourceInfo *TInfo =
14442 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14443 FunctionProtoTypeLoc ProtoLoc =
14445
14446 // Check the inherited constructor is valid and find the list of base classes
14447 // from which it was inherited.
14448 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14449
14450 bool Constexpr = BaseCtor->isConstexpr() &&
14453 false, BaseCtor, &ICI);
14454
14456 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14457 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14458 /*isInline=*/true,
14459 /*isImplicitlyDeclared=*/true,
14461 InheritedConstructor(Shadow, BaseCtor),
14462 BaseCtor->getTrailingRequiresClause());
14463 if (Shadow->isInvalidDecl())
14464 DerivedCtor->setInvalidDecl();
14465
14466 // Build an unevaluated exception specification for this fake constructor.
14467 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14470 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14471 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14472 FPT->getParamTypes(), EPI));
14473
14474 // Build the parameter declarations.
14476 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14477 TypeSourceInfo *TInfo =
14478 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14480 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14481 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14482 PD->setScopeInfo(0, I);
14483 PD->setImplicit();
14484 // Ensure attributes are propagated onto parameters (this matters for
14485 // format, pass_object_size, ...).
14486 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14487 ParamDecls.push_back(PD);
14488 ProtoLoc.setParam(I, PD);
14489 }
14490
14491 // Set up the new constructor.
14492 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14493 DerivedCtor->setAccess(BaseCtor->getAccess());
14494 DerivedCtor->setParams(ParamDecls);
14495 Derived->addDecl(DerivedCtor);
14496
14497 if (ShouldDeleteSpecialMember(DerivedCtor,
14499 SetDeclDeleted(DerivedCtor, UsingLoc);
14500
14501 return DerivedCtor;
14502}
14503
14511
14514 CXXRecordDecl *ClassDecl = Constructor->getParent();
14515 assert(Constructor->getInheritedConstructor() &&
14516 !Constructor->doesThisDeclarationHaveABody() &&
14517 !Constructor->isDeleted());
14518 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14519 return;
14520
14521 // Initializations are performed "as if by a defaulted default constructor",
14522 // so enter the appropriate scope.
14524
14525 // The exception specification is needed because we are defining the
14526 // function.
14527 ResolveExceptionSpec(CurrentLocation,
14528 Constructor->getType()->castAs<FunctionProtoType>());
14529 MarkVTableUsed(CurrentLocation, ClassDecl);
14530
14531 // Add a context note for diagnostics produced after this point.
14532 Scope.addContextNote(CurrentLocation);
14533
14535 Constructor->getInheritedConstructor().getShadowDecl();
14536 CXXConstructorDecl *InheritedCtor =
14537 Constructor->getInheritedConstructor().getConstructor();
14538
14539 // [class.inhctor.init]p1:
14540 // initialization proceeds as if a defaulted default constructor is used to
14541 // initialize the D object and each base class subobject from which the
14542 // constructor was inherited
14543
14544 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14545 CXXRecordDecl *RD = Shadow->getParent();
14546 SourceLocation InitLoc = Shadow->getLocation();
14547
14548 // Build explicit initializers for all base classes from which the
14549 // constructor was inherited.
14551 for (bool VBase : {false, true}) {
14552 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14553 if (B.isVirtual() != VBase)
14554 continue;
14555
14556 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14557 if (!BaseRD)
14558 continue;
14559
14560 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14561 if (!BaseCtor.first)
14562 continue;
14563
14564 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14566 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14567
14568 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14569 Inits.push_back(new (Context) CXXCtorInitializer(
14570 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14571 SourceLocation()));
14572 }
14573 }
14574
14575 // We now proceed as if for a defaulted default constructor, with the relevant
14576 // initializers replaced.
14577
14578 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14579 Constructor->setInvalidDecl();
14580 return;
14581 }
14582
14583 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14584 Constructor->markUsed(Context);
14585
14587 L->CompletedImplicitDefinition(Constructor);
14588 }
14589
14590 DiagnoseUninitializedFields(*this, Constructor);
14591}
14592
14594 // C++ [class.dtor]p2:
14595 // If a class has no user-declared destructor, a destructor is
14596 // declared implicitly. An implicitly-declared destructor is an
14597 // inline public member of its class.
14598 assert(ClassDecl->needsImplicitDestructor());
14599
14600 DeclaringSpecialMember DSM(*this, ClassDecl,
14602 if (DSM.isAlreadyBeingDeclared())
14603 return nullptr;
14604
14606 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14607
14608 // Create the actual destructor declaration.
14609 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14610 SourceLocation ClassLoc = ClassDecl->getLocation();
14611 DeclarationName Name
14612 = Context.DeclarationNames.getCXXDestructorName(ClassType);
14613 DeclarationNameInfo NameInfo(Name, ClassLoc);
14615 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14616 getCurFPFeatures().isFPConstrained(),
14617 /*isInline=*/true,
14618 /*isImplicitlyDeclared=*/true,
14621 Destructor->setAccess(AS_public);
14622 Destructor->setDefaulted();
14623
14624 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14625
14626 if (getLangOpts().CUDA)
14627 CUDA().inferTargetForImplicitSpecialMember(
14629 /* ConstRHS */ false,
14630 /* Diagnose */ false);
14631
14632 // We don't need to use SpecialMemberIsTrivial here; triviality for
14633 // destructors is easy to compute.
14634 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14635 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14636 ClassDecl->hasTrivialDestructorForCall());
14637
14638 // Note that we have declared this destructor.
14639 ++getASTContext().NumImplicitDestructorsDeclared;
14640
14641 Scope *S = getScopeForContext(ClassDecl);
14643
14644 // We can't check whether an implicit destructor is deleted before we complete
14645 // the definition of the class, because its validity depends on the alignment
14646 // of the class. We'll check this from ActOnFields once the class is complete.
14647 if (ClassDecl->isCompleteDefinition() &&
14649 SetDeclDeleted(Destructor, ClassLoc);
14650
14651 // Introduce this destructor into its scope.
14652 if (S)
14653 PushOnScopeChains(Destructor, S, false);
14654 ClassDecl->addDecl(Destructor);
14655
14656 return Destructor;
14657}
14658
14661 assert((Destructor->isDefaulted() &&
14662 !Destructor->doesThisDeclarationHaveABody() &&
14663 !Destructor->isDeleted()) &&
14664 "DefineImplicitDestructor - call it for implicit default dtor");
14665 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14666 return;
14667
14668 CXXRecordDecl *ClassDecl = Destructor->getParent();
14669 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14670
14672
14673 // The exception specification is needed because we are defining the
14674 // function.
14675 ResolveExceptionSpec(CurrentLocation,
14676 Destructor->getType()->castAs<FunctionProtoType>());
14677 MarkVTableUsed(CurrentLocation, ClassDecl);
14678
14679 // Add a context note for diagnostics produced after this point.
14680 Scope.addContextNote(CurrentLocation);
14681
14683 Destructor->getParent());
14684
14686 Destructor->setInvalidDecl();
14687 return;
14688 }
14689
14690 SourceLocation Loc = Destructor->getEndLoc().isValid()
14691 ? Destructor->getEndLoc()
14692 : Destructor->getLocation();
14693 Destructor->setBody(new (Context) CompoundStmt(Loc));
14694 Destructor->markUsed(Context);
14695
14697 L->CompletedImplicitDefinition(Destructor);
14698 }
14699}
14700
14703 if (Destructor->isInvalidDecl())
14704 return;
14705
14706 CXXRecordDecl *ClassDecl = Destructor->getParent();
14707 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14708 "implicit complete dtors unneeded outside MS ABI");
14709 assert(ClassDecl->getNumVBases() > 0 &&
14710 "complete dtor only exists for classes with vbases");
14711
14713
14714 // Add a context note for diagnostics produced after this point.
14715 Scope.addContextNote(CurrentLocation);
14716
14717 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14718}
14719
14721 // If the context is an invalid C++ class, just suppress these checks.
14722 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14723 if (Record->isInvalidDecl()) {
14726 return;
14727 }
14729 }
14730}
14731
14734
14735 if (!DelayedDllExportMemberFunctions.empty()) {
14737 std::swap(DelayedDllExportMemberFunctions, WorkList);
14738 for (CXXMethodDecl *M : WorkList) {
14739 DefineDefaultedFunction(*this, M, M->getLocation());
14740
14741 // Pass the method to the consumer to get emitted. This is not necessary
14742 // for explicit instantiation definitions, as they will get emitted
14743 // anyway.
14744 if (M->getParent()->getTemplateSpecializationKind() !=
14747 }
14748 }
14749}
14750
14752 if (!DelayedDllExportClasses.empty()) {
14753 // Calling ReferenceDllExportedMembers might cause the current function to
14754 // be called again, so use a local copy of DelayedDllExportClasses.
14756 std::swap(DelayedDllExportClasses, WorkList);
14757 for (CXXRecordDecl *Class : WorkList)
14759 }
14760}
14761
14763 assert(getLangOpts().CPlusPlus11 &&
14764 "adjusting dtor exception specs was introduced in c++11");
14765
14766 if (Destructor->isDependentContext())
14767 return;
14768
14769 // C++11 [class.dtor]p3:
14770 // A declaration of a destructor that does not have an exception-
14771 // specification is implicitly considered to have the same exception-
14772 // specification as an implicit declaration.
14773 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14774 if (DtorType->hasExceptionSpec())
14775 return;
14776
14777 // Replace the destructor's type, building off the existing one. Fortunately,
14778 // the only thing of interest in the destructor type is its extended info.
14779 // The return and arguments are fixed.
14780 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14783 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14784
14785 // FIXME: If the destructor has a body that could throw, and the newly created
14786 // spec doesn't allow exceptions, we should emit a warning, because this
14787 // change in behavior can break conforming C++03 programs at runtime.
14788 // However, we don't have a body or an exception specification yet, so it
14789 // needs to be done somewhere else.
14790}
14791
14792namespace {
14793/// An abstract base class for all helper classes used in building the
14794// copy/move operators. These classes serve as factory functions and help us
14795// avoid using the same Expr* in the AST twice.
14796class ExprBuilder {
14797 ExprBuilder(const ExprBuilder&) = delete;
14798 ExprBuilder &operator=(const ExprBuilder&) = delete;
14799
14800protected:
14801 static Expr *assertNotNull(Expr *E) {
14802 assert(E && "Expression construction must not fail.");
14803 return E;
14804 }
14805
14806public:
14807 ExprBuilder() {}
14808 virtual ~ExprBuilder() {}
14809
14810 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14811};
14812
14813class RefBuilder: public ExprBuilder {
14814 VarDecl *Var;
14815 QualType VarType;
14816
14817public:
14818 Expr *build(Sema &S, SourceLocation Loc) const override {
14819 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14820 }
14821
14822 RefBuilder(VarDecl *Var, QualType VarType)
14823 : Var(Var), VarType(VarType) {}
14824};
14825
14826class ThisBuilder: public ExprBuilder {
14827public:
14828 Expr *build(Sema &S, SourceLocation Loc) const override {
14829 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14830 }
14831};
14832
14833class CastBuilder: public ExprBuilder {
14834 const ExprBuilder &Builder;
14835 QualType Type;
14837 const CXXCastPath &Path;
14838
14839public:
14840 Expr *build(Sema &S, SourceLocation Loc) const override {
14841 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14842 CK_UncheckedDerivedToBase, Kind,
14843 &Path).get());
14844 }
14845
14846 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14847 const CXXCastPath &Path)
14848 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14849};
14850
14851class DerefBuilder: public ExprBuilder {
14852 const ExprBuilder &Builder;
14853
14854public:
14855 Expr *build(Sema &S, SourceLocation Loc) const override {
14856 return assertNotNull(
14857 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14858 }
14859
14860 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14861};
14862
14863class MemberBuilder: public ExprBuilder {
14864 const ExprBuilder &Builder;
14865 QualType Type;
14866 CXXScopeSpec SS;
14867 bool IsArrow;
14868 LookupResult &MemberLookup;
14869
14870public:
14871 Expr *build(Sema &S, SourceLocation Loc) const override {
14872 return assertNotNull(S.BuildMemberReferenceExpr(
14873 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14874 nullptr, MemberLookup, nullptr, nullptr).get());
14875 }
14876
14877 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14878 LookupResult &MemberLookup)
14879 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14880 MemberLookup(MemberLookup) {}
14881};
14882
14883class MoveCastBuilder: public ExprBuilder {
14884 const ExprBuilder &Builder;
14885
14886public:
14887 Expr *build(Sema &S, SourceLocation Loc) const override {
14888 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14889 }
14890
14891 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14892};
14893
14894class LvalueConvBuilder: public ExprBuilder {
14895 const ExprBuilder &Builder;
14896
14897public:
14898 Expr *build(Sema &S, SourceLocation Loc) const override {
14899 return assertNotNull(
14900 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14901 }
14902
14903 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14904};
14905
14906class SubscriptBuilder: public ExprBuilder {
14907 const ExprBuilder &Base;
14908 const ExprBuilder &Index;
14909
14910public:
14911 Expr *build(Sema &S, SourceLocation Loc) const override {
14912 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14913 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14914 }
14915
14916 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14917 : Base(Base), Index(Index) {}
14918};
14919
14920} // end anonymous namespace
14921
14922/// When generating a defaulted copy or move assignment operator, if a field
14923/// should be copied with __builtin_memcpy rather than via explicit assignments,
14924/// do so. This optimization only applies for arrays of scalars, and for arrays
14925/// of class type where the selected copy/move-assignment operator is trivial.
14926static StmtResult
14928 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14929 // Compute the size of the memory buffer to be copied.
14930 QualType SizeType = S.Context.getSizeType();
14931 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14933
14934 // Take the address of the field references for "from" and "to". We
14935 // directly construct UnaryOperators here because semantic analysis
14936 // does not permit us to take the address of an xvalue.
14937 Expr *From = FromB.build(S, Loc);
14938 From = UnaryOperator::Create(
14939 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14940 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14941 Expr *To = ToB.build(S, Loc);
14943 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14944 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14945
14946 bool NeedsCollectableMemCpy = false;
14947 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14948 NeedsCollectableMemCpy = RD->hasObjectMember();
14949
14950 // Create a reference to the __builtin_objc_memmove_collectable function
14951 StringRef MemCpyName = NeedsCollectableMemCpy ?
14952 "__builtin_objc_memmove_collectable" :
14953 "__builtin_memcpy";
14954 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14956 S.LookupName(R, S.TUScope, true);
14957
14958 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14959 if (!MemCpy)
14960 // Something went horribly wrong earlier, and we will have complained
14961 // about it.
14962 return StmtError();
14963
14964 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14965 VK_PRValue, Loc, nullptr);
14966 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14967
14968 Expr *CallArgs[] = {
14969 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14970 };
14971 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14972 Loc, CallArgs, Loc);
14973
14974 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14975 return Call.getAs<Stmt>();
14976}
14977
14978/// Builds a statement that copies/moves the given entity from \p From to
14979/// \c To.
14980///
14981/// This routine is used to copy/move the members of a class with an
14982/// implicitly-declared copy/move assignment operator. When the entities being
14983/// copied are arrays, this routine builds for loops to copy them.
14984///
14985/// \param S The Sema object used for type-checking.
14986///
14987/// \param Loc The location where the implicit copy/move is being generated.
14988///
14989/// \param T The type of the expressions being copied/moved. Both expressions
14990/// must have this type.
14991///
14992/// \param To The expression we are copying/moving to.
14993///
14994/// \param From The expression we are copying/moving from.
14995///
14996/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14997/// Otherwise, it's a non-static member subobject.
14998///
14999/// \param Copying Whether we're copying or moving.
15000///
15001/// \param Depth Internal parameter recording the depth of the recursion.
15002///
15003/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15004/// if a memcpy should be used instead.
15005static StmtResult
15007 const ExprBuilder &To, const ExprBuilder &From,
15008 bool CopyingBaseSubobject, bool Copying,
15009 unsigned Depth = 0) {
15010 // C++11 [class.copy]p28:
15011 // Each subobject is assigned in the manner appropriate to its type:
15012 //
15013 // - if the subobject is of class type, as if by a call to operator= with
15014 // the subobject as the object expression and the corresponding
15015 // subobject of x as a single function argument (as if by explicit
15016 // qualification; that is, ignoring any possible virtual overriding
15017 // functions in more derived classes);
15018 //
15019 // C++03 [class.copy]p13:
15020 // - if the subobject is of class type, the copy assignment operator for
15021 // the class is used (as if by explicit qualification; that is,
15022 // ignoring any possible virtual overriding functions in more derived
15023 // classes);
15024 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15025 // Look for operator=.
15026 DeclarationName Name
15028 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15029 S.LookupQualifiedName(OpLookup, ClassDecl, false);
15030
15031 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15032 // operator.
15033 if (!S.getLangOpts().CPlusPlus11) {
15034 LookupResult::Filter F = OpLookup.makeFilter();
15035 while (F.hasNext()) {
15036 NamedDecl *D = F.next();
15037 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
15038 if (Method->isCopyAssignmentOperator() ||
15039 (!Copying && Method->isMoveAssignmentOperator()))
15040 continue;
15041
15042 F.erase();
15043 }
15044 F.done();
15045 }
15046
15047 // Suppress the protected check (C++ [class.protected]) for each of the
15048 // assignment operators we found. This strange dance is required when
15049 // we're assigning via a base classes's copy-assignment operator. To
15050 // ensure that we're getting the right base class subobject (without
15051 // ambiguities), we need to cast "this" to that subobject type; to
15052 // ensure that we don't go through the virtual call mechanism, we need
15053 // to qualify the operator= name with the base class (see below). However,
15054 // this means that if the base class has a protected copy assignment
15055 // operator, the protected member access check will fail. So, we
15056 // rewrite "protected" access to "public" access in this case, since we
15057 // know by construction that we're calling from a derived class.
15058 if (CopyingBaseSubobject) {
15059 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15060 L != LEnd; ++L) {
15061 if (L.getAccess() == AS_protected)
15062 L.setAccess(AS_public);
15063 }
15064 }
15065
15066 // Create the nested-name-specifier that will be used to qualify the
15067 // reference to operator=; this is required to suppress the virtual
15068 // call mechanism.
15069 CXXScopeSpec SS;
15070 // FIXME: Don't canonicalize this.
15071 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
15072 SS.MakeTrivial(S.Context, NestedNameSpecifier(CanonicalT), Loc);
15073
15074 // Create the reference to operator=.
15075 ExprResult OpEqualRef
15076 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
15077 SS, /*TemplateKWLoc=*/SourceLocation(),
15078 /*FirstQualifierInScope=*/nullptr,
15079 OpLookup,
15080 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15081 /*SuppressQualifierCheck=*/true);
15082 if (OpEqualRef.isInvalid())
15083 return StmtError();
15084
15085 // Build the call to the assignment operator.
15086
15087 Expr *FromInst = From.build(S, Loc);
15088 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
15089 OpEqualRef.getAs<Expr>(),
15090 Loc, FromInst, Loc);
15091 if (Call.isInvalid())
15092 return StmtError();
15093
15094 // If we built a call to a trivial 'operator=' while copying an array,
15095 // bail out. We'll replace the whole shebang with a memcpy.
15096 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
15097 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15098 return StmtResult((Stmt*)nullptr);
15099
15100 // Convert to an expression-statement, and clean up any produced
15101 // temporaries.
15102 return S.ActOnExprStmt(Call);
15103 }
15104
15105 // - if the subobject is of scalar type, the built-in assignment
15106 // operator is used.
15107 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
15108 if (!ArrayTy) {
15110 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
15111 if (Assignment.isInvalid())
15112 return StmtError();
15113 return S.ActOnExprStmt(Assignment);
15114 }
15115
15116 // - if the subobject is an array, each element is assigned, in the
15117 // manner appropriate to the element type;
15118
15119 // Construct a loop over the array bounds, e.g.,
15120 //
15121 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15122 //
15123 // that will copy each of the array elements.
15124 QualType SizeType = S.Context.getSizeType();
15125
15126 // Create the iteration variable.
15127 IdentifierInfo *IterationVarName = nullptr;
15128 {
15129 SmallString<8> Str;
15130 llvm::raw_svector_ostream OS(Str);
15131 OS << "__i" << Depth;
15132 IterationVarName = &S.Context.Idents.get(OS.str());
15133 }
15134 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
15135 IterationVarName, SizeType,
15136 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
15137 SC_None);
15138
15139 // Initialize the iteration variable to zero.
15140 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
15141 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
15142
15143 // Creates a reference to the iteration variable.
15144 RefBuilder IterationVarRef(IterationVar, SizeType);
15145 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15146
15147 // Create the DeclStmt that holds the iteration variable.
15148 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15149
15150 // Subscript the "from" and "to" expressions with the iteration variable.
15151 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15152 MoveCastBuilder FromIndexMove(FromIndexCopy);
15153 const ExprBuilder *FromIndex;
15154 if (Copying)
15155 FromIndex = &FromIndexCopy;
15156 else
15157 FromIndex = &FromIndexMove;
15158
15159 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15160
15161 // Build the copy/move for an individual element of the array.
15162 StmtResult Copy =
15164 ToIndex, *FromIndex, CopyingBaseSubobject,
15165 Copying, Depth + 1);
15166 // Bail out if copying fails or if we determined that we should use memcpy.
15167 if (Copy.isInvalid() || !Copy.get())
15168 return Copy;
15169
15170 // Create the comparison against the array bound.
15171 llvm::APInt Upper
15172 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
15174 S.Context, IterationVarRefRVal.build(S, Loc),
15175 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
15178
15179 // Create the pre-increment of the iteration variable. We can determine
15180 // whether the increment will overflow based on the value of the array
15181 // bound.
15182 Expr *Increment = UnaryOperator::Create(
15183 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
15184 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
15185
15186 // Construct the loop that copies all elements of this array.
15187 return S.ActOnForStmt(
15188 Loc, Loc, InitStmt,
15190 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
15191}
15192
15193static StmtResult
15195 const ExprBuilder &To, const ExprBuilder &From,
15196 bool CopyingBaseSubobject, bool Copying) {
15197 // Maybe we should use a memcpy?
15198 if (T->isArrayType() && !T.hasQualifiers() &&
15199 T.isTriviallyCopyableType(S.Context))
15200 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15201
15202 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15203 CopyingBaseSubobject,
15204 Copying, 0));
15205
15206 // If we ended up picking a trivial assignment operator for an array of a
15207 // non-trivially-copyable class type, just emit a memcpy.
15208 if (!Result.isInvalid() && !Result.get())
15209 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15210
15211 return Result;
15212}
15213
15215 // Note: The following rules are largely analoguous to the copy
15216 // constructor rules. Note that virtual bases are not taken into account
15217 // for determining the argument type of the operator. Note also that
15218 // operators taking an object instead of a reference are allowed.
15219 assert(ClassDecl->needsImplicitCopyAssignment());
15220
15221 DeclaringSpecialMember DSM(*this, ClassDecl,
15223 if (DSM.isAlreadyBeingDeclared())
15224 return nullptr;
15225
15227 /*Qualifier=*/std::nullopt, ClassDecl,
15228 /*OwnsTag=*/false);
15230 if (AS != LangAS::Default)
15231 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15232 QualType RetType = Context.getLValueReferenceType(ArgType);
15233 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15234 if (Const)
15235 ArgType = ArgType.withConst();
15236
15237 ArgType = Context.getLValueReferenceType(ArgType);
15238
15240 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
15241
15242 // An implicitly-declared copy assignment operator is an inline public
15243 // member of its class.
15244 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15245 SourceLocation ClassLoc = ClassDecl->getLocation();
15246 DeclarationNameInfo NameInfo(Name, ClassLoc);
15248 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15249 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15250 getCurFPFeatures().isFPConstrained(),
15251 /*isInline=*/true,
15253 SourceLocation());
15254 CopyAssignment->setAccess(AS_public);
15255 CopyAssignment->setDefaulted();
15256 CopyAssignment->setImplicit();
15257
15258 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15259
15260 if (getLangOpts().CUDA)
15261 CUDA().inferTargetForImplicitSpecialMember(
15263 /* ConstRHS */ Const,
15264 /* Diagnose */ false);
15265
15266 // Add the parameter to the operator.
15268 ClassLoc, ClassLoc,
15269 /*Id=*/nullptr, ArgType,
15270 /*TInfo=*/nullptr, SC_None,
15271 nullptr);
15272 CopyAssignment->setParams(FromParam);
15273
15274 CopyAssignment->setTrivial(
15278 : ClassDecl->hasTrivialCopyAssignment());
15279
15280 // Note that we have added this copy-assignment operator.
15281 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15282
15283 Scope *S = getScopeForContext(ClassDecl);
15285
15289 SetDeclDeleted(CopyAssignment, ClassLoc);
15290 }
15291
15292 if (S)
15294 ClassDecl->addDecl(CopyAssignment);
15295
15296 return CopyAssignment;
15297}
15298
15299/// Diagnose an implicit copy operation for a class which is odr-used, but
15300/// which is deprecated because the class has a user-declared copy constructor,
15301/// copy assignment operator, or destructor.
15303 assert(CopyOp->isImplicit());
15304
15305 CXXRecordDecl *RD = CopyOp->getParent();
15306 CXXMethodDecl *UserDeclaredOperation = nullptr;
15307
15308 if (RD->hasUserDeclaredDestructor()) {
15309 UserDeclaredOperation = RD->getDestructor();
15310 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15312 // Find any user-declared copy constructor.
15313 for (auto *I : RD->ctors()) {
15314 if (I->isCopyConstructor()) {
15315 UserDeclaredOperation = I;
15316 break;
15317 }
15318 }
15319 assert(UserDeclaredOperation);
15320 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15322 // Find any user-declared move assignment operator.
15323 for (auto *I : RD->methods()) {
15324 if (I->isCopyAssignmentOperator()) {
15325 UserDeclaredOperation = I;
15326 break;
15327 }
15328 }
15329 assert(UserDeclaredOperation);
15330 }
15331
15332 if (UserDeclaredOperation) {
15333 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15334 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15335 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15336 unsigned DiagID =
15337 (UDOIsUserProvided && UDOIsDestructor)
15338 ? diag::warn_deprecated_copy_with_user_provided_dtor
15339 : (UDOIsUserProvided && !UDOIsDestructor)
15340 ? diag::warn_deprecated_copy_with_user_provided_copy
15341 : (!UDOIsUserProvided && UDOIsDestructor)
15342 ? diag::warn_deprecated_copy_with_dtor
15343 : diag::warn_deprecated_copy;
15344 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15345 << RD << IsCopyAssignment;
15346 }
15347}
15348
15350 CXXMethodDecl *CopyAssignOperator) {
15351 assert((CopyAssignOperator->isDefaulted() &&
15352 CopyAssignOperator->isOverloadedOperator() &&
15353 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15354 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15355 !CopyAssignOperator->isDeleted()) &&
15356 "DefineImplicitCopyAssignment called for wrong function");
15357 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15358 return;
15359
15360 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15361 if (ClassDecl->isInvalidDecl()) {
15362 CopyAssignOperator->setInvalidDecl();
15363 return;
15364 }
15365
15366 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15367
15368 // The exception specification is needed because we are defining the
15369 // function.
15370 ResolveExceptionSpec(CurrentLocation,
15371 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15372
15373 // Add a context note for diagnostics produced after this point.
15374 Scope.addContextNote(CurrentLocation);
15375
15376 // C++11 [class.copy]p18:
15377 // The [definition of an implicitly declared copy assignment operator] is
15378 // deprecated if the class has a user-declared copy constructor or a
15379 // user-declared destructor.
15380 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15381 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15382
15383 // C++0x [class.copy]p30:
15384 // The implicitly-defined or explicitly-defaulted copy assignment operator
15385 // for a non-union class X performs memberwise copy assignment of its
15386 // subobjects. The direct base classes of X are assigned first, in the
15387 // order of their declaration in the base-specifier-list, and then the
15388 // immediate non-static data members of X are assigned, in the order in
15389 // which they were declared in the class definition.
15390
15391 // The statements that form the synthesized function body.
15392 SmallVector<Stmt*, 8> Statements;
15393
15394 // The parameter for the "other" object, which we are copying from.
15395 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15396 Qualifiers OtherQuals = Other->getType().getQualifiers();
15397 QualType OtherRefType = Other->getType();
15398 if (OtherRefType->isLValueReferenceType()) {
15399 OtherRefType = OtherRefType->getPointeeType();
15400 OtherQuals = OtherRefType.getQualifiers();
15401 }
15402
15403 // Our location for everything implicitly-generated.
15404 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15405 ? CopyAssignOperator->getEndLoc()
15406 : CopyAssignOperator->getLocation();
15407
15408 // Builds a DeclRefExpr for the "other" object.
15409 RefBuilder OtherRef(Other, OtherRefType);
15410
15411 // Builds the function object parameter.
15412 std::optional<ThisBuilder> This;
15413 std::optional<DerefBuilder> DerefThis;
15414 std::optional<RefBuilder> ExplicitObject;
15415 bool IsArrow = false;
15416 QualType ObjectType;
15417 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15418 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15419 if (ObjectType->isReferenceType())
15420 ObjectType = ObjectType->getPointeeType();
15421 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15422 } else {
15423 ObjectType = getCurrentThisType();
15424 This.emplace();
15425 DerefThis.emplace(*This);
15426 IsArrow = !LangOpts.HLSL;
15427 }
15428 ExprBuilder &ObjectParameter =
15429 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15430 : static_cast<ExprBuilder &>(*This);
15431
15432 // Assign base classes.
15433 bool Invalid = false;
15434 for (auto &Base : ClassDecl->bases()) {
15435 // Form the assignment:
15436 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15437 QualType BaseType = Base.getType().getUnqualifiedType();
15438 if (!BaseType->isRecordType()) {
15439 Invalid = true;
15440 continue;
15441 }
15442
15443 CXXCastPath BasePath;
15444 BasePath.push_back(&Base);
15445
15446 // Construct the "from" expression, which is an implicit cast to the
15447 // appropriately-qualified base type.
15448 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15449 VK_LValue, BasePath);
15450
15451 // Dereference "this".
15452 CastBuilder To(
15453 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15454 : static_cast<ExprBuilder &>(*DerefThis),
15455 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15456 VK_LValue, BasePath);
15457
15458 // Build the copy.
15459 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15460 To, From,
15461 /*CopyingBaseSubobject=*/true,
15462 /*Copying=*/true);
15463 if (Copy.isInvalid()) {
15464 CopyAssignOperator->setInvalidDecl();
15465 return;
15466 }
15467
15468 // Success! Record the copy.
15469 Statements.push_back(Copy.getAs<Expr>());
15470 }
15471
15472 // Assign non-static members.
15473 for (auto *Field : ClassDecl->fields()) {
15474 // FIXME: We should form some kind of AST representation for the implied
15475 // memcpy in a union copy operation.
15476 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15477 continue;
15478
15479 if (Field->isInvalidDecl()) {
15480 Invalid = true;
15481 continue;
15482 }
15483
15484 // Check for members of reference type; we can't copy those.
15485 if (Field->getType()->isReferenceType()) {
15486 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15487 << Context.getCanonicalTagType(ClassDecl) << 0
15488 << Field->getDeclName();
15489 Diag(Field->getLocation(), diag::note_declared_at);
15490 Invalid = true;
15491 continue;
15492 }
15493
15494 // Check for members of const-qualified, non-class type.
15495 QualType BaseType = Context.getBaseElementType(Field->getType());
15496 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15497 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15498 << Context.getCanonicalTagType(ClassDecl) << 1
15499 << Field->getDeclName();
15500 Diag(Field->getLocation(), diag::note_declared_at);
15501 Invalid = true;
15502 continue;
15503 }
15504
15505 // Suppress assigning zero-width bitfields.
15506 if (Field->isZeroLengthBitField())
15507 continue;
15508
15509 QualType FieldType = Field->getType().getNonReferenceType();
15510 if (FieldType->isIncompleteArrayType()) {
15511 assert(ClassDecl->hasFlexibleArrayMember() &&
15512 "Incomplete array type is not valid");
15513 continue;
15514 }
15515
15516 // Build references to the field in the object we're copying from and to.
15517 CXXScopeSpec SS; // Intentionally empty
15518 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15520 MemberLookup.addDecl(Field);
15521 MemberLookup.resolveKind();
15522
15523 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15524 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15525 // Build the copy of this field.
15526 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15527 To, From,
15528 /*CopyingBaseSubobject=*/false,
15529 /*Copying=*/true);
15530 if (Copy.isInvalid()) {
15531 CopyAssignOperator->setInvalidDecl();
15532 return;
15533 }
15534
15535 // Success! Record the copy.
15536 Statements.push_back(Copy.getAs<Stmt>());
15537 }
15538
15539 if (!Invalid) {
15540 // Add a "return *this;"
15541 Expr *ThisExpr =
15542 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15543 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15544 : static_cast<ExprBuilder &>(*DerefThis))
15545 .build(*this, Loc);
15546 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15547 if (Return.isInvalid())
15548 Invalid = true;
15549 else
15550 Statements.push_back(Return.getAs<Stmt>());
15551 }
15552
15553 if (Invalid) {
15554 CopyAssignOperator->setInvalidDecl();
15555 return;
15556 }
15557
15558 StmtResult Body;
15559 {
15560 CompoundScopeRAII CompoundScope(*this);
15561 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15562 /*isStmtExpr=*/false);
15563 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15564 }
15565 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15566 CopyAssignOperator->markUsed(Context);
15567
15569 L->CompletedImplicitDefinition(CopyAssignOperator);
15570 }
15571}
15572
15574 assert(ClassDecl->needsImplicitMoveAssignment());
15575
15576 DeclaringSpecialMember DSM(*this, ClassDecl,
15578 if (DSM.isAlreadyBeingDeclared())
15579 return nullptr;
15580
15581 // Note: The following rules are largely analoguous to the move
15582 // constructor rules.
15583
15585 /*Qualifier=*/std::nullopt, ClassDecl,
15586 /*OwnsTag=*/false);
15588 if (AS != LangAS::Default)
15589 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15590 QualType RetType = Context.getLValueReferenceType(ArgType);
15591 ArgType = Context.getRValueReferenceType(ArgType);
15592
15594 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15595
15596 // An implicitly-declared move assignment operator is an inline public
15597 // member of its class.
15598 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15599 SourceLocation ClassLoc = ClassDecl->getLocation();
15600 DeclarationNameInfo NameInfo(Name, ClassLoc);
15602 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15603 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15604 getCurFPFeatures().isFPConstrained(),
15605 /*isInline=*/true,
15607 SourceLocation());
15608 MoveAssignment->setAccess(AS_public);
15609 MoveAssignment->setDefaulted();
15610 MoveAssignment->setImplicit();
15611
15612 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15613
15614 if (getLangOpts().CUDA)
15615 CUDA().inferTargetForImplicitSpecialMember(
15617 /* ConstRHS */ false,
15618 /* Diagnose */ false);
15619
15620 // Add the parameter to the operator.
15622 ClassLoc, ClassLoc,
15623 /*Id=*/nullptr, ArgType,
15624 /*TInfo=*/nullptr, SC_None,
15625 nullptr);
15626 MoveAssignment->setParams(FromParam);
15627
15628 MoveAssignment->setTrivial(
15632 : ClassDecl->hasTrivialMoveAssignment());
15633
15634 // Note that we have added this copy-assignment operator.
15635 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15636
15637 Scope *S = getScopeForContext(ClassDecl);
15639
15643 SetDeclDeleted(MoveAssignment, ClassLoc);
15644 }
15645
15646 if (S)
15648 ClassDecl->addDecl(MoveAssignment);
15649
15650 return MoveAssignment;
15651}
15652
15653/// Check if we're implicitly defining a move assignment operator for a class
15654/// with virtual bases. Such a move assignment might move-assign the virtual
15655/// base multiple times.
15657 SourceLocation CurrentLocation) {
15658 assert(!Class->isDependentContext() && "should not define dependent move");
15659
15660 // Only a virtual base could get implicitly move-assigned multiple times.
15661 // Only a non-trivial move assignment can observe this. We only want to
15662 // diagnose if we implicitly define an assignment operator that assigns
15663 // two base classes, both of which move-assign the same virtual base.
15664 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15665 Class->getNumBases() < 2)
15666 return;
15667
15669 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15670 VBaseMap VBases;
15671
15672 for (auto &BI : Class->bases()) {
15673 Worklist.push_back(&BI);
15674 while (!Worklist.empty()) {
15675 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15676 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15677
15678 // If the base has no non-trivial move assignment operators,
15679 // we don't care about moves from it.
15680 if (!Base->hasNonTrivialMoveAssignment())
15681 continue;
15682
15683 // If there's nothing virtual here, skip it.
15684 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15685 continue;
15686
15687 // If we're not actually going to call a move assignment for this base,
15688 // or the selected move assignment is trivial, skip it.
15691 /*ConstArg*/ false, /*VolatileArg*/ false,
15692 /*RValueThis*/ true, /*ConstThis*/ false,
15693 /*VolatileThis*/ false);
15694 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15696 continue;
15697
15698 if (BaseSpec->isVirtual()) {
15699 // We're going to move-assign this virtual base, and its move
15700 // assignment operator is not trivial. If this can happen for
15701 // multiple distinct direct bases of Class, diagnose it. (If it
15702 // only happens in one base, we'll diagnose it when synthesizing
15703 // that base class's move assignment operator.)
15704 CXXBaseSpecifier *&Existing =
15705 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15706 .first->second;
15707 if (Existing && Existing != &BI) {
15708 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15709 << Class << Base;
15710 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15711 << (Base->getCanonicalDecl() ==
15713 << Base << Existing->getType() << Existing->getSourceRange();
15714 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15715 << (Base->getCanonicalDecl() ==
15716 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15717 << Base << BI.getType() << BaseSpec->getSourceRange();
15718
15719 // Only diagnose each vbase once.
15720 Existing = nullptr;
15721 }
15722 } else {
15723 // Only walk over bases that have defaulted move assignment operators.
15724 // We assume that any user-provided move assignment operator handles
15725 // the multiple-moves-of-vbase case itself somehow.
15726 if (!SMOR.getMethod()->isDefaulted())
15727 continue;
15728
15729 // We're going to move the base classes of Base. Add them to the list.
15730 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15731 }
15732 }
15733 }
15734}
15735
15737 CXXMethodDecl *MoveAssignOperator) {
15738 assert((MoveAssignOperator->isDefaulted() &&
15739 MoveAssignOperator->isOverloadedOperator() &&
15740 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15741 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15742 !MoveAssignOperator->isDeleted()) &&
15743 "DefineImplicitMoveAssignment called for wrong function");
15744 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15745 return;
15746
15747 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15748 if (ClassDecl->isInvalidDecl()) {
15749 MoveAssignOperator->setInvalidDecl();
15750 return;
15751 }
15752
15753 // C++0x [class.copy]p28:
15754 // The implicitly-defined or move assignment operator for a non-union class
15755 // X performs memberwise move assignment of its subobjects. The direct base
15756 // classes of X are assigned first, in the order of their declaration in the
15757 // base-specifier-list, and then the immediate non-static data members of X
15758 // are assigned, in the order in which they were declared in the class
15759 // definition.
15760
15761 // Issue a warning if our implicit move assignment operator will move
15762 // from a virtual base more than once.
15763 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15764
15765 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15766
15767 // The exception specification is needed because we are defining the
15768 // function.
15769 ResolveExceptionSpec(CurrentLocation,
15770 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15771
15772 // Add a context note for diagnostics produced after this point.
15773 Scope.addContextNote(CurrentLocation);
15774
15775 // The statements that form the synthesized function body.
15776 SmallVector<Stmt*, 8> Statements;
15777
15778 // The parameter for the "other" object, which we are move from.
15779 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15780 QualType OtherRefType =
15781 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15782
15783 // Our location for everything implicitly-generated.
15784 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15785 ? MoveAssignOperator->getEndLoc()
15786 : MoveAssignOperator->getLocation();
15787
15788 // Builds a reference to the "other" object.
15789 RefBuilder OtherRef(Other, OtherRefType);
15790 // Cast to rvalue.
15791 MoveCastBuilder MoveOther(OtherRef);
15792
15793 // Builds the function object parameter.
15794 std::optional<ThisBuilder> This;
15795 std::optional<DerefBuilder> DerefThis;
15796 std::optional<RefBuilder> ExplicitObject;
15797 QualType ObjectType;
15798 bool IsArrow = false;
15799 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15800 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15801 if (ObjectType->isReferenceType())
15802 ObjectType = ObjectType->getPointeeType();
15803 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15804 } else {
15805 ObjectType = getCurrentThisType();
15806 This.emplace();
15807 DerefThis.emplace(*This);
15808 IsArrow = !getLangOpts().HLSL;
15809 }
15810 ExprBuilder &ObjectParameter =
15811 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15812
15813 // Assign base classes.
15814 bool Invalid = false;
15815 for (auto &Base : ClassDecl->bases()) {
15816 // C++11 [class.copy]p28:
15817 // It is unspecified whether subobjects representing virtual base classes
15818 // are assigned more than once by the implicitly-defined copy assignment
15819 // operator.
15820 // FIXME: Do not assign to a vbase that will be assigned by some other base
15821 // class. For a move-assignment, this can result in the vbase being moved
15822 // multiple times.
15823
15824 // Form the assignment:
15825 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15826 QualType BaseType = Base.getType().getUnqualifiedType();
15827 if (!BaseType->isRecordType()) {
15828 Invalid = true;
15829 continue;
15830 }
15831
15832 CXXCastPath BasePath;
15833 BasePath.push_back(&Base);
15834
15835 // Construct the "from" expression, which is an implicit cast to the
15836 // appropriately-qualified base type.
15837 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15838
15839 // Implicitly cast "this" to the appropriately-qualified base type.
15840 // Dereference "this".
15841 CastBuilder To(
15842 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15843 : static_cast<ExprBuilder &>(*DerefThis),
15844 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15845 VK_LValue, BasePath);
15846
15847 // Build the move.
15848 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15849 To, From,
15850 /*CopyingBaseSubobject=*/true,
15851 /*Copying=*/false);
15852 if (Move.isInvalid()) {
15853 MoveAssignOperator->setInvalidDecl();
15854 return;
15855 }
15856
15857 // Success! Record the move.
15858 Statements.push_back(Move.getAs<Expr>());
15859 }
15860
15861 // Assign non-static members.
15862 for (auto *Field : ClassDecl->fields()) {
15863 // FIXME: We should form some kind of AST representation for the implied
15864 // memcpy in a union copy operation.
15865 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15866 continue;
15867
15868 if (Field->isInvalidDecl()) {
15869 Invalid = true;
15870 continue;
15871 }
15872
15873 // Check for members of reference type; we can't move those.
15874 if (Field->getType()->isReferenceType()) {
15875 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15876 << Context.getCanonicalTagType(ClassDecl) << 0
15877 << Field->getDeclName();
15878 Diag(Field->getLocation(), diag::note_declared_at);
15879 Invalid = true;
15880 continue;
15881 }
15882
15883 // Check for members of const-qualified, non-class type.
15884 QualType BaseType = Context.getBaseElementType(Field->getType());
15885 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15886 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15887 << Context.getCanonicalTagType(ClassDecl) << 1
15888 << Field->getDeclName();
15889 Diag(Field->getLocation(), diag::note_declared_at);
15890 Invalid = true;
15891 continue;
15892 }
15893
15894 // Suppress assigning zero-width bitfields.
15895 if (Field->isZeroLengthBitField())
15896 continue;
15897
15898 QualType FieldType = Field->getType().getNonReferenceType();
15899 if (FieldType->isIncompleteArrayType()) {
15900 assert(ClassDecl->hasFlexibleArrayMember() &&
15901 "Incomplete array type is not valid");
15902 continue;
15903 }
15904
15905 // Build references to the field in the object we're copying from and to.
15906 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15908 MemberLookup.addDecl(Field);
15909 MemberLookup.resolveKind();
15910 MemberBuilder From(MoveOther, OtherRefType,
15911 /*IsArrow=*/false, MemberLookup);
15912 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15913
15914 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15915 "Member reference with rvalue base must be rvalue except for reference "
15916 "members, which aren't allowed for move assignment.");
15917
15918 // Build the move of this field.
15919 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15920 To, From,
15921 /*CopyingBaseSubobject=*/false,
15922 /*Copying=*/false);
15923 if (Move.isInvalid()) {
15924 MoveAssignOperator->setInvalidDecl();
15925 return;
15926 }
15927
15928 // Success! Record the copy.
15929 Statements.push_back(Move.getAs<Stmt>());
15930 }
15931
15932 if (!Invalid) {
15933 // Add a "return *this;"
15934 Expr *ThisExpr =
15935 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15936 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15937 : static_cast<ExprBuilder &>(*DerefThis))
15938 .build(*this, Loc);
15939
15940 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15941 if (Return.isInvalid())
15942 Invalid = true;
15943 else
15944 Statements.push_back(Return.getAs<Stmt>());
15945 }
15946
15947 if (Invalid) {
15948 MoveAssignOperator->setInvalidDecl();
15949 return;
15950 }
15951
15952 StmtResult Body;
15953 {
15954 CompoundScopeRAII CompoundScope(*this);
15955 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15956 /*isStmtExpr=*/false);
15957 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15958 }
15959 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15960 MoveAssignOperator->markUsed(Context);
15961
15963 L->CompletedImplicitDefinition(MoveAssignOperator);
15964 }
15965}
15966
15968 CXXRecordDecl *ClassDecl) {
15969 // C++ [class.copy]p4:
15970 // If the class definition does not explicitly declare a copy
15971 // constructor, one is declared implicitly.
15972 assert(ClassDecl->needsImplicitCopyConstructor());
15973
15974 DeclaringSpecialMember DSM(*this, ClassDecl,
15976 if (DSM.isAlreadyBeingDeclared())
15977 return nullptr;
15978
15979 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
15980 /*Qualifier=*/std::nullopt, ClassDecl,
15981 /*OwnsTag=*/false);
15982 QualType ArgType = ClassType;
15983 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15984 if (Const)
15985 ArgType = ArgType.withConst();
15986
15988 if (AS != LangAS::Default)
15989 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15990
15991 ArgType = Context.getLValueReferenceType(ArgType);
15992
15994 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15995
15996 DeclarationName Name
15997 = Context.DeclarationNames.getCXXConstructorName(
15998 Context.getCanonicalType(ClassType));
15999 SourceLocation ClassLoc = ClassDecl->getLocation();
16000 DeclarationNameInfo NameInfo(Name, ClassLoc);
16001
16002 // An implicitly-declared copy constructor is an inline public
16003 // member of its class.
16005 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16006 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16007 /*isInline=*/true,
16008 /*isImplicitlyDeclared=*/true,
16011 CopyConstructor->setAccess(AS_public);
16012 CopyConstructor->setDefaulted();
16013
16014 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
16015
16016 if (getLangOpts().CUDA)
16017 CUDA().inferTargetForImplicitSpecialMember(
16019 /* ConstRHS */ Const,
16020 /* Diagnose */ false);
16021
16022 // During template instantiation of special member functions we need a
16023 // reliable TypeSourceInfo for the parameter types in order to allow functions
16024 // to be substituted.
16025 TypeSourceInfo *TSI = nullptr;
16026 if (inTemplateInstantiation() && ClassDecl->isLambda())
16027 TSI = Context.getTrivialTypeSourceInfo(ArgType);
16028
16029 // Add the parameter to the constructor.
16030 ParmVarDecl *FromParam =
16031 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
16032 /*IdentifierInfo=*/nullptr, ArgType,
16033 /*TInfo=*/TSI, SC_None, nullptr);
16034 CopyConstructor->setParams(FromParam);
16035
16036 CopyConstructor->setTrivial(
16040 : ClassDecl->hasTrivialCopyConstructor());
16041
16042 CopyConstructor->setTrivialForCall(
16043 ClassDecl->hasAttr<TrivialABIAttr>() ||
16048 : ClassDecl->hasTrivialCopyConstructorForCall()));
16049
16050 // Note that we have declared this constructor.
16051 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16052
16053 Scope *S = getScopeForContext(ClassDecl);
16055
16060 }
16061
16062 if (S)
16064 ClassDecl->addDecl(CopyConstructor);
16065
16066 return CopyConstructor;
16067}
16068
16071 assert((CopyConstructor->isDefaulted() &&
16072 CopyConstructor->isCopyConstructor() &&
16073 !CopyConstructor->doesThisDeclarationHaveABody() &&
16074 !CopyConstructor->isDeleted()) &&
16075 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16076 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16077 return;
16078
16079 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16080 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16081
16083
16084 // The exception specification is needed because we are defining the
16085 // function.
16086 ResolveExceptionSpec(CurrentLocation,
16087 CopyConstructor->getType()->castAs<FunctionProtoType>());
16088 MarkVTableUsed(CurrentLocation, ClassDecl);
16089
16090 // Add a context note for diagnostics produced after this point.
16091 Scope.addContextNote(CurrentLocation);
16092
16093 // C++11 [class.copy]p7:
16094 // The [definition of an implicitly declared copy constructor] is
16095 // deprecated if the class has a user-declared copy assignment operator
16096 // or a user-declared destructor.
16097 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16099
16100 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
16101 CopyConstructor->setInvalidDecl();
16102 } else {
16103 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16104 ? CopyConstructor->getEndLoc()
16105 : CopyConstructor->getLocation();
16106 Sema::CompoundScopeRAII CompoundScope(*this);
16107 CopyConstructor->setBody(
16108 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16109 CopyConstructor->markUsed(Context);
16110 }
16111
16113 L->CompletedImplicitDefinition(CopyConstructor);
16114 }
16115}
16116
16118 CXXRecordDecl *ClassDecl) {
16119 assert(ClassDecl->needsImplicitMoveConstructor());
16120
16121 DeclaringSpecialMember DSM(*this, ClassDecl,
16123 if (DSM.isAlreadyBeingDeclared())
16124 return nullptr;
16125
16126 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16127 /*Qualifier=*/std::nullopt, ClassDecl,
16128 /*OwnsTag=*/false);
16129
16130 QualType ArgType = ClassType;
16132 if (AS != LangAS::Default)
16133 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
16134 ArgType = Context.getRValueReferenceType(ArgType);
16135
16137 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
16138
16139 DeclarationName Name
16140 = Context.DeclarationNames.getCXXConstructorName(
16141 Context.getCanonicalType(ClassType));
16142 SourceLocation ClassLoc = ClassDecl->getLocation();
16143 DeclarationNameInfo NameInfo(Name, ClassLoc);
16144
16145 // C++11 [class.copy]p11:
16146 // An implicitly-declared copy/move constructor is an inline public
16147 // member of its class.
16149 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16150 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16151 /*isInline=*/true,
16152 /*isImplicitlyDeclared=*/true,
16155 MoveConstructor->setAccess(AS_public);
16156 MoveConstructor->setDefaulted();
16157
16158 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
16159
16160 if (getLangOpts().CUDA)
16161 CUDA().inferTargetForImplicitSpecialMember(
16163 /* ConstRHS */ false,
16164 /* Diagnose */ false);
16165
16166 // Add the parameter to the constructor.
16168 ClassLoc, ClassLoc,
16169 /*IdentifierInfo=*/nullptr,
16170 ArgType, /*TInfo=*/nullptr,
16171 SC_None, nullptr);
16172 MoveConstructor->setParams(FromParam);
16173
16174 MoveConstructor->setTrivial(
16178 : ClassDecl->hasTrivialMoveConstructor());
16179
16180 MoveConstructor->setTrivialForCall(
16181 ClassDecl->hasAttr<TrivialABIAttr>() ||
16186 : ClassDecl->hasTrivialMoveConstructorForCall()));
16187
16188 // Note that we have declared this constructor.
16189 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16190
16191 Scope *S = getScopeForContext(ClassDecl);
16193
16198 }
16199
16200 if (S)
16202 ClassDecl->addDecl(MoveConstructor);
16203
16204 return MoveConstructor;
16205}
16206
16209 assert((MoveConstructor->isDefaulted() &&
16210 MoveConstructor->isMoveConstructor() &&
16211 !MoveConstructor->doesThisDeclarationHaveABody() &&
16212 !MoveConstructor->isDeleted()) &&
16213 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16214 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16215 return;
16216
16217 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16218 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16219
16221
16222 // The exception specification is needed because we are defining the
16223 // function.
16224 ResolveExceptionSpec(CurrentLocation,
16225 MoveConstructor->getType()->castAs<FunctionProtoType>());
16226 MarkVTableUsed(CurrentLocation, ClassDecl);
16227
16228 // Add a context note for diagnostics produced after this point.
16229 Scope.addContextNote(CurrentLocation);
16230
16231 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
16232 MoveConstructor->setInvalidDecl();
16233 } else {
16234 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16235 ? MoveConstructor->getEndLoc()
16236 : MoveConstructor->getLocation();
16237 Sema::CompoundScopeRAII CompoundScope(*this);
16238 MoveConstructor->setBody(
16239 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16240 MoveConstructor->markUsed(Context);
16241 }
16242
16244 L->CompletedImplicitDefinition(MoveConstructor);
16245 }
16246}
16247
16249 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16250}
16251
16253 SourceLocation CurrentLocation,
16254 CXXConversionDecl *Conv) {
16255 SynthesizedFunctionScope Scope(*this, Conv);
16256 assert(!Conv->getReturnType()->isUndeducedType());
16257
16258 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16259 CallingConv CC =
16260 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16261
16262 CXXRecordDecl *Lambda = Conv->getParent();
16263 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16264 FunctionDecl *Invoker =
16265 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16266 ? CallOp
16267 : Lambda->getLambdaStaticInvoker(CC);
16268
16269 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16271 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16272 if (!CallOp)
16273 return;
16274
16275 if (CallOp != Invoker) {
16277 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16278 CurrentLocation);
16279 if (!Invoker)
16280 return;
16281 }
16282 }
16283
16284 if (CallOp->isInvalidDecl())
16285 return;
16286
16287 // Mark the call operator referenced (and add to pending instantiations
16288 // if necessary).
16289 // For both the conversion and static-invoker template specializations
16290 // we construct their body's in this function, so no need to add them
16291 // to the PendingInstantiations.
16292 MarkFunctionReferenced(CurrentLocation, CallOp);
16293
16294 if (Invoker != CallOp) {
16295 // Fill in the __invoke function with a dummy implementation. IR generation
16296 // will fill in the actual details. Update its type in case it contained
16297 // an 'auto'.
16298 Invoker->markUsed(Context);
16299 Invoker->setReferenced();
16300 Invoker->setType(Conv->getReturnType()->getPointeeType());
16301 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16302 }
16303
16304 // Construct the body of the conversion function { return __invoke; }.
16305 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16306 Conv->getLocation());
16307 assert(FunctionRef && "Can't refer to __invoke function?");
16308 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16310 Conv->getLocation(), Conv->getLocation()));
16311 Conv->markUsed(Context);
16312 Conv->setReferenced();
16313
16315 L->CompletedImplicitDefinition(Conv);
16316 if (Invoker != CallOp)
16317 L->CompletedImplicitDefinition(Invoker);
16318 }
16319}
16320
16322 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16323 assert(!Conv->getParent()->isGenericLambda());
16324
16325 SynthesizedFunctionScope Scope(*this, Conv);
16326
16327 // Copy-initialize the lambda object as needed to capture it.
16328 Expr *This = ActOnCXXThis(CurrentLocation).get();
16329 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16330
16331 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16332 Conv->getLocation(),
16333 Conv, DerefThis);
16334
16335 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16336 // behavior. Note that only the general conversion function does this
16337 // (since it's unusable otherwise); in the case where we inline the
16338 // block literal, it has block literal lifetime semantics.
16339 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16340 BuildBlock = ImplicitCastExpr::Create(
16341 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16342 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16343
16344 if (BuildBlock.isInvalid()) {
16345 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16346 Conv->setInvalidDecl();
16347 return;
16348 }
16349
16350 // Create the return statement that returns the block from the conversion
16351 // function.
16352 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16353 if (Return.isInvalid()) {
16354 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16355 Conv->setInvalidDecl();
16356 return;
16357 }
16358
16359 // Set the body of the conversion function.
16360 Stmt *ReturnS = Return.get();
16362 Conv->getLocation(), Conv->getLocation()));
16363 Conv->markUsed(Context);
16364
16365 // We're done; notify the mutation listener, if any.
16367 L->CompletedImplicitDefinition(Conv);
16368 }
16369}
16370
16371/// Determine whether the given list arguments contains exactly one
16372/// "real" (non-default) argument.
16374 switch (Args.size()) {
16375 case 0:
16376 return false;
16377
16378 default:
16379 if (!Args[1]->isDefaultArgument())
16380 return false;
16381
16382 [[fallthrough]];
16383 case 1:
16384 return !Args[0]->isDefaultArgument();
16385 }
16386
16387 return false;
16388}
16389
16391 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16393 bool HadMultipleCandidates, bool IsListInitialization,
16394 bool IsStdInitListInitialization, bool RequiresZeroInit,
16395 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16396 bool Elidable = false;
16397
16398 // C++0x [class.copy]p34:
16399 // When certain criteria are met, an implementation is allowed to
16400 // omit the copy/move construction of a class object, even if the
16401 // copy/move constructor and/or destructor for the object have
16402 // side effects. [...]
16403 // - when a temporary class object that has not been bound to a
16404 // reference (12.2) would be copied/moved to a class object
16405 // with the same cv-unqualified type, the copy/move operation
16406 // can be omitted by constructing the temporary object
16407 // directly into the target of the omitted copy/move
16408 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16409 // FIXME: Converting constructors should also be accepted.
16410 // But to fix this, the logic that digs down into a CXXConstructExpr
16411 // to find the source object needs to handle it.
16412 // Right now it assumes the source object is passed directly as the
16413 // first argument.
16414 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16415 Expr *SubExpr = ExprArgs[0];
16416 // FIXME: Per above, this is also incorrect if we want to accept
16417 // converting constructors, as isTemporaryObject will
16418 // reject temporaries with different type from the
16419 // CXXRecord itself.
16420 Elidable = SubExpr->isTemporaryObject(
16422 }
16423
16424 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16425 FoundDecl, Constructor,
16426 Elidable, ExprArgs, HadMultipleCandidates,
16427 IsListInitialization,
16428 IsStdInitListInitialization, RequiresZeroInit,
16429 ConstructKind, ParenRange);
16430}
16431
16433 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16434 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16435 bool HadMultipleCandidates, bool IsListInitialization,
16436 bool IsStdInitListInitialization, bool RequiresZeroInit,
16437 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16438 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16439 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16440 // The only way to get here is if we did overload resolution to find the
16441 // shadow decl, so we don't need to worry about re-checking the trailing
16442 // requires clause.
16443 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16444 return ExprError();
16445 }
16446
16447 return BuildCXXConstructExpr(
16448 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16449 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16450 RequiresZeroInit, ConstructKind, ParenRange);
16451}
16452
16453/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16454/// including handling of its default argument expressions.
16456 SourceLocation ConstructLoc, QualType DeclInitType,
16457 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16458 bool HadMultipleCandidates, bool IsListInitialization,
16459 bool IsStdInitListInitialization, bool RequiresZeroInit,
16460 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16461 assert(declaresSameEntity(
16462 Constructor->getParent(),
16463 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16464 "given constructor for wrong type");
16465 MarkFunctionReferenced(ConstructLoc, Constructor);
16466 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16467 return ExprError();
16468
16471 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16472 HadMultipleCandidates, IsListInitialization,
16473 IsStdInitListInitialization, RequiresZeroInit,
16474 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16475 Constructor);
16476}
16477
16479 if (VD->isInvalidDecl()) return;
16480 // If initializing the variable failed, don't also diagnose problems with
16481 // the destructor, they're likely related.
16482 if (VD->getInit() && VD->getInit()->containsErrors())
16483 return;
16484
16485 ClassDecl = ClassDecl->getDefinitionOrSelf();
16486 if (ClassDecl->isInvalidDecl()) return;
16487 if (ClassDecl->hasIrrelevantDestructor()) return;
16488 if (ClassDecl->isDependentContext()) return;
16489
16490 if (VD->isNoDestroy(getASTContext()))
16491 return;
16492
16494 // The result of `LookupDestructor` might be nullptr if the destructor is
16495 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16496 // will not be selected by `CXXRecordDecl::getDestructor()`.
16497 if (!Destructor)
16498 return;
16499 // If this is an array, we'll require the destructor during initialization, so
16500 // we can skip over this. We still want to emit exit-time destructor warnings
16501 // though.
16502 if (!VD->getType()->isArrayType()) {
16505 PDiag(diag::err_access_dtor_var)
16506 << VD->getDeclName() << VD->getType());
16508 }
16509
16510 if (Destructor->isTrivial()) return;
16511
16512 // If the destructor is constexpr, check whether the variable has constant
16513 // destruction now.
16514 if (Destructor->isConstexpr()) {
16515 bool HasConstantInit = false;
16516 if (VD->getInit() && !VD->getInit()->isValueDependent())
16517 HasConstantInit = VD->evaluateValue();
16519 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16520 HasConstantInit) {
16521 Diag(VD->getLocation(),
16522 diag::err_constexpr_var_requires_const_destruction) << VD;
16523 for (const PartialDiagnosticAt &Note : Notes)
16524 Diag(Note.first, Note.second);
16525 }
16526 }
16527
16528 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16529 return;
16530
16531 // Emit warning for non-trivial dtor in global scope (a real global,
16532 // class-static, function-static).
16533 if (!VD->hasAttr<AlwaysDestroyAttr>())
16534 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16535
16536 // TODO: this should be re-enabled for static locals by !CXAAtExit
16537 if (!VD->isStaticLocal())
16538 Diag(VD->getLocation(), diag::warn_global_destructor);
16539}
16540
16542 QualType DeclInitType, MultiExprArg ArgsPtr,
16543 SourceLocation Loc,
16544 SmallVectorImpl<Expr *> &ConvertedArgs,
16545 bool AllowExplicit,
16546 bool IsListInitialization) {
16547 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16548 unsigned NumArgs = ArgsPtr.size();
16549 Expr **Args = ArgsPtr.data();
16550
16551 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16552 unsigned NumParams = Proto->getNumParams();
16553
16554 // If too few arguments are available, we'll fill in the rest with defaults.
16555 if (NumArgs < NumParams)
16556 ConvertedArgs.reserve(NumParams);
16557 else
16558 ConvertedArgs.reserve(NumArgs);
16559
16560 VariadicCallType CallType = Proto->isVariadic()
16563 SmallVector<Expr *, 8> AllArgs;
16565 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16566 CallType, AllowExplicit, IsListInitialization);
16567 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16568
16569 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16570
16571 CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),
16572 Proto, Loc);
16573
16574 return Invalid;
16575}
16576
16578 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16579 return typeAwareAllocationModeFromBool(SeenTypedOperators);
16580}
16581
16584 QualType DeallocType, SourceLocation Loc) {
16585 if (DeallocType.isNull())
16586 return nullptr;
16587
16588 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16589 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16590 return nullptr;
16591
16592 if (FnDecl->isVariadic())
16593 return nullptr;
16594
16595 unsigned NumParams = FnDecl->getNumParams();
16596 constexpr unsigned RequiredParameterCount =
16598 // A usual deallocation function has no placement parameters
16599 if (NumParams != RequiredParameterCount)
16600 return nullptr;
16601
16602 // A type aware allocation is only usual if the only dependent parameter is
16603 // the first parameter.
16604 if (llvm::any_of(FnDecl->parameters().drop_front(),
16605 [](const ParmVarDecl *ParamDecl) {
16606 return ParamDecl->getType()->isDependentType();
16607 }))
16608 return nullptr;
16609
16610 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);
16611 if (SpecializedTypeIdentity.isNull())
16612 return nullptr;
16613
16615 ArgTypes.reserve(NumParams);
16616
16617 // The first parameter to a type aware operator delete is by definition the
16618 // type-identity argument, so we explicitly set this to the target
16619 // type-identity type, the remaining usual parameters should then simply match
16620 // the type declared in the function template.
16621 ArgTypes.push_back(SpecializedTypeIdentity);
16622 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16623 ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());
16624
16626 QualType ExpectedFunctionType =
16627 Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
16630 if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,
16632 return nullptr;
16633 return Result;
16634}
16635
16636static inline bool
16638 const FunctionDecl *FnDecl) {
16639 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16640 if (isa<NamespaceDecl>(DC)) {
16641 return SemaRef.Diag(FnDecl->getLocation(),
16642 diag::err_operator_new_delete_declared_in_namespace)
16643 << FnDecl->getDeclName();
16644 }
16645
16646 if (isa<TranslationUnitDecl>(DC) &&
16647 FnDecl->getStorageClass() == SC_Static) {
16648 return SemaRef.Diag(FnDecl->getLocation(),
16649 diag::err_operator_new_delete_declared_static)
16650 << FnDecl->getDeclName();
16651 }
16652
16653 return false;
16654}
16655
16657 const PointerType *PtrTy) {
16658 auto &Ctx = SemaRef.Context;
16659 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16660 PtrQuals.removeAddressSpace();
16662 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16663}
16664
16666
16668 const FunctionDecl *FD,
16669 bool *WasMalformed) {
16670 const Decl *MalformedDecl = nullptr;
16671 if (FD->getNumParams() > 0 &&
16672 SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
16673 /*TypeArgument=*/nullptr, &MalformedDecl))
16674 return true;
16675
16676 if (!MalformedDecl)
16677 return false;
16678
16679 if (WasMalformed)
16680 *WasMalformed = true;
16681
16682 return true;
16683}
16684
16686 auto *RD = Type->getAsCXXRecordDecl();
16687 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16688 RD->getIdentifier()->isStr("destroying_delete_t");
16689}
16690
16692 const FunctionDecl *FD) {
16693 // C++ P0722:
16694 // Within a class C, a single object deallocation function with signature
16695 // (T, std::destroying_delete_t, <more params>)
16696 // is a destroying operator delete.
16697 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16698 SemaRef, FD, /*WasMalformed=*/nullptr);
16699 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16700 return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&
16701 FD->getNumParams() > DestroyingDeleteIdx &&
16702 isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
16703}
16704
16706 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16707 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16708 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16709 auto NormalizeType = [&SemaRef](QualType T) {
16710 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16711 // The operator is valid on any address space for OpenCL.
16712 // Drop address space from actual and expected result types.
16713 if (const auto PtrTy = T->template getAs<PointerType>())
16714 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16715 }
16716 return SemaRef.Context.getCanonicalType(T);
16717 };
16718
16719 const unsigned NumParams = FnDecl->getNumParams();
16720 unsigned FirstNonTypeParam = 0;
16721 bool MalformedTypeIdentity = false;
16722 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16723 SemaRef, FnDecl, &MalformedTypeIdentity);
16724 unsigned MinimumMandatoryArgumentCount = 1;
16725 unsigned SizeParameterIndex = 0;
16726 if (IsPotentiallyTypeAware) {
16727 // We don't emit this diagnosis for template instantiations as we will
16728 // have already emitted it for the original template declaration.
16729 if (!FnDecl->isTemplateInstantiation())
16730 SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);
16731
16732 if (OperatorKind == AllocationOperatorKind::New) {
16733 SizeParameterIndex = 1;
16734 MinimumMandatoryArgumentCount =
16736 } else {
16737 SizeParameterIndex = 2;
16738 MinimumMandatoryArgumentCount =
16740 }
16741 FirstNonTypeParam = 1;
16742 }
16743
16744 bool IsPotentiallyDestroyingDelete =
16746
16747 if (IsPotentiallyDestroyingDelete) {
16748 ++MinimumMandatoryArgumentCount;
16749 ++SizeParameterIndex;
16750 }
16751
16752 if (NumParams < MinimumMandatoryArgumentCount)
16753 return SemaRef.Diag(FnDecl->getLocation(),
16754 diag::err_operator_new_delete_too_few_parameters)
16755 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16756 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16757
16758 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16759 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);
16760 if (ParamDecl->hasDefaultArg())
16761 return SemaRef.Diag(FnDecl->getLocation(),
16762 diag::err_operator_new_default_arg)
16763 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16764 }
16765
16766 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16767 QualType CanResultType = NormalizeType(FnType->getReturnType());
16768 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16769 QualType CanExpectedSizeOrAddressParamType =
16770 NormalizeType(ExpectedSizeOrAddressParamType);
16771
16772 // Check that the result type is what we expect.
16773 if (CanResultType != CanExpectedResultType) {
16774 // Reject even if the type is dependent; an operator delete function is
16775 // required to have a non-dependent result type.
16776 return SemaRef.Diag(
16777 FnDecl->getLocation(),
16778 CanResultType->isDependentType()
16779 ? diag::err_operator_new_delete_dependent_result_type
16780 : diag::err_operator_new_delete_invalid_result_type)
16781 << FnDecl->getDeclName() << ExpectedResultType;
16782 }
16783
16784 // A function template must have at least 2 parameters.
16785 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16786 return SemaRef.Diag(FnDecl->getLocation(),
16787 diag::err_operator_new_delete_template_too_few_parameters)
16788 << FnDecl->getDeclName();
16789
16790 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16791 auto FallbackType) -> bool {
16792 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);
16793 if (ExpectedType.isNull()) {
16794 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
16795 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16796 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16797 << ParamDecl->getSourceRange();
16798 }
16799 CanQualType CanExpectedTy =
16800 NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));
16801 auto ActualParamType =
16802 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16803 if (ActualParamType == CanExpectedTy)
16804 return false;
16805 unsigned Diagnostic = ActualParamType->isDependentType()
16806 ? DependentParamTypeDiag
16807 : InvalidParamTypeDiag;
16808 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
16809 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16810 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16811 << FallbackType << ParamDecl->getSourceRange();
16812 };
16813
16814 // Check that the first parameter type is what we expect.
16815 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16816 return true;
16817
16818 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16819
16820 // If the first parameter type is not a type-identity we're done, otherwise
16821 // we need to ensure the size and alignment parameters have the correct type
16822 if (!IsPotentiallyTypeAware)
16823 return false;
16824
16825 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16826 return true;
16827 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16828 CanQualType StdAlignValT =
16829 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(StdAlignValTDecl)
16830 : CanQualType();
16831 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16832 return true;
16833
16835 return MalformedTypeIdentity;
16836}
16837
16838static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16839 // C++ [basic.stc.dynamic.allocation]p1:
16840 // A program is ill-formed if an allocation function is declared in a
16841 // namespace scope other than global scope or declared static in global
16842 // scope.
16843 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16844 return true;
16845
16846 CanQualType SizeTy =
16847 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16848
16849 // C++ [basic.stc.dynamic.allocation]p1:
16850 // The return type shall be void*. The first parameter shall have type
16851 // std::size_t.
16853 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
16854 SizeTy, diag::err_operator_new_dependent_param_type,
16855 diag::err_operator_new_param_type);
16856}
16857
16858static bool
16860 // C++ [basic.stc.dynamic.deallocation]p1:
16861 // A program is ill-formed if deallocation functions are declared in a
16862 // namespace scope other than global scope or declared static in global
16863 // scope.
16864 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16865 return true;
16866
16867 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16868 auto ConstructDestroyingDeleteAddressType = [&]() {
16869 assert(MD);
16870 return SemaRef.Context.getPointerType(
16871 SemaRef.Context.getCanonicalTagType(MD->getParent()));
16872 };
16873
16874 // C++ P2719: A destroying operator delete cannot be type aware
16875 // so for QoL we actually check for this explicitly by considering
16876 // an destroying-delete appropriate address type and the presence of
16877 // any parameter of type destroying_delete_t as an erroneous attempt
16878 // to declare a type aware destroying delete, rather than emitting a
16879 // pile of incorrect parameter type errors.
16881 SemaRef, MD, /*WasMalformed=*/nullptr)) {
16882 QualType AddressParamType =
16883 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
16884 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16885 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16886 // The address parameter type implies an author trying to construct a
16887 // type aware destroying delete, so we'll see if we can find a parameter
16888 // of type `std::destroying_delete_t`, and if we find it we'll report
16889 // this as being an attempt at a type aware destroying delete just stop
16890 // here. If we don't do this, the resulting incorrect parameter ordering
16891 // results in a pile mismatched argument type errors that don't explain
16892 // the core problem.
16893 for (auto Param : MD->parameters()) {
16894 if (isDestroyingDeleteT(Param->getType())) {
16895 SemaRef.Diag(MD->getLocation(),
16896 diag::err_type_aware_destroying_operator_delete)
16897 << Param->getSourceRange();
16898 return true;
16899 }
16900 }
16901 }
16902 }
16903
16904 // C++ P0722:
16905 // Within a class C, the first parameter of a destroying operator delete
16906 // shall be of type C *. The first parameter of any other deallocation
16907 // function shall be of type void *.
16908 CanQualType ExpectedAddressParamType =
16909 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
16910 ? SemaRef.Context.getPointerType(
16911 SemaRef.Context.getCanonicalTagType(MD->getParent()))
16912 : SemaRef.Context.VoidPtrTy;
16913
16914 // C++ [basic.stc.dynamic.deallocation]p2:
16915 // Each deallocation function shall return void
16917 SemaRef, FnDecl, AllocationOperatorKind::Delete,
16918 SemaRef.Context.VoidTy, ExpectedAddressParamType,
16919 diag::err_operator_delete_dependent_param_type,
16920 diag::err_operator_delete_param_type))
16921 return true;
16922
16923 // C++ P0722:
16924 // A destroying operator delete shall be a usual deallocation function.
16925 if (MD && !MD->getParent()->isDependentContext() &&
16927 if (!SemaRef.isUsualDeallocationFunction(MD)) {
16928 SemaRef.Diag(MD->getLocation(),
16929 diag::err_destroying_operator_delete_not_usual);
16930 return true;
16931 }
16932 }
16933
16934 return false;
16935}
16936
16938 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16939 "Expected an overloaded operator declaration");
16940
16942
16943 // C++ [over.oper]p5:
16944 // The allocation and deallocation functions, operator new,
16945 // operator new[], operator delete and operator delete[], are
16946 // described completely in 3.7.3. The attributes and restrictions
16947 // found in the rest of this subclause do not apply to them unless
16948 // explicitly stated in 3.7.3.
16949 if (Op == OO_Delete || Op == OO_Array_Delete)
16950 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16951
16952 if (Op == OO_New || Op == OO_Array_New)
16953 return CheckOperatorNewDeclaration(*this, FnDecl);
16954
16955 // C++ [over.oper]p7:
16956 // An operator function shall either be a member function or
16957 // be a non-member function and have at least one parameter
16958 // whose type is a class, a reference to a class, an enumeration,
16959 // or a reference to an enumeration.
16960 // Note: Before C++23, a member function could not be static. The only member
16961 // function allowed to be static is the call operator function.
16962 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16963 if (MethodDecl->isStatic()) {
16964 if (Op == OO_Call || Op == OO_Subscript)
16965 Diag(FnDecl->getLocation(),
16966 (LangOpts.CPlusPlus23
16967 ? diag::warn_cxx20_compat_operator_overload_static
16968 : diag::ext_operator_overload_static))
16969 << FnDecl;
16970 else
16971 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16972 << FnDecl;
16973 }
16974 } else {
16975 bool ClassOrEnumParam = false;
16976 for (auto *Param : FnDecl->parameters()) {
16977 QualType ParamType = Param->getType().getNonReferenceType();
16978 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16979 ParamType->isEnumeralType()) {
16980 ClassOrEnumParam = true;
16981 break;
16982 }
16983 }
16984
16985 if (!ClassOrEnumParam)
16986 return Diag(FnDecl->getLocation(),
16987 diag::err_operator_overload_needs_class_or_enum)
16988 << FnDecl->getDeclName();
16989 }
16990
16991 // C++ [over.oper]p8:
16992 // An operator function cannot have default arguments (8.3.6),
16993 // except where explicitly stated below.
16994 //
16995 // Only the function-call operator (C++ [over.call]p1) and the subscript
16996 // operator (CWG2507) allow default arguments.
16997 if (Op != OO_Call) {
16998 ParmVarDecl *FirstDefaultedParam = nullptr;
16999 for (auto *Param : FnDecl->parameters()) {
17000 if (Param->hasDefaultArg()) {
17001 FirstDefaultedParam = Param;
17002 break;
17003 }
17004 }
17005 if (FirstDefaultedParam) {
17006 if (Op == OO_Subscript) {
17007 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17008 ? diag::ext_subscript_overload
17009 : diag::error_subscript_overload)
17010 << FnDecl->getDeclName() << 1
17011 << FirstDefaultedParam->getDefaultArgRange();
17012 } else {
17013 return Diag(FirstDefaultedParam->getLocation(),
17014 diag::err_operator_overload_default_arg)
17015 << FnDecl->getDeclName()
17016 << FirstDefaultedParam->getDefaultArgRange();
17017 }
17018 }
17019 }
17020
17021 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17022 { false, false, false }
17023#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17024 , { Unary, Binary, MemberOnly }
17025#include "clang/Basic/OperatorKinds.def"
17026 };
17027
17028 bool CanBeUnaryOperator = OperatorUses[Op][0];
17029 bool CanBeBinaryOperator = OperatorUses[Op][1];
17030 bool MustBeMemberOperator = OperatorUses[Op][2];
17031
17032 // C++ [over.oper]p8:
17033 // [...] Operator functions cannot have more or fewer parameters
17034 // than the number required for the corresponding operator, as
17035 // described in the rest of this subclause.
17036 unsigned NumParams = FnDecl->getNumParams() +
17037 (isa<CXXMethodDecl>(FnDecl) &&
17039 ? 1
17040 : 0);
17041 if (Op != OO_Call && Op != OO_Subscript &&
17042 ((NumParams == 1 && !CanBeUnaryOperator) ||
17043 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17044 (NumParams > 2))) {
17045 // We have the wrong number of parameters.
17046 unsigned ErrorKind;
17047 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17048 ErrorKind = 2; // 2 -> unary or binary.
17049 } else if (CanBeUnaryOperator) {
17050 ErrorKind = 0; // 0 -> unary
17051 } else {
17052 assert(CanBeBinaryOperator &&
17053 "All non-call overloaded operators are unary or binary!");
17054 ErrorKind = 1; // 1 -> binary
17055 }
17056 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
17057 << FnDecl->getDeclName() << NumParams << ErrorKind;
17058 }
17059
17060 if (Op == OO_Subscript && NumParams != 2) {
17061 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17062 ? diag::ext_subscript_overload
17063 : diag::error_subscript_overload)
17064 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17065 }
17066
17067 // Overloaded operators other than operator() and operator[] cannot be
17068 // variadic.
17069 if (Op != OO_Call &&
17070 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17071 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
17072 << FnDecl->getDeclName();
17073 }
17074
17075 // Some operators must be member functions.
17076 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
17077 return Diag(FnDecl->getLocation(),
17078 diag::err_operator_overload_must_be_member)
17079 << FnDecl->getDeclName();
17080 }
17081
17082 // C++ [over.inc]p1:
17083 // The user-defined function called operator++ implements the
17084 // prefix and postfix ++ operator. If this function is a member
17085 // function with no parameters, or a non-member function with one
17086 // parameter of class or enumeration type, it defines the prefix
17087 // increment operator ++ for objects of that type. If the function
17088 // is a member function with one parameter (which shall be of type
17089 // int) or a non-member function with two parameters (the second
17090 // of which shall be of type int), it defines the postfix
17091 // increment operator ++ for objects of that type.
17092 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17093 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
17094 QualType ParamType = LastParam->getType();
17095
17096 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
17097 !ParamType->isDependentType())
17098 return Diag(LastParam->getLocation(),
17099 diag::err_operator_overload_post_incdec_must_be_int)
17100 << LastParam->getType() << (Op == OO_MinusMinus);
17101 }
17102
17103 return false;
17104}
17105
17106static bool
17108 FunctionTemplateDecl *TpDecl) {
17109 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17110
17111 // Must have one or two template parameters.
17112 if (TemplateParams->size() == 1) {
17113 NonTypeTemplateParmDecl *PmDecl =
17114 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
17115
17116 // The template parameter must be a char parameter pack.
17117 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17118 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
17119 return false;
17120
17121 // C++20 [over.literal]p5:
17122 // A string literal operator template is a literal operator template
17123 // whose template-parameter-list comprises a single non-type
17124 // template-parameter of class type.
17125 //
17126 // As a DR resolution, we also allow placeholders for deduced class
17127 // template specializations.
17128 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17129 !PmDecl->isTemplateParameterPack() &&
17130 (PmDecl->getType()->isRecordType() ||
17131 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17132 return false;
17133 } else if (TemplateParams->size() == 2) {
17134 TemplateTypeParmDecl *PmType =
17135 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
17136 NonTypeTemplateParmDecl *PmArgs =
17137 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
17138
17139 // The second template parameter must be a parameter pack with the
17140 // first template parameter as its type.
17141 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17142 PmArgs->isTemplateParameterPack()) {
17143 if (const auto *TArgs =
17144 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17145 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17146 TArgs->getIndex() == PmType->getIndex()) {
17147 if (!SemaRef.inTemplateInstantiation())
17148 SemaRef.Diag(TpDecl->getLocation(),
17149 diag::ext_string_literal_operator_template);
17150 return false;
17151 }
17152 }
17153 }
17154
17155 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17156 diag::err_literal_operator_template)
17157 << TpDecl->getTemplateParameters()->getSourceRange();
17158 return true;
17159}
17160
17162 if (isa<CXXMethodDecl>(FnDecl)) {
17163 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
17164 << FnDecl->getDeclName();
17165 return true;
17166 }
17167
17168 if (FnDecl->isExternC()) {
17169 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
17170 if (const LinkageSpecDecl *LSD =
17171 FnDecl->getDeclContext()->getExternCContext())
17172 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
17173 return true;
17174 }
17175
17176 // This might be the definition of a literal operator template.
17178
17179 // This might be a specialization of a literal operator template.
17180 if (!TpDecl)
17181 TpDecl = FnDecl->getPrimaryTemplate();
17182
17183 // template <char...> type operator "" name() and
17184 // template <class T, T...> type operator "" name() are the only valid
17185 // template signatures, and the only valid signatures with no parameters.
17186 //
17187 // C++20 also allows template <SomeClass T> type operator "" name().
17188 if (TpDecl) {
17189 if (FnDecl->param_size() != 0) {
17190 Diag(FnDecl->getLocation(),
17191 diag::err_literal_operator_template_with_params);
17192 return true;
17193 }
17194
17196 return true;
17197
17198 } else if (FnDecl->param_size() == 1) {
17199 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
17200
17201 QualType ParamType = Param->getType().getUnqualifiedType();
17202
17203 // Only unsigned long long int, long double, any character type, and const
17204 // char * are allowed as the only parameters.
17205 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
17206 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
17207 Context.hasSameType(ParamType, Context.CharTy) ||
17208 Context.hasSameType(ParamType, Context.WideCharTy) ||
17209 Context.hasSameType(ParamType, Context.Char8Ty) ||
17210 Context.hasSameType(ParamType, Context.Char16Ty) ||
17211 Context.hasSameType(ParamType, Context.Char32Ty)) {
17212 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17213 QualType InnerType = Ptr->getPointeeType();
17214
17215 // Pointer parameter must be a const char *.
17216 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17217 Context.CharTy) &&
17218 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17219 Diag(Param->getSourceRange().getBegin(),
17220 diag::err_literal_operator_param)
17221 << ParamType << "'const char *'" << Param->getSourceRange();
17222 return true;
17223 }
17224
17225 } else if (ParamType->isRealFloatingType()) {
17226 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17227 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17228 return true;
17229
17230 } else if (ParamType->isIntegerType()) {
17231 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17232 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17233 return true;
17234
17235 } else {
17236 Diag(Param->getSourceRange().getBegin(),
17237 diag::err_literal_operator_invalid_param)
17238 << ParamType << Param->getSourceRange();
17239 return true;
17240 }
17241
17242 } else if (FnDecl->param_size() == 2) {
17243 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17244
17245 // First, verify that the first parameter is correct.
17246
17247 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17248
17249 // Two parameter function must have a pointer to const as a
17250 // first parameter; let's strip those qualifiers.
17251 const PointerType *PT = FirstParamType->getAs<PointerType>();
17252
17253 if (!PT) {
17254 Diag((*Param)->getSourceRange().getBegin(),
17255 diag::err_literal_operator_param)
17256 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17257 return true;
17258 }
17259
17260 QualType PointeeType = PT->getPointeeType();
17261 // First parameter must be const
17262 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17263 Diag((*Param)->getSourceRange().getBegin(),
17264 diag::err_literal_operator_param)
17265 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17266 return true;
17267 }
17268
17269 QualType InnerType = PointeeType.getUnqualifiedType();
17270 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17271 // const char32_t* are allowed as the first parameter to a two-parameter
17272 // function
17273 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17274 Context.hasSameType(InnerType, Context.WideCharTy) ||
17275 Context.hasSameType(InnerType, Context.Char8Ty) ||
17276 Context.hasSameType(InnerType, Context.Char16Ty) ||
17277 Context.hasSameType(InnerType, Context.Char32Ty))) {
17278 Diag((*Param)->getSourceRange().getBegin(),
17279 diag::err_literal_operator_param)
17280 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17281 return true;
17282 }
17283
17284 // Move on to the second and final parameter.
17285 ++Param;
17286
17287 // The second parameter must be a std::size_t.
17288 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17289 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
17290 Diag((*Param)->getSourceRange().getBegin(),
17291 diag::err_literal_operator_param)
17292 << SecondParamType << Context.getSizeType()
17293 << (*Param)->getSourceRange();
17294 return true;
17295 }
17296 } else {
17297 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17298 return true;
17299 }
17300
17301 // Parameters are good.
17302
17303 // A parameter-declaration-clause containing a default argument is not
17304 // equivalent to any of the permitted forms.
17305 for (auto *Param : FnDecl->parameters()) {
17306 if (Param->hasDefaultArg()) {
17307 Diag(Param->getDefaultArgRange().getBegin(),
17308 diag::err_literal_operator_default_argument)
17309 << Param->getDefaultArgRange();
17310 break;
17311 }
17312 }
17313
17314 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17317 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
17318 // C++23 [usrlit.suffix]p1:
17319 // Literal suffix identifiers that do not start with an underscore are
17320 // reserved for future standardization. Literal suffix identifiers that
17321 // contain a double underscore __ are reserved for use by C++
17322 // implementations.
17323 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17324 << static_cast<int>(Status)
17326 }
17327
17328 return false;
17329}
17330
17332 Expr *LangStr,
17333 SourceLocation LBraceLoc) {
17334 StringLiteral *Lit = cast<StringLiteral>(LangStr);
17335 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17336
17337 StringRef Lang = Lit->getString();
17339 if (Lang == "C")
17341 else if (Lang == "C++")
17343 else {
17344 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17345 << LangStr->getSourceRange();
17346 return nullptr;
17347 }
17348
17349 // FIXME: Add all the various semantics of linkage specifications
17350
17352 LangStr->getExprLoc(), Language,
17353 LBraceLoc.isValid());
17354
17355 /// C++ [module.unit]p7.2.3
17356 /// - Otherwise, if the declaration
17357 /// - ...
17358 /// - ...
17359 /// - appears within a linkage-specification,
17360 /// it is attached to the global module.
17361 ///
17362 /// If the declaration is already in global module fragment, we don't
17363 /// need to attach it again.
17364 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17365 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
17366 D->setLocalOwningModule(GlobalModule);
17367 }
17368
17369 CurContext->addDecl(D);
17370 PushDeclContext(S, D);
17371 return D;
17372}
17373
17375 Decl *LinkageSpec,
17376 SourceLocation RBraceLoc) {
17377 if (RBraceLoc.isValid()) {
17378 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
17379 LSDecl->setRBraceLoc(RBraceLoc);
17380 }
17381
17382 // If the current module doesn't has Parent, it implies that the
17383 // LinkageSpec isn't in the module created by itself. So we don't
17384 // need to pop it.
17385 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17386 getCurrentModule()->isImplicitGlobalModule() &&
17387 getCurrentModule()->Parent)
17388 PopImplicitGlobalModuleFragment();
17389
17391 return LinkageSpec;
17392}
17393
17395 const ParsedAttributesView &AttrList,
17396 SourceLocation SemiLoc) {
17397 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
17398 // Attribute declarations appertain to empty declaration so we handle
17399 // them here.
17400 ProcessDeclAttributeList(S, ED, AttrList);
17401
17402 CurContext->addDecl(ED);
17403 return ED;
17404}
17405
17407 SourceLocation StartLoc,
17408 SourceLocation Loc,
17409 const IdentifierInfo *Name) {
17410 bool Invalid = false;
17411 QualType ExDeclType = TInfo->getType();
17412
17413 // Arrays and functions decay.
17414 if (ExDeclType->isArrayType())
17415 ExDeclType = Context.getArrayDecayedType(ExDeclType);
17416 else if (ExDeclType->isFunctionType())
17417 ExDeclType = Context.getPointerType(ExDeclType);
17418
17419 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17420 // The exception-declaration shall not denote a pointer or reference to an
17421 // incomplete type, other than [cv] void*.
17422 // N2844 forbids rvalue references.
17423 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17424 Diag(Loc, diag::err_catch_rvalue_ref);
17425 Invalid = true;
17426 }
17427
17428 if (ExDeclType->isVariablyModifiedType()) {
17429 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17430 Invalid = true;
17431 }
17432
17433 QualType BaseType = ExDeclType;
17434 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17435 unsigned DK = diag::err_catch_incomplete;
17436 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17437 BaseType = Ptr->getPointeeType();
17438 Mode = 1;
17439 DK = diag::err_catch_incomplete_ptr;
17440 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17441 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17442 BaseType = Ref->getPointeeType();
17443 Mode = 2;
17444 DK = diag::err_catch_incomplete_ref;
17445 }
17446 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17447 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17448 Invalid = true;
17449
17450 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17451 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17452 Invalid = true;
17453 }
17454
17455 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17456 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17457 Invalid = true;
17458 }
17459
17460 if (!Invalid && !ExDeclType->isDependentType() &&
17461 RequireNonAbstractType(Loc, ExDeclType,
17462 diag::err_abstract_type_in_decl,
17464 Invalid = true;
17465
17466 // Only the non-fragile NeXT runtime currently supports C++ catches
17467 // of ObjC types, and no runtime supports catching ObjC types by value.
17468 if (!Invalid && getLangOpts().ObjC) {
17469 QualType T = ExDeclType;
17470 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17471 T = RT->getPointeeType();
17472
17473 if (T->isObjCObjectType()) {
17474 Diag(Loc, diag::err_objc_object_catch);
17475 Invalid = true;
17476 } else if (T->isObjCObjectPointerType()) {
17477 // FIXME: should this be a test for macosx-fragile specifically?
17479 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17480 }
17481 }
17482
17483 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17484 ExDeclType, TInfo, SC_None);
17485 ExDecl->setExceptionVariable(true);
17486
17487 // In ARC, infer 'retaining' for variables of retainable type.
17488 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17489 Invalid = true;
17490
17491 if (!Invalid && !ExDeclType->isDependentType()) {
17492 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17493 // Insulate this from anything else we might currently be parsing.
17496
17497 // C++ [except.handle]p16:
17498 // The object declared in an exception-declaration or, if the
17499 // exception-declaration does not specify a name, a temporary (12.2) is
17500 // copy-initialized (8.5) from the exception object. [...]
17501 // The object is destroyed when the handler exits, after the destruction
17502 // of any automatic objects initialized within the handler.
17503 //
17504 // We just pretend to initialize the object with itself, then make sure
17505 // it can be destroyed later.
17506 QualType initType = Context.getExceptionObjectType(ExDeclType);
17507
17508 InitializedEntity entity =
17510 InitializationKind initKind =
17512
17513 Expr *opaqueValue =
17514 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17515 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17516 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17517 if (result.isInvalid())
17518 Invalid = true;
17519 else {
17520 // If the constructor used was non-trivial, set this as the
17521 // "initializer".
17522 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17523 if (!construct->getConstructor()->isTrivial()) {
17524 Expr *init = MaybeCreateExprWithCleanups(construct);
17525 ExDecl->setInit(init);
17526 }
17527
17528 // And make sure it's destructable.
17529 FinalizeVarWithDestructor(ExDecl, ClassDecl);
17530 }
17531 }
17532 }
17533
17534 if (Invalid)
17535 ExDecl->setInvalidDecl();
17536
17537 return ExDecl;
17538}
17539
17542 bool Invalid = D.isInvalidType();
17543
17544 // Check for unexpanded parameter packs.
17547 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17548 D.getIdentifierLoc());
17549 Invalid = true;
17550 }
17551
17552 const IdentifierInfo *II = D.getIdentifier();
17553 if (NamedDecl *PrevDecl =
17556 // The scope should be freshly made just for us. There is just no way
17557 // it contains any previous declaration, except for function parameters in
17558 // a function-try-block's catch statement.
17559 assert(!S->isDeclScope(PrevDecl));
17560 if (isDeclInScope(PrevDecl, CurContext, S)) {
17561 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17562 << D.getIdentifier();
17563 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17564 Invalid = true;
17565 } else if (PrevDecl->isTemplateParameter())
17566 // Maybe we will complain about the shadowed template parameter.
17568 }
17569
17570 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17571 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17572 << D.getCXXScopeSpec().getRange();
17573 Invalid = true;
17574 }
17575
17577 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17578 if (Invalid)
17579 ExDecl->setInvalidDecl();
17580
17581 // Add the exception declaration into this scope.
17582 if (II)
17583 PushOnScopeChains(ExDecl, S);
17584 else
17585 CurContext->addDecl(ExDecl);
17586
17587 ProcessDeclAttributes(S, ExDecl, D);
17588 return ExDecl;
17589}
17590
17592 Expr *AssertExpr,
17593 Expr *AssertMessageExpr,
17594 SourceLocation RParenLoc) {
17596 return nullptr;
17597
17598 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17599 AssertMessageExpr, RParenLoc, false);
17600}
17601
17602static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17603 switch (BTK) {
17604 case BuiltinType::Char_S:
17605 case BuiltinType::Char_U:
17606 break;
17607 case BuiltinType::Char8:
17608 OS << "u8";
17609 break;
17610 case BuiltinType::Char16:
17611 OS << 'u';
17612 break;
17613 case BuiltinType::Char32:
17614 OS << 'U';
17615 break;
17616 case BuiltinType::WChar_S:
17617 case BuiltinType::WChar_U:
17618 OS << 'L';
17619 break;
17620 default:
17621 llvm_unreachable("Non-character type");
17622 }
17623}
17624
17625/// Convert character's value, interpreted as a code unit, to a string.
17626/// The value needs to be zero-extended to 32-bits.
17627/// FIXME: This assumes Unicode literal encodings
17629 unsigned TyWidth,
17630 SmallVectorImpl<char> &Str) {
17631 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17632 char *Ptr = Arr;
17633 BuiltinType::Kind K = BTy->getKind();
17634 llvm::raw_svector_ostream OS(Str);
17635
17636 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17637 // other types.
17638 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17639 K == BuiltinType::Char8 || Value <= 0x7F) {
17640 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17641 if (!Escaped.empty())
17642 EscapeStringForDiagnostic(Escaped, Str);
17643 else
17644 OS << static_cast<char>(Value);
17645 return;
17646 }
17647
17648 switch (K) {
17649 case BuiltinType::Char16:
17650 case BuiltinType::Char32:
17651 case BuiltinType::WChar_S:
17652 case BuiltinType::WChar_U: {
17653 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17654 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17655 else
17656 OS << "\\x"
17657 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17658 break;
17659 }
17660 default:
17661 llvm_unreachable("Non-character type is passed");
17662 }
17663}
17664
17665/// Convert \V to a string we can present to the user in a diagnostic
17666/// \T is the type of the expression that has been evaluated into \V
17669 ASTContext &Context) {
17670 if (!V.hasValue())
17671 return false;
17672
17673 switch (V.getKind()) {
17675 if (T->isBooleanType()) {
17676 // Bools are reduced to ints during evaluation, but for
17677 // diagnostic purposes we want to print them as
17678 // true or false.
17679 int64_t BoolValue = V.getInt().getExtValue();
17680 assert((BoolValue == 0 || BoolValue == 1) &&
17681 "Bool type, but value is not 0 or 1");
17682 llvm::raw_svector_ostream OS(Str);
17683 OS << (BoolValue ? "true" : "false");
17684 } else {
17685 llvm::raw_svector_ostream OS(Str);
17686 // Same is true for chars.
17687 // We want to print the character representation for textual types
17688 const auto *BTy = T->getAs<BuiltinType>();
17689 if (BTy) {
17690 switch (BTy->getKind()) {
17691 case BuiltinType::Char_S:
17692 case BuiltinType::Char_U:
17693 case BuiltinType::Char8:
17694 case BuiltinType::Char16:
17695 case BuiltinType::Char32:
17696 case BuiltinType::WChar_S:
17697 case BuiltinType::WChar_U: {
17698 unsigned TyWidth = Context.getIntWidth(T);
17699 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17700 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17701 WriteCharTypePrefix(BTy->getKind(), OS);
17702 OS << '\'';
17703 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17704 OS << "' (0x"
17705 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17706 /*Upper=*/true)
17707 << ", " << V.getInt() << ')';
17708 return true;
17709 }
17710 default:
17711 break;
17712 }
17713 }
17714 V.getInt().toString(Str);
17715 }
17716
17717 break;
17718
17720 V.getFloat().toString(Str);
17721 break;
17722
17724 if (V.isNullPointer()) {
17725 llvm::raw_svector_ostream OS(Str);
17726 OS << "nullptr";
17727 } else
17728 return false;
17729 break;
17730
17732 llvm::raw_svector_ostream OS(Str);
17733 OS << '(';
17734 V.getComplexFloatReal().toString(Str);
17735 OS << " + ";
17736 V.getComplexFloatImag().toString(Str);
17737 OS << "i)";
17738 } break;
17739
17741 llvm::raw_svector_ostream OS(Str);
17742 OS << '(';
17743 V.getComplexIntReal().toString(Str);
17744 OS << " + ";
17745 V.getComplexIntImag().toString(Str);
17746 OS << "i)";
17747 } break;
17748
17749 default:
17750 return false;
17751 }
17752
17753 return true;
17754}
17755
17756/// Some Expression types are not useful to print notes about,
17757/// e.g. literals and values that have already been expanded
17758/// before such as int-valued template parameters.
17759static bool UsefulToPrintExpr(const Expr *E) {
17760 E = E->IgnoreParenImpCasts();
17761 // Literals are pretty easy for humans to understand.
17764 return false;
17765
17766 // These have been substituted from template parameters
17767 // and appear as literals in the static assert error.
17769 return false;
17770
17771 // -5 is also simple to understand.
17772 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17773 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17774
17775 // Only print nested arithmetic operators.
17776 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17777 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17778 BO->isBitwiseOp());
17779
17780 return true;
17781}
17782
17784 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17785 Op && Op->getOpcode() != BO_LOr) {
17786 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17787 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17788
17789 // Ignore comparisons of boolean expressions with a boolean literal.
17790 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17791 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17792 return;
17793
17794 // Don't print obvious expressions.
17795 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17796 return;
17797
17798 struct {
17799 const clang::Expr *Cond;
17801 SmallString<12> ValueString;
17802 bool Print;
17803 } DiagSides[2] = {{LHS, Expr::EvalResult(), {}, false},
17804 {RHS, Expr::EvalResult(), {}, false}};
17805 for (auto &DiagSide : DiagSides) {
17806 const Expr *Side = DiagSide.Cond;
17807
17808 Side->EvaluateAsRValue(DiagSide.Result, Context, true);
17809
17810 DiagSide.Print = ConvertAPValueToString(
17811 DiagSide.Result.Val, Side->getType(), DiagSide.ValueString, Context);
17812 }
17813 if (DiagSides[0].Print && DiagSides[1].Print) {
17814 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17815 << DiagSides[0].ValueString << Op->getOpcodeStr()
17816 << DiagSides[1].ValueString << Op->getSourceRange();
17817 }
17818 } else {
17820 }
17821}
17822
17823template <typename ResultType>
17824static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17825 ResultType &Result, ASTContext &Ctx,
17827 bool ErrorOnInvalidMessage) {
17828
17829 assert(Message);
17830 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17831 "can't evaluate a dependant static assert message");
17832
17833 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17834 assert(SL->isUnevaluated() && "expected an unevaluated string");
17835 if constexpr (std::is_same_v<APValue, ResultType>) {
17836 Result =
17837 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17838 const ConstantArrayType *CAT =
17839 SemaRef.getASTContext().getAsConstantArrayType(SL->getType());
17840 assert(CAT && "string literal isn't an array");
17841 QualType CharType = CAT->getElementType();
17842 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),
17843 CharType->isUnsignedIntegerType());
17844 for (unsigned I = 0; I < SL->getLength(); I++) {
17845 Value = SL->getCodeUnit(I);
17846 Result.getArrayInitializedElt(I) = APValue(Value);
17847 }
17848 } else {
17849 Result.assign(SL->getString().begin(), SL->getString().end());
17850 }
17851 return true;
17852 }
17853
17854 SourceLocation Loc = Message->getBeginLoc();
17855 QualType T = Message->getType().getNonReferenceType();
17856 auto *RD = T->getAsCXXRecordDecl();
17857 if (!RD) {
17858 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
17859 return false;
17860 }
17861
17862 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17864 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17865 SemaRef.LookupQualifiedName(MemberLookup, RD);
17866 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17868 if (MemberLookup.empty())
17869 return std::nullopt;
17870 return std::move(MemberLookup);
17871 };
17872
17873 std::optional<LookupResult> SizeMember = FindMember("size");
17874 std::optional<LookupResult> DataMember = FindMember("data");
17875 if (!SizeMember || !DataMember) {
17876 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
17877 << EvalContext
17878 << ((!SizeMember && !DataMember) ? 2
17879 : !SizeMember ? 0
17880 : 1);
17881 return false;
17882 }
17883
17884 auto BuildExpr = [&](LookupResult &LR) {
17886 Message, Message->getType(), Message->getBeginLoc(), false,
17887 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17888 if (Res.isInvalid())
17889 return ExprError();
17890 Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,
17891 false, true);
17892 if (Res.isInvalid())
17893 return ExprError();
17894 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17895 return ExprError();
17896 return SemaRef.TemporaryMaterializationConversion(Res.get());
17897 };
17898
17899 ExprResult SizeE = BuildExpr(*SizeMember);
17900 ExprResult DataE = BuildExpr(*DataMember);
17901
17902 QualType SizeT = SemaRef.Context.getSizeType();
17903 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17904 SemaRef.Context.getConstType(SemaRef.Context.CharTy));
17905
17906 ExprResult EvaluatedSize =
17907 SizeE.isInvalid()
17908 ? ExprError()
17911 if (EvaluatedSize.isInvalid()) {
17912 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17913 << EvalContext << /*size*/ 0;
17914 return false;
17915 }
17916
17917 ExprResult EvaluatedData =
17918 DataE.isInvalid()
17919 ? ExprError()
17921 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);
17922 if (EvaluatedData.isInvalid()) {
17923 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17924 << EvalContext << /*data*/ 1;
17925 return false;
17926 }
17927
17928 if (!ErrorOnInvalidMessage &&
17929 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
17930 return true;
17931
17932 Expr::EvalResult Status;
17934 Status.Diag = &Notes;
17935 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17936 EvaluatedData.get(), Ctx, Status) ||
17937 !Notes.empty()) {
17938 SemaRef.Diag(Message->getBeginLoc(),
17939 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17940 : diag::warn_user_defined_msg_constexpr)
17941 << EvalContext;
17942 for (const auto &Note : Notes)
17943 SemaRef.Diag(Note.first, Note.second);
17944 return !ErrorOnInvalidMessage;
17945 }
17946 return true;
17947}
17948
17950 StringEvaluationContext EvalContext,
17951 bool ErrorOnInvalidMessage) {
17952 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17953 ErrorOnInvalidMessage);
17954}
17955
17956bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17957 StringEvaluationContext EvalContext,
17958 bool ErrorOnInvalidMessage) {
17959 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17960 ErrorOnInvalidMessage);
17961}
17962
17964 Expr *AssertExpr, Expr *AssertMessage,
17965 SourceLocation RParenLoc,
17966 bool Failed) {
17967 assert(AssertExpr != nullptr && "Expected non-null condition");
17968 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17969 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17970 !AssertMessage->isValueDependent())) &&
17971 !Failed) {
17972 // In a static_assert-declaration, the constant-expression shall be a
17973 // constant expression that can be contextually converted to bool.
17974 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17975 if (Converted.isInvalid())
17976 Failed = true;
17977
17978 ExprResult FullAssertExpr =
17979 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17980 /*DiscardedValue*/ false,
17981 /*IsConstexpr*/ true);
17982 if (FullAssertExpr.isInvalid())
17983 Failed = true;
17984 else
17985 AssertExpr = FullAssertExpr.get();
17986
17987 llvm::APSInt Cond;
17988 Expr *BaseExpr = AssertExpr;
17990
17991 if (!getLangOpts().CPlusPlus) {
17992 // In C mode, allow folding as an extension for better compatibility with
17993 // C++ in terms of expressions like static_assert("test") or
17994 // static_assert(nullptr).
17995 FoldKind = AllowFoldKind::Allow;
17996 }
17997
17998 if (!Failed && VerifyIntegerConstantExpression(
17999 BaseExpr, &Cond,
18000 diag::err_static_assert_expression_is_not_constant,
18001 FoldKind).isInvalid())
18002 Failed = true;
18003
18004 // If the static_assert passes, only verify that
18005 // the message is grammatically valid without evaluating it.
18006 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18007 std::string Str;
18008 EvaluateAsString(AssertMessage, Str, Context,
18010 /*ErrorOnInvalidMessage=*/false);
18011 }
18012
18013 // CWG2518
18014 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18015 // template definition, the declaration has no effect.
18016 bool InTemplateDefinition =
18017 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18018
18019 if (!Failed && !Cond && !InTemplateDefinition) {
18020 SmallString<256> MsgBuffer;
18021 llvm::raw_svector_ostream Msg(MsgBuffer);
18022 bool HasMessage = AssertMessage;
18023 if (AssertMessage) {
18024 std::string Str;
18025 HasMessage = EvaluateAsString(AssertMessage, Str, Context,
18027 /*ErrorOnInvalidMessage=*/true) ||
18028 !Str.empty();
18029 Msg << Str;
18030 }
18031 Expr *InnerCond = nullptr;
18032 std::string InnerCondDescription;
18033 std::tie(InnerCond, InnerCondDescription) =
18034 findFailedBooleanCondition(Converted.get());
18035 if (const auto *ConceptIDExpr =
18036 dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {
18037 const ASTConstraintSatisfaction &Satisfaction =
18038 ConceptIDExpr->getSatisfaction();
18039 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18040 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18041 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18042 // Drill down into concept specialization expressions to see why they
18043 // weren't satisfied.
18044 DiagnoseUnsatisfiedConstraint(ConceptIDExpr);
18045 }
18046 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&
18047 !isa<IntegerLiteral>(InnerCond)) {
18048 Diag(InnerCond->getBeginLoc(),
18049 diag::err_static_assert_requirement_failed)
18050 << InnerCondDescription << !HasMessage << Msg.str()
18051 << InnerCond->getSourceRange();
18052 DiagnoseStaticAssertDetails(InnerCond);
18053 } else {
18054 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18055 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18057 }
18058 Failed = true;
18059 }
18060 } else {
18061 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
18062 /*DiscardedValue*/false,
18063 /*IsConstexpr*/true);
18064 if (FullAssertExpr.isInvalid())
18065 Failed = true;
18066 else
18067 AssertExpr = FullAssertExpr.get();
18068 }
18069
18071 AssertExpr, AssertMessage, RParenLoc,
18072 Failed);
18073
18074 CurContext->addDecl(Decl);
18075 return Decl;
18076}
18077
18079 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18080 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18081 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18082 MultiTemplateParamsArg TempParamLists) {
18084
18085 bool IsMemberSpecialization = false;
18086 bool Invalid = false;
18087
18088 if (TemplateParameterList *TemplateParams =
18090 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
18091 IsMemberSpecialization, Invalid)) {
18092 if (TemplateParams->size() > 0) {
18093 // This is a declaration of a class template.
18094 if (Invalid)
18095 return true;
18096
18097 return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,
18098 Name, NameLoc, Attr, TemplateParams, AS_public,
18099 /*ModulePrivateLoc=*/SourceLocation(),
18100 FriendLoc, TempParamLists.size() - 1,
18101 TempParamLists.data(), IsMemberSpecialization)
18102 .get();
18103 } else {
18104 // The "template<>" header is extraneous.
18105 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18106 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18107 }
18108 }
18109
18110 if (Invalid) return true;
18111
18112 bool isAllExplicitSpecializations =
18113 llvm::all_of(TempParamLists, [](const TemplateParameterList *List) {
18114 return List->size() == 0;
18115 });
18116
18117 // FIXME: don't ignore attributes.
18118
18119 // If it's explicit specializations all the way down, just forget
18120 // about the template header and build an appropriate non-templated
18121 // friend. TODO: for source fidelity, remember the headers.
18123 if (isAllExplicitSpecializations) {
18124 if (SS.isEmpty()) {
18125 bool Owned = false;
18126 bool IsDependent = false;
18127 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
18128 Attr, AS_public,
18129 /*ModulePrivateLoc=*/SourceLocation(),
18130 MultiTemplateParamsArg(), Owned, IsDependent,
18131 /*ScopedEnumKWLoc=*/SourceLocation(),
18132 /*ScopedEnumUsesClassTag=*/false,
18133 /*UnderlyingType=*/TypeResult(),
18134 /*IsTypeSpecifier=*/false,
18135 /*IsTemplateParamOrArg=*/false,
18136 /*OOK=*/OffsetOfKind::Outside);
18137 }
18138
18139 TypeSourceInfo *TSI = nullptr;
18142 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name,
18143 NameLoc, &TSI, /*DeducedTSTContext=*/true);
18144 if (T.isNull())
18145 return true;
18146
18148 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18149 EllipsisLoc, TempParamLists);
18150 Friend->setAccess(AS_public);
18151 CurContext->addDecl(Friend);
18152 return Friend;
18153 }
18154
18155 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18156
18157 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
18158 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
18159 // shall not have been introduced by the template-declaration.
18161 collectUnexpandedParameterPacks(QualifierLoc, Unexpanded);
18162 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18163 for (UnexpandedParameterPack &U : Unexpanded) {
18164 if (std::optional<std::pair<unsigned, unsigned>> DI = getDepthAndIndex(U);
18165 DI && DI->first >= FriendDeclDepth) {
18166 auto *ND = dyn_cast<NamedDecl *>(U.first);
18167 if (!ND)
18168 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
18169 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18170 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18171 return true;
18172 }
18173 }
18174
18175 // Handle the case of a templated-scope friend class. e.g.
18176 // template <class T> class A<T>::B;
18177 // FIXME: we don't support these right now.
18178 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
18181 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
18182 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18184 TL.setElaboratedKeywordLoc(TagLoc);
18186 TL.setNameLoc(NameLoc);
18187
18189 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18190 EllipsisLoc, TempParamLists);
18191 Friend->setAccess(AS_public);
18192 Friend->setUnsupportedFriend(true);
18193 CurContext->addDecl(Friend);
18194 return Friend;
18195}
18196
18198 MultiTemplateParamsArg TempParams,
18199 SourceLocation EllipsisLoc) {
18200 SourceLocation Loc = DS.getBeginLoc();
18201 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18202
18203 assert(DS.isFriendSpecified());
18205
18206 // C++ [class.friend]p3:
18207 // A friend declaration that does not declare a function shall have one of
18208 // the following forms:
18209 // friend elaborated-type-specifier ;
18210 // friend simple-type-specifier ;
18211 // friend typename-specifier ;
18212 //
18213 // If the friend keyword isn't first, or if the declarations has any type
18214 // qualifiers, then the declaration doesn't have that form.
18216 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
18217 if (DS.getTypeQualifiers()) {
18219 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
18221 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
18223 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
18225 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
18227 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
18228 }
18229
18230 // Try to convert the decl specifier to a type. This works for
18231 // friend templates because ActOnTag never produces a ClassTemplateDecl
18232 // for a TagUseKind::Friend.
18233 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18235 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
18236 QualType T = TSI->getType();
18237 if (TheDeclarator.isInvalidType())
18238 return nullptr;
18239
18240 // If '...' is present, the type must contain an unexpanded parameter
18241 // pack, and vice versa.
18242 bool Invalid = false;
18243 if (EllipsisLoc.isInvalid() &&
18245 return nullptr;
18246 if (EllipsisLoc.isValid() &&
18248 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18249 << TSI->getTypeLoc().getSourceRange();
18250 Invalid = true;
18251 }
18252
18253 if (!T->isElaboratedTypeSpecifier()) {
18254 if (TempParams.size()) {
18255 // C++23 [dcl.pre]p5:
18256 // In a simple-declaration, the optional init-declarator-list can be
18257 // omitted only when declaring a class or enumeration, that is, when
18258 // the decl-specifier-seq contains either a class-specifier, an
18259 // elaborated-type-specifier with a class-key, or an enum-specifier.
18260 //
18261 // The declaration of a template-declaration or explicit-specialization
18262 // is never a member-declaration, so this must be a simple-declaration
18263 // with no init-declarator-list. Therefore, this is ill-formed.
18264 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
18265 return nullptr;
18266 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18267 SmallString<16> InsertionText(" ");
18268 InsertionText += RD->getKindName();
18269
18271 ? diag::warn_cxx98_compat_unelaborated_friend_type
18272 : diag::ext_unelaborated_friend_type)
18273 << (unsigned)RD->getTagKind() << T
18275 InsertionText);
18276 } else {
18277 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
18278 << T << DS.getSourceRange();
18279 }
18280 }
18281
18282 // C++98 [class.friend]p1: A friend of a class is a function
18283 // or class that is not a member of the class . . .
18284 // This is fixed in DR77, which just barely didn't make the C++03
18285 // deadline. It's also a very silly restriction that seriously
18286 // affects inner classes and which nobody else seems to implement;
18287 // thus we never diagnose it, not even in -pedantic.
18288 //
18289 // But note that we could warn about it: it's always useless to
18290 // friend one of your own members (it's not, however, worthless to
18291 // friend a member of an arbitrary specialization of your template).
18292
18293 Decl *D;
18294 if (!TempParams.empty())
18295 // TODO: Support variadic friend template decls?
18296 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
18297 FriendLoc);
18298 else
18300 TSI, FriendLoc, EllipsisLoc);
18301
18302 if (!D)
18303 return nullptr;
18304
18305 D->setAccess(AS_public);
18306 CurContext->addDecl(D);
18307
18308 if (Invalid)
18309 D->setInvalidDecl();
18310
18311 return D;
18312}
18313
18315 MultiTemplateParamsArg TemplateParams) {
18316 const DeclSpec &DS = D.getDeclSpec();
18317
18318 assert(DS.isFriendSpecified());
18320
18323
18324 // C++ [class.friend]p1
18325 // A friend of a class is a function or class....
18326 // Note that this sees through typedefs, which is intended.
18327 // It *doesn't* see through dependent types, which is correct
18328 // according to [temp.arg.type]p3:
18329 // If a declaration acquires a function type through a
18330 // type dependent on a template-parameter and this causes
18331 // a declaration that does not use the syntactic form of a
18332 // function declarator to have a function type, the program
18333 // is ill-formed.
18334 if (!TInfo->getType()->isFunctionType()) {
18335 Diag(Loc, diag::err_unexpected_friend);
18336
18337 // It might be worthwhile to try to recover by creating an
18338 // appropriate declaration.
18339 return nullptr;
18340 }
18341
18342 // C++ [namespace.memdef]p3
18343 // - If a friend declaration in a non-local class first declares a
18344 // class or function, the friend class or function is a member
18345 // of the innermost enclosing namespace.
18346 // - The name of the friend is not found by simple name lookup
18347 // until a matching declaration is provided in that namespace
18348 // scope (either before or after the class declaration granting
18349 // friendship).
18350 // - If a friend function is called, its name may be found by the
18351 // name lookup that considers functions from namespaces and
18352 // classes associated with the types of the function arguments.
18353 // - When looking for a prior declaration of a class or a function
18354 // declared as a friend, scopes outside the innermost enclosing
18355 // namespace scope are not considered.
18356
18357 CXXScopeSpec &SS = D.getCXXScopeSpec();
18359 assert(NameInfo.getName());
18360
18361 // Check for unexpanded parameter packs.
18365 return nullptr;
18366
18367 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18368
18369 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
18370 auto Kind = SS.getScopeRep().getKind();
18371 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
18373 if (IsNamespaceOrGlobal) {
18374 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
18376 SS.clear();
18377 }
18378 }
18379
18380 // The context we found the declaration in, or in which we should
18381 // create the declaration.
18382 DeclContext *DC;
18383 Scope *DCScope = S;
18384 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18386
18387 // There are five cases here.
18388 // - There's no scope specifier and we're in a local class. Only look
18389 // for functions declared in the immediately-enclosing block scope.
18390 // We recover from invalid scope qualifiers as if they just weren't there.
18391 FunctionDecl *FunctionContainingLocalClass = nullptr;
18392 if ((SS.isInvalid() || !SS.isSet()) &&
18393 (FunctionContainingLocalClass =
18394 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
18395 // C++11 [class.friend]p11:
18396 // If a friend declaration appears in a local class and the name
18397 // specified is an unqualified name, a prior declaration is
18398 // looked up without considering scopes that are outside the
18399 // innermost enclosing non-class scope. For a friend function
18400 // declaration, if there is no prior declaration, the program is
18401 // ill-formed.
18402
18403 // Find the innermost enclosing non-class scope. This is the block
18404 // scope containing the local class definition (or for a nested class,
18405 // the outer local class).
18406 DCScope = S->getFnParent();
18407
18408 // Look up the function name in the scope.
18410 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
18411
18412 if (!Previous.empty()) {
18413 // All possible previous declarations must have the same context:
18414 // either they were declared at block scope or they are members of
18415 // one of the enclosing local classes.
18416 DC = Previous.getRepresentativeDecl()->getDeclContext();
18417 } else {
18418 // This is ill-formed, but provide the context that we would have
18419 // declared the function in, if we were permitted to, for error recovery.
18420 DC = FunctionContainingLocalClass;
18421 }
18423
18424 // - There's no scope specifier, in which case we just go to the
18425 // appropriate scope and look for a function or function template
18426 // there as appropriate.
18427 } else if (SS.isInvalid() || !SS.isSet()) {
18428 // C++11 [namespace.memdef]p3:
18429 // If the name in a friend declaration is neither qualified nor
18430 // a template-id and the declaration is a function or an
18431 // elaborated-type-specifier, the lookup to determine whether
18432 // the entity has been previously declared shall not consider
18433 // any scopes outside the innermost enclosing namespace.
18434
18435 // Find the appropriate context according to the above.
18436 DC = CurContext;
18437
18438 // Skip class contexts. If someone can cite chapter and verse
18439 // for this behavior, that would be nice --- it's what GCC and
18440 // EDG do, and it seems like a reasonable intent, but the spec
18441 // really only says that checks for unqualified existing
18442 // declarations should stop at the nearest enclosing namespace,
18443 // not that they should only consider the nearest enclosing
18444 // namespace.
18445 while (DC->isRecord())
18446 DC = DC->getParent();
18447
18448 DeclContext *LookupDC = DC->getNonTransparentContext();
18449 while (true) {
18450 LookupQualifiedName(Previous, LookupDC);
18451
18452 if (!Previous.empty()) {
18453 DC = LookupDC;
18454 break;
18455 }
18456
18457 if (isTemplateId) {
18458 if (isa<TranslationUnitDecl>(LookupDC)) break;
18459 } else {
18460 if (LookupDC->isFileContext()) break;
18461 }
18462 LookupDC = LookupDC->getParent();
18463 }
18464
18465 DCScope = getScopeForDeclContext(S, DC);
18466
18467 // - There's a non-dependent scope specifier, in which case we
18468 // compute it and do a previous lookup there for a function
18469 // or function template.
18470 } else if (!SS.getScopeRep().isDependent()) {
18471 DC = computeDeclContext(SS);
18472 if (!DC) return nullptr;
18473
18474 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18475
18477
18478 // C++ [class.friend]p1: A friend of a class is a function or
18479 // class that is not a member of the class . . .
18480 if (DC->Equals(CurContext))
18483 diag::warn_cxx98_compat_friend_is_member :
18484 diag::err_friend_is_member);
18485
18486 // - There's a scope specifier that does not match any template
18487 // parameter lists, in which case we use some arbitrary context,
18488 // create a method or method template, and wait for instantiation.
18489 // - There's a scope specifier that does match some template
18490 // parameter lists, which we don't handle right now.
18491 } else {
18492 DC = CurContext;
18493 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18494 }
18495
18496 if (!DC->isRecord()) {
18497 int DiagArg = -1;
18498 switch (D.getName().getKind()) {
18501 DiagArg = 0;
18502 break;
18504 DiagArg = 1;
18505 break;
18507 DiagArg = 2;
18508 break;
18510 DiagArg = 3;
18511 break;
18517 break;
18518 }
18519 // This implies that it has to be an operator or function.
18520 if (DiagArg >= 0) {
18521 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18522 return nullptr;
18523 }
18524 } else {
18525 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(DC);
18526 if (RC->isLambda()) {
18527 Diag(NameInfo.getBeginLoc(), diag::err_friend_lambda_decl);
18528 }
18529 }
18530
18531 // FIXME: This is an egregious hack to cope with cases where the scope stack
18532 // does not contain the declaration context, i.e., in an out-of-line
18533 // definition of a class.
18534 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18535 if (!DCScope) {
18536 FakeDCScope.setEntity(DC);
18537 DCScope = &FakeDCScope;
18538 }
18539
18540 bool AddToScope = true;
18541 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18542 TemplateParams, AddToScope);
18543 if (!ND) return nullptr;
18544
18545 assert(ND->getLexicalDeclContext() == CurContext);
18546
18547 // If we performed typo correction, we might have added a scope specifier
18548 // and changed the decl context.
18549 DC = ND->getDeclContext();
18550
18551 // Add the function declaration to the appropriate lookup tables,
18552 // adjusting the redeclarations list as necessary. We don't
18553 // want to do this yet if the friending class is dependent.
18554 //
18555 // Also update the scope-based lookup if the target context's
18556 // lookup context is in lexical scope.
18557 if (!CurContext->isDependentContext()) {
18558 DC = DC->getRedeclContext();
18560 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18561 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18562 }
18563
18565 D.getIdentifierLoc(), ND,
18566 DS.getFriendSpecLoc());
18567 FrD->setAccess(AS_public);
18568 CurContext->addDecl(FrD);
18569
18570 if (ND->isInvalidDecl()) {
18571 FrD->setInvalidDecl();
18572 } else {
18573 if (DC->isRecord()) CheckFriendAccess(ND);
18574
18575 FunctionDecl *FD;
18576 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18577 FD = FTD->getTemplatedDecl();
18578 else
18579 FD = cast<FunctionDecl>(ND);
18580
18581 // C++ [class.friend]p6:
18582 // A function may be defined in a friend declaration of a class if and
18583 // only if the class is a non-local class, and the function name is
18584 // unqualified.
18585 if (D.isFunctionDefinition()) {
18586 // Qualified friend function definition.
18587 if (SS.isNotEmpty()) {
18588 // FIXME: We should only do this if the scope specifier names the
18589 // innermost enclosing namespace; otherwise the fixit changes the
18590 // meaning of the code.
18592 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18593
18594 DB << SS.getScopeRep();
18595 if (DC->isFileContext())
18597
18598 // Friend function defined in a local class.
18599 } else if (FunctionContainingLocalClass) {
18600 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18601
18602 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18603 // a template-id, the function name is not unqualified because these is
18604 // no name. While the wording requires some reading in-between the
18605 // lines, GCC, MSVC, and EDG all consider a friend function
18606 // specialization definitions to be de facto explicit specialization
18607 // and diagnose them as such.
18608 } else if (isTemplateId) {
18609 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18610 }
18611 }
18612
18613 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18614 // default argument expression, that declaration shall be a definition
18615 // and shall be the only declaration of the function or function
18616 // template in the translation unit.
18618 // We can't look at FD->getPreviousDecl() because it may not have been set
18619 // if we're in a dependent context. If the function is known to be a
18620 // redeclaration, we will have narrowed Previous down to the right decl.
18621 if (D.isRedeclaration()) {
18622 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18623 Diag(Previous.getRepresentativeDecl()->getLocation(),
18624 diag::note_previous_declaration);
18625 } else if (!D.isFunctionDefinition())
18626 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18627 }
18628
18629 // Mark templated-scope function declarations as unsupported.
18630 if (!FD->getTemplateParameterLists().empty() && SS.isValid()) {
18631 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18632 << SS.getScopeRep() << SS.getRange()
18634 FrD->setUnsupportedFriend(true);
18635 }
18636 }
18637
18639
18640 return ND;
18641}
18642
18644 StringLiteral *Message) {
18646
18647 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18648 if (!Fn) {
18649 Diag(DelLoc, diag::err_deleted_non_function);
18650 return;
18651 }
18652
18653 // Deleted function does not have a body.
18654 Fn->setWillHaveBody(false);
18655
18656 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18657 // Don't consider the implicit declaration we generate for explicit
18658 // specializations. FIXME: Do not generate these implicit declarations.
18659 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18660 Prev->getPreviousDecl()) &&
18661 !Prev->isDefined()) {
18662 Diag(DelLoc, diag::err_deleted_decl_not_first);
18663 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18664 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18665 : diag::note_previous_declaration);
18666 // We can't recover from this; the declaration might have already
18667 // been used.
18668 Fn->setInvalidDecl();
18669 return;
18670 }
18671
18672 // To maintain the invariant that functions are only deleted on their first
18673 // declaration, mark the implicitly-instantiated declaration of the
18674 // explicitly-specialized function as deleted instead of marking the
18675 // instantiated redeclaration.
18676 Fn = Fn->getCanonicalDecl();
18677 }
18678
18679 // dllimport/dllexport cannot be deleted.
18680 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18681 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18682 Fn->setInvalidDecl();
18683 }
18684
18685 // C++11 [basic.start.main]p3:
18686 // A program that defines main as deleted [...] is ill-formed.
18687 if (Fn->isMain())
18688 Diag(DelLoc, diag::err_deleted_main);
18689
18690 // C++11 [dcl.fct.def.delete]p4:
18691 // A deleted function is implicitly inline.
18692 Fn->setImplicitlyInline();
18693 Fn->setDeletedAsWritten(true, Message);
18694}
18695
18697 if (!Dcl || Dcl->isInvalidDecl())
18698 return;
18699
18700 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18701 if (!FD) {
18702 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18703 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18704 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18705 return;
18706 }
18707 }
18708
18709 Diag(DefaultLoc, diag::err_default_special_members)
18710 << getLangOpts().CPlusPlus20;
18711 return;
18712 }
18713
18714 // Reject if this can't possibly be a defaultable function.
18716 if (!DefKind &&
18717 // A dependent function that doesn't locally look defaultable can
18718 // still instantiate to a defaultable function if it's a constructor
18719 // or assignment operator.
18720 (!FD->isDependentContext() ||
18722 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18723 Diag(DefaultLoc, diag::err_default_special_members)
18724 << getLangOpts().CPlusPlus20;
18725 return;
18726 }
18727
18728 // Issue compatibility warning. We already warned if the operator is
18729 // 'operator<=>' when parsing the '<=>' token.
18730 if (DefKind.isComparison() &&
18732 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18733 ? diag::warn_cxx17_compat_defaulted_comparison
18734 : diag::ext_defaulted_comparison);
18735 }
18736
18737 FD->setDefaulted();
18738 FD->setExplicitlyDefaulted();
18739 FD->setDefaultLoc(DefaultLoc);
18740
18741 // Defer checking functions that are defaulted in a dependent context.
18742 if (FD->isDependentContext())
18743 return;
18744
18745 // Unset that we will have a body for this function. We might not,
18746 // if it turns out to be trivial, and we don't need this marking now
18747 // that we've marked it as defaulted.
18748 FD->setWillHaveBody(false);
18749
18750 if (DefKind.isComparison()) {
18751 // If this comparison's defaulting occurs within the definition of its
18752 // lexical class context, we have to do the checking when complete.
18753 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18754 if (!RD->isCompleteDefinition())
18755 return;
18756 }
18757
18758 // If this member fn was defaulted on its first declaration, we will have
18759 // already performed the checking in CheckCompletedCXXClass. Such a
18760 // declaration doesn't trigger an implicit definition.
18761 if (isa<CXXMethodDecl>(FD)) {
18762 const FunctionDecl *Primary = FD;
18763 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18764 // Ask the template instantiation pattern that actually had the
18765 // '= default' on it.
18766 Primary = Pattern;
18767 if (Primary->getCanonicalDecl()->isDefaulted())
18768 return;
18769 }
18770
18771 if (DefKind.isComparison()) {
18772 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18773 FD->setInvalidDecl();
18774 else
18775 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18776 } else {
18777 auto *MD = cast<CXXMethodDecl>(FD);
18778
18780 DefaultLoc))
18781 MD->setInvalidDecl();
18782 else
18783 DefineDefaultedFunction(*this, MD, DefaultLoc);
18784 }
18785}
18786
18788 for (Stmt *SubStmt : S->children()) {
18789 if (!SubStmt)
18790 continue;
18791 if (isa<ReturnStmt>(SubStmt))
18792 Self.Diag(SubStmt->getBeginLoc(),
18793 diag::err_return_in_constructor_handler);
18794 if (!isa<Expr>(SubStmt))
18795 SearchForReturnInStmt(Self, SubStmt);
18796 }
18797}
18798
18800 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18801 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18802 SearchForReturnInStmt(*this, Handler);
18803 }
18804}
18805
18807 StringLiteral *DeletedMessage) {
18808 switch (BodyKind) {
18809 case FnBodyKind::Delete:
18810 SetDeclDeleted(D, Loc, DeletedMessage);
18811 break;
18813 SetDeclDefaulted(D, Loc);
18814 break;
18815 case FnBodyKind::Other:
18816 llvm_unreachable(
18817 "Parsed function body should be '= delete;' or '= default;'");
18818 }
18819}
18820
18822 const CXXMethodDecl *Old) {
18823 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18824 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18825
18826 if (OldFT->hasExtParameterInfos()) {
18827 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18828 // A parameter of the overriding method should be annotated with noescape
18829 // if the corresponding parameter of the overridden method is annotated.
18830 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18831 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18832 Diag(New->getParamDecl(I)->getLocation(),
18833 diag::warn_overriding_method_missing_noescape);
18834 Diag(Old->getParamDecl(I)->getLocation(),
18835 diag::note_overridden_marked_noescape);
18836 }
18837 }
18838
18839 // SME attributes must match when overriding a function declaration.
18840 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18841 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18842 << New << New->getType() << Old->getType();
18843 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18844 return true;
18845 }
18846
18847 // Virtual overrides must have the same code_seg.
18848 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18849 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18850 if ((NewCSA || OldCSA) &&
18851 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18852 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18853 Diag(Old->getLocation(), diag::note_previous_declaration);
18854 return true;
18855 }
18856
18857 // Virtual overrides: check for matching effects.
18858 if (Context.hasAnyFunctionEffects()) {
18859 const auto OldFX = Old->getFunctionEffects();
18860 const auto NewFXOrig = New->getFunctionEffects();
18861
18862 if (OldFX != NewFXOrig) {
18863 FunctionEffectSet NewFX(NewFXOrig);
18864 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18866 for (const auto &Diff : Diffs) {
18867 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18869 break;
18871 Diag(New->getLocation(), diag::warn_conflicting_func_effect_override)
18872 << Diff.effectName();
18873 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18874 << Old->getReturnTypeSourceRange();
18875 break;
18877 NewFX.insert(Diff.Old.value(), Errs);
18878 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18879 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18881 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18882 NewFT->getParamTypes(), EPI);
18883 New->setType(ModQT);
18884 if (Errs.empty()) {
18885 // A warning here is somewhat pedantic. Skip this if there was
18886 // already a merge conflict, which is more serious.
18887 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18888 << Diff.effectName();
18889 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18890 << Old->getReturnTypeSourceRange();
18891 }
18892 break;
18893 }
18894 }
18895 }
18896 if (!Errs.empty())
18897 diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
18898 Old->getLocation());
18899 }
18900 }
18901
18902 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18903
18904 // If the calling conventions match, everything is fine
18905 if (NewCC == OldCC)
18906 return false;
18907
18908 // If the calling conventions mismatch because the new function is static,
18909 // suppress the calling convention mismatch error; the error about static
18910 // function override (err_static_overrides_virtual from
18911 // Sema::CheckFunctionDeclaration) is more clear.
18912 if (New->getStorageClass() == SC_Static)
18913 return false;
18914
18915 Diag(New->getLocation(),
18916 diag::err_conflicting_overriding_cc_attributes)
18917 << New->getDeclName() << New->getType() << Old->getType();
18918 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18919 return true;
18920}
18921
18923 const CXXMethodDecl *Old) {
18924 // CWG2553
18925 // A virtual function shall not be an explicit object member function.
18926 if (!New->isExplicitObjectMemberFunction())
18927 return true;
18928 Diag(New->getParamDecl(0)->getBeginLoc(),
18929 diag::err_explicit_object_parameter_nonmember)
18930 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18931 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18932 New->setInvalidDecl();
18933 return false;
18934}
18935
18937 const CXXMethodDecl *Old) {
18938 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18939 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18940
18941 if (Context.hasSameType(NewTy, OldTy) ||
18942 NewTy->isDependentType() || OldTy->isDependentType())
18943 return false;
18944
18945 // Check if the return types are covariant
18946 QualType NewClassTy, OldClassTy;
18947
18948 /// Both types must be pointers or references to classes.
18949 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18950 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18951 NewClassTy = NewPT->getPointeeType();
18952 OldClassTy = OldPT->getPointeeType();
18953 }
18954 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18955 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18956 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18957 NewClassTy = NewRT->getPointeeType();
18958 OldClassTy = OldRT->getPointeeType();
18959 }
18960 }
18961 }
18962
18963 // The return types aren't either both pointers or references to a class type.
18964 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
18965 Diag(New->getLocation(),
18966 diag::err_different_return_type_for_overriding_virtual_function)
18967 << New->getDeclName() << NewTy << OldTy
18968 << New->getReturnTypeSourceRange();
18969 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18970 << Old->getReturnTypeSourceRange();
18971
18972 return true;
18973 }
18974
18975 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18976 // C++14 [class.virtual]p8:
18977 // If the class type in the covariant return type of D::f differs from
18978 // that of B::f, the class type in the return type of D::f shall be
18979 // complete at the point of declaration of D::f or shall be the class
18980 // type D.
18981 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
18982 if (!RD->isBeingDefined() &&
18983 RequireCompleteType(New->getLocation(), NewClassTy,
18984 diag::err_covariant_return_incomplete,
18985 New->getDeclName()))
18986 return true;
18987 }
18988
18989 // Check if the new class derives from the old class.
18990 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18991 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18992 << New->getDeclName() << NewTy << OldTy
18993 << New->getReturnTypeSourceRange();
18994 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18995 << Old->getReturnTypeSourceRange();
18996 return true;
18997 }
18998
18999 // Check if we the conversion from derived to base is valid.
19001 NewClassTy, OldClassTy,
19002 diag::err_covariant_return_inaccessible_base,
19003 diag::err_covariant_return_ambiguous_derived_to_base_conv,
19004 New->getLocation(), New->getReturnTypeSourceRange(),
19005 New->getDeclName(), nullptr)) {
19006 // FIXME: this note won't trigger for delayed access control
19007 // diagnostics, and it's impossible to get an undelayed error
19008 // here from access control during the original parse because
19009 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19010 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19011 << Old->getReturnTypeSourceRange();
19012 return true;
19013 }
19014 }
19015
19016 // The qualifiers of the return types must be the same.
19017 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19018 Diag(New->getLocation(),
19019 diag::err_covariant_return_type_different_qualifications)
19020 << New->getDeclName() << NewTy << OldTy
19021 << New->getReturnTypeSourceRange();
19022 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19023 << Old->getReturnTypeSourceRange();
19024 return true;
19025 }
19026
19027
19028 // The new class type must have the same or less qualifiers as the old type.
19029 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
19030 Diag(New->getLocation(),
19031 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19032 << New->getDeclName() << NewTy << OldTy
19033 << New->getReturnTypeSourceRange();
19034 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19035 << Old->getReturnTypeSourceRange();
19036 return true;
19037 }
19038
19039 return false;
19040}
19041
19043 SourceLocation EndLoc = InitRange.getEnd();
19044 if (EndLoc.isValid())
19045 Method->setRangeEnd(EndLoc);
19046
19047 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19048 Method->setIsPureVirtual();
19049 return false;
19050 }
19051
19052 if (!Method->isInvalidDecl())
19053 Diag(Method->getLocation(), diag::err_non_virtual_pure)
19054 << Method->getDeclName() << InitRange;
19055 return true;
19056}
19057
19059 if (D->getFriendObjectKind())
19060 Diag(D->getLocation(), diag::err_pure_friend);
19061 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
19062 CheckPureMethod(M, ZeroLoc);
19063 else
19064 Diag(D->getLocation(), diag::err_illegal_initializer);
19065}
19066
19067/// Invoked when we are about to parse an initializer for the declaration
19068/// 'Dcl'.
19069///
19070/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19071/// static data member of class X, names should be looked up in the scope of
19072/// class X. If the declaration had a scope specifier, a scope will have
19073/// been created and passed in for this purpose. Otherwise, S will be null.
19075 assert(D && !D->isInvalidDecl());
19076
19077 // We will always have a nested name specifier here, but this declaration
19078 // might not be out of line if the specifier names the current namespace:
19079 // extern int n;
19080 // int ::n = 0;
19081 if (S && D->isOutOfLine())
19083
19087}
19088
19090 assert(D);
19091
19092 if (S && D->isOutOfLine())
19094
19096}
19097
19099 // C++ 6.4p2:
19100 // The declarator shall not specify a function or an array.
19101 // The type-specifier-seq shall not contain typedef and shall not declare a
19102 // new class or enumeration.
19104 "Parser allowed 'typedef' as storage class of condition decl.");
19105
19106 Decl *Dcl = ActOnDeclarator(S, D);
19107 if (!Dcl)
19108 return true;
19109
19110 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
19111 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
19112 << D.getSourceRange();
19113 return true;
19114 }
19115
19116 if (auto *VD = dyn_cast<VarDecl>(Dcl))
19117 VD->setCXXCondDecl();
19118
19119 return Dcl;
19120}
19121
19123 if (!ExternalSource)
19124 return;
19125
19127 ExternalSource->ReadUsedVTables(VTables);
19129 for (const ExternalVTableUse &VTable : VTables) {
19130 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19131 VTablesUsed.find(VTable.Record);
19132 // Even if a definition wasn't required before, it may be required now.
19133 if (Pos != VTablesUsed.end()) {
19134 if (!Pos->second && VTable.DefinitionRequired)
19135 Pos->second = true;
19136 continue;
19137 }
19138
19139 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19140 NewUses.push_back(VTableUse(VTable.Record, VTable.Location));
19141 }
19142
19143 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
19144}
19145
19147 bool DefinitionRequired) {
19148 // Ignore any vtable uses in unevaluated operands or for classes that do
19149 // not have a vtable.
19150 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19151 CurContext->isDependentContext() || isUnevaluatedContext())
19152 return;
19153 // Do not mark as used if compiling for the device outside of the target
19154 // region.
19155 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19156 !OpenMP().isInOpenMPDeclareTargetContext() &&
19157 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19158 if (!DefinitionRequired)
19160 return;
19161 }
19162
19163 // Try to insert this class into the map.
19165 Class = Class->getCanonicalDecl();
19166 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19167 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
19168 if (!Pos.second) {
19169 // If we already had an entry, check to see if we are promoting this vtable
19170 // to require a definition. If so, we need to reappend to the VTableUses
19171 // list, since we may have already processed the first entry.
19172 if (DefinitionRequired && !Pos.first->second) {
19173 Pos.first->second = true;
19174 } else {
19175 // Otherwise, we can early exit.
19176 return;
19177 }
19178 } else {
19179 // The Microsoft ABI requires that we perform the destructor body
19180 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19181 // the deleting destructor is emitted with the vtable, not with the
19182 // destructor definition as in the Itanium ABI.
19183 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19184 CXXDestructorDecl *DD = Class->getDestructor();
19185 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19186 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19187 // If this is an out-of-line declaration, marking it referenced will
19188 // not do anything. Manually call CheckDestructor to look up operator
19189 // delete().
19190 ContextRAII SavedContext(*this, DD);
19191 CheckDestructor(DD);
19192 if (!DD->getOperatorDelete())
19193 DD->setInvalidDecl();
19194 } else {
19195 MarkFunctionReferenced(Loc, Class->getDestructor());
19196 }
19197 }
19198 }
19199 }
19200
19201 // Local classes need to have their virtual members marked
19202 // immediately. For all other classes, we mark their virtual members
19203 // at the end of the translation unit.
19204 if (Class->isLocalClass())
19205 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
19206 else
19207 VTableUses.push_back(std::make_pair(Class, Loc));
19208}
19209
19212 if (VTableUses.empty())
19213 return false;
19214
19215 // Note: The VTableUses vector could grow as a result of marking
19216 // the members of a class as "used", so we check the size each
19217 // time through the loop and prefer indices (which are stable) to
19218 // iterators (which are not).
19219 bool DefinedAnything = false;
19220 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19221 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19222 if (!Class)
19223 continue;
19225 Class->getTemplateSpecializationKind();
19226
19227 SourceLocation Loc = VTableUses[I].second;
19228
19229 bool DefineVTable = true;
19230
19231 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
19232 // V-tables for non-template classes with an owning module are always
19233 // uniquely emitted in that module.
19234 if (Class->isInCurrentModuleUnit()) {
19235 DefineVTable = true;
19236 } else if (KeyFunction && !KeyFunction->hasBody()) {
19237 // If this class has a key function, but that key function is
19238 // defined in another translation unit, we don't need to emit the
19239 // vtable even though we're using it.
19240 // The key function is in another translation unit.
19241 DefineVTable = false;
19243 KeyFunction->getTemplateSpecializationKind();
19246 "Instantiations don't have key functions");
19247 (void)TSK;
19248 } else if (!KeyFunction) {
19249 // If we have a class with no key function that is the subject
19250 // of an explicit instantiation declaration, suppress the
19251 // vtable; it will live with the explicit instantiation
19252 // definition.
19253 bool IsExplicitInstantiationDeclaration =
19255 for (auto *R : Class->redecls()) {
19257 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
19259 IsExplicitInstantiationDeclaration = true;
19260 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19261 IsExplicitInstantiationDeclaration = false;
19262 break;
19263 }
19264 }
19265
19266 if (IsExplicitInstantiationDeclaration) {
19267 const bool HasExcludeFromExplicitInstantiation =
19268 llvm::any_of(Class->methods(), [](CXXMethodDecl *method) {
19269 // If the class has a member function declared with
19270 // `__attribute__((exclude_from_explicit_instantiation))`, the
19271 // explicit instantiation declaration should not suppress emitting
19272 // the vtable, since the corresponding explicit instantiation
19273 // definition might not emit the vtable if a triggering method is
19274 // excluded.
19275 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19276 });
19277 if (!HasExcludeFromExplicitInstantiation)
19278 DefineVTable = false;
19279 }
19280 }
19281
19282 // The exception specifications for all virtual members may be needed even
19283 // if we are not providing an authoritative form of the vtable in this TU.
19284 // We may choose to emit it available_externally anyway.
19285 if (!DefineVTable) {
19287 continue;
19288 }
19289
19290 // Mark all of the virtual members of this class as referenced, so
19291 // that we can build a vtable. Then, tell the AST consumer that a
19292 // vtable for this class is required.
19293 DefinedAnything = true;
19295 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19296 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
19297 Consumer.HandleVTable(Class);
19298
19299 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19300 // no key function or the key function is inlined. Don't warn in C++ ABIs
19301 // that lack key functions, since the user won't be able to make one.
19302 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19303 Class->isExternallyVisible() &&
19304 !(Class->getOwningModule() &&
19305 Class->getOwningModule()->isInterfaceOrPartition()) &&
19306 ClassTSK != TSK_ImplicitInstantiation &&
19309 const FunctionDecl *KeyFunctionDef = nullptr;
19310 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
19311 KeyFunctionDef->isInlined()))
19312 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
19313 }
19314 }
19315 VTableUses.clear();
19316
19317 return DefinedAnything;
19318}
19319
19321 const CXXRecordDecl *RD) {
19322 for (const auto *I : RD->methods())
19323 if (I->isVirtual() && !I->isPureVirtual())
19324 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
19325}
19326
19328 const CXXRecordDecl *RD,
19329 bool ConstexprOnly) {
19330 // Mark all functions which will appear in RD's vtable as used.
19331 CXXFinalOverriderMap FinalOverriders;
19332 RD->getFinalOverriders(FinalOverriders);
19333 for (const auto &FinalOverrider : FinalOverriders) {
19334 for (const auto &OverridingMethod : FinalOverrider.second) {
19335 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19336 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19337
19338 // C++ [basic.def.odr]p2:
19339 // [...] A virtual member function is used if it is not pure. [...]
19340 if (!Overrider->isPureVirtual() &&
19341 (!ConstexprOnly || Overrider->isConstexpr()))
19342 MarkFunctionReferenced(Loc, Overrider);
19343 }
19344 }
19345
19346 // Only classes that have virtual bases need a VTT.
19347 if (RD->getNumVBases() == 0)
19348 return;
19349
19350 for (const auto &I : RD->bases()) {
19351 const auto *Base = I.getType()->castAsCXXRecordDecl();
19352 if (Base->getNumVBases() == 0)
19353 continue;
19355 }
19356}
19357
19358static
19363 Sema &S) {
19364 if (Ctor->isInvalidDecl())
19365 return;
19366
19368
19369 // Target may not be determinable yet, for instance if this is a dependent
19370 // call in an uninstantiated template.
19371 if (Target) {
19372 const FunctionDecl *FNTarget = nullptr;
19373 (void)Target->hasBody(FNTarget);
19374 Target = const_cast<CXXConstructorDecl*>(
19375 cast_or_null<CXXConstructorDecl>(FNTarget));
19376 }
19377
19378 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19379 // Avoid dereferencing a null pointer here.
19380 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19381
19382 if (!Current.insert(Canonical).second)
19383 return;
19384
19385 // We know that beyond here, we aren't chaining into a cycle.
19386 if (!Target || !Target->isDelegatingConstructor() ||
19387 Target->isInvalidDecl() || Valid.count(TCanonical)) {
19388 Valid.insert_range(Current);
19389 Current.clear();
19390 // We've hit a cycle.
19391 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
19392 Current.count(TCanonical)) {
19393 // If we haven't diagnosed this cycle yet, do so now.
19394 if (!Invalid.count(TCanonical)) {
19395 S.Diag((*Ctor->init_begin())->getSourceLocation(),
19396 diag::warn_delegating_ctor_cycle)
19397 << Ctor;
19398
19399 // Don't add a note for a function delegating directly to itself.
19400 if (TCanonical != Canonical)
19401 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
19402
19404 while (C->getCanonicalDecl() != Canonical) {
19405 const FunctionDecl *FNTarget = nullptr;
19406 (void)C->getTargetConstructor()->hasBody(FNTarget);
19407 assert(FNTarget && "Ctor cycle through bodiless function");
19408
19409 C = const_cast<CXXConstructorDecl*>(
19410 cast<CXXConstructorDecl>(FNTarget));
19411 S.Diag(C->getLocation(), diag::note_which_delegates_to);
19412 }
19413 }
19414
19415 Invalid.insert_range(Current);
19416 Current.clear();
19417 } else {
19419 }
19420}
19421
19422
19425
19426 for (DelegatingCtorDeclsType::iterator
19427 I = DelegatingCtorDecls.begin(ExternalSource.get()),
19428 E = DelegatingCtorDecls.end();
19429 I != E; ++I)
19430 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
19431
19432 for (CXXConstructorDecl *CI : Invalid)
19433 CI->setInvalidDecl();
19434}
19435
19436namespace {
19437 /// AST visitor that finds references to the 'this' expression.
19438class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19439 Sema &S;
19440
19441public:
19442 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19443
19444 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19445 S.Diag(E->getLocation(), diag::err_this_static_member_func)
19446 << E->isImplicit();
19447 return false;
19448 }
19449};
19450}
19451
19453 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19454 if (!TSInfo)
19455 return false;
19456
19457 TypeLoc TL = TSInfo->getTypeLoc();
19459 if (!ProtoTL)
19460 return false;
19461
19462 // C++11 [expr.prim.general]p3:
19463 // [The expression this] shall not appear before the optional
19464 // cv-qualifier-seq and it shall not appear within the declaration of a
19465 // static member function (although its type and value category are defined
19466 // within a static member function as they are within a non-static member
19467 // function). [ Note: this is because declaration matching does not occur
19468 // until the complete declarator is known. - end note ]
19469 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19470 FindCXXThisExpr Finder(*this);
19471
19472 // If the return type came after the cv-qualifier-seq, check it now.
19473 if (Proto->hasTrailingReturn() &&
19474 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19475 return true;
19476
19477 // Check the exception specification.
19479 return true;
19480
19481 // Check the trailing requires clause
19482 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19483 if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))
19484 return true;
19485
19487}
19488
19490 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19491 if (!TSInfo)
19492 return false;
19493
19494 TypeLoc TL = TSInfo->getTypeLoc();
19496 if (!ProtoTL)
19497 return false;
19498
19499 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19500 FindCXXThisExpr Finder(*this);
19501
19502 switch (Proto->getExceptionSpecType()) {
19503 case EST_Unparsed:
19504 case EST_Uninstantiated:
19505 case EST_Unevaluated:
19506 case EST_BasicNoexcept:
19507 case EST_NoThrow:
19508 case EST_DynamicNone:
19509 case EST_MSAny:
19510 case EST_None:
19511 break;
19512
19514 case EST_NoexceptFalse:
19515 case EST_NoexceptTrue:
19516 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19517 return true;
19518 [[fallthrough]];
19519
19520 case EST_Dynamic:
19521 for (const auto &E : Proto->exceptions()) {
19522 if (!Finder.TraverseType(E))
19523 return true;
19524 }
19525 break;
19526 }
19527
19528 return false;
19529}
19530
19532 FindCXXThisExpr Finder(*this);
19533
19534 // Check attributes.
19535 for (const auto *A : Method->attrs()) {
19536 // FIXME: This should be emitted by tblgen.
19537 Expr *Arg = nullptr;
19538 ArrayRef<Expr *> Args;
19539 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19540 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19541 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19542 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19543 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19544 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19545 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19546 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19547 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19548 Arg = LR->getArg();
19549 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19550 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19551 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19552 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19553 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19554 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19555 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {
19556 Arg = AC->getSuccessValue();
19557 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19558 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19559 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19560
19561 if (Arg && !Finder.TraverseStmt(Arg))
19562 return true;
19563
19564 for (Expr *A : Args) {
19565 if (!Finder.TraverseStmt(A))
19566 return true;
19567 }
19568 }
19569
19570 return false;
19571}
19572
19574 bool IsTopLevel, ExceptionSpecificationType EST,
19575 ArrayRef<ParsedType> DynamicExceptions,
19576 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19577 SmallVectorImpl<QualType> &Exceptions,
19579 Exceptions.clear();
19580 ESI.Type = EST;
19581 if (EST == EST_Dynamic) {
19582 Exceptions.reserve(DynamicExceptions.size());
19583 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19584 // FIXME: Preserve type source info.
19585 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19586
19587 if (IsTopLevel) {
19589 collectUnexpandedParameterPacks(ET, Unexpanded);
19590 if (!Unexpanded.empty()) {
19592 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19593 Unexpanded);
19594 continue;
19595 }
19596 }
19597
19598 // Check that the type is valid for an exception spec, and
19599 // drop it if not.
19600 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19601 Exceptions.push_back(ET);
19602 }
19603 ESI.Exceptions = Exceptions;
19604 return;
19605 }
19606
19607 if (isComputedNoexcept(EST)) {
19608 assert((NoexceptExpr->isTypeDependent() ||
19609 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19610 Context.BoolTy) &&
19611 "Parser should have made sure that the expression is boolean");
19612 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19613 ESI.Type = EST_BasicNoexcept;
19614 return;
19615 }
19616
19617 ESI.NoexceptExpr = NoexceptExpr;
19618 return;
19619 }
19620}
19621
19623 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19624 ArrayRef<ParsedType> DynamicExceptions,
19625 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19626 if (!D)
19627 return;
19628
19629 // Dig out the function we're referring to.
19630 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
19631 D = FTD->getTemplatedDecl();
19632
19633 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
19634 if (!FD)
19635 return;
19636
19637 // Check the exception specification.
19640 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19641 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19642 ESI);
19643
19644 // Update the exception specification on the function type.
19645 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19646
19647 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19648 if (MD->isStatic())
19650
19651 if (MD->isVirtual()) {
19652 // Check overrides, which we previously had to delay.
19653 for (const CXXMethodDecl *O : MD->overridden_methods())
19655 }
19656 }
19657}
19658
19659/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19660///
19662 SourceLocation DeclStart, Declarator &D,
19663 Expr *BitWidth,
19664 InClassInitStyle InitStyle,
19665 AccessSpecifier AS,
19666 const ParsedAttr &MSPropertyAttr) {
19667 const IdentifierInfo *II = D.getIdentifier();
19668 if (!II) {
19669 Diag(DeclStart, diag::err_anonymous_property);
19670 return nullptr;
19671 }
19673
19675 QualType T = TInfo->getType();
19676 if (getLangOpts().CPlusPlus) {
19678
19681 D.setInvalidType();
19682 T = Context.IntTy;
19683 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19684 }
19685 }
19686
19688
19690 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19691 << getLangOpts().CPlusPlus17;
19694 diag::err_invalid_thread)
19696
19697 // Check to see if this name was declared as a member previously
19698 NamedDecl *PrevDecl = nullptr;
19699 LookupResult Previous(*this, II, Loc, LookupMemberName,
19701 LookupName(Previous, S);
19702 switch (Previous.getResultKind()) {
19705 PrevDecl = Previous.getAsSingle<NamedDecl>();
19706 break;
19707
19709 PrevDecl = Previous.getRepresentativeDecl();
19710 break;
19711
19715 break;
19716 }
19717
19718 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19719 // Maybe we will complain about the shadowed template parameter.
19721 // Just pretend that we didn't see the previous declaration.
19722 PrevDecl = nullptr;
19723 }
19724
19725 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19726 PrevDecl = nullptr;
19727
19728 SourceLocation TSSL = D.getBeginLoc();
19729 MSPropertyDecl *NewPD =
19730 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19731 MSPropertyAttr.getPropertyDataGetter(),
19732 MSPropertyAttr.getPropertyDataSetter());
19733 ProcessDeclAttributes(TUScope, NewPD, D);
19734 NewPD->setAccess(AS);
19735
19736 if (NewPD->isInvalidDecl())
19737 Record->setInvalidDecl();
19738
19740 NewPD->setModulePrivate();
19741
19742 if (NewPD->isInvalidDecl() && PrevDecl) {
19743 // Don't introduce NewFD into scope; there's already something
19744 // with the same name in the same scope.
19745 } else if (II) {
19746 PushOnScopeChains(NewPD, S);
19747 } else
19748 Record->addDecl(NewPD);
19749
19750 return NewPD;
19751}
19752
19754 Declarator &Declarator, unsigned TemplateParameterDepth) {
19755 auto &Info = InventedParameterInfos.emplace_back();
19756 TemplateParameterList *ExplicitParams = nullptr;
19757 ArrayRef<TemplateParameterList *> ExplicitLists =
19759 if (!ExplicitLists.empty()) {
19760 bool IsMemberSpecialization, IsInvalid;
19763 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19764 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19765 /*SuppressDiagnostic=*/true);
19766 }
19767 // C++23 [dcl.fct]p23:
19768 // An abbreviated function template can have a template-head. The invented
19769 // template-parameters are appended to the template-parameter-list after
19770 // the explicitly declared template-parameters.
19771 //
19772 // A template-head must have one or more template-parameters (read:
19773 // 'template<>' is *not* a template-head). Only append the invented
19774 // template parameters if we matched the nested-name-specifier to a non-empty
19775 // TemplateParameterList.
19776 if (ExplicitParams && !ExplicitParams->empty()) {
19777 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19778 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19779 Info.NumExplicitTemplateParams = ExplicitParams->size();
19780 } else {
19781 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19782 Info.NumExplicitTemplateParams = 0;
19783 }
19784}
19785
19787 auto &FSI = InventedParameterInfos.back();
19788 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19789 if (FSI.NumExplicitTemplateParams != 0) {
19790 TemplateParameterList *ExplicitParams =
19794 Context, ExplicitParams->getTemplateLoc(),
19795 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19796 ExplicitParams->getRAngleLoc(),
19797 ExplicitParams->getRequiresClause()));
19798 } else {
19801 FSI.TemplateParams, Declarator.getEndLoc(),
19802 /*RequiresClause=*/nullptr));
19803 }
19804 }
19805 InventedParameterInfos.pop_back();
19806}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static void ProcessAPINotes(Sema &S, Decl *D, const api_notes::CommonEntityInfo &Info, VersionedInfoMetadata Metadata)
This file declares semantic analysis for CUDA constructs.
static void DiagnoseUnsatisfiedConstraint(Sema &S, ArrayRef< UnsatisfiedConstraintRecord > Records, SourceLocation Loc, bool First=true, concepts::NestedRequirement *Req=nullptr)
static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD, SourceLocation Loc, bool &Res)
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we're implicitly defining a move assignment operator for a class with virtual bases.
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID)
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *Body, Sema::CheckConstexprKind Kind)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, CXXRecordDecl *Class)
static bool checkVectorDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT)
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
static CXXDestructorDecl * LookupDestructorIfRelevant(Sema &S, CXXRecordDecl *Class)
static void extendRight(SourceRange &R, SourceRange After)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef, const FunctionDecl *FD, bool *WasMalformed)
static bool RefersToRValueRef(Expr *MemRef)
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallPtrSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
#define CheckPolymorphic(Type)
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy, unsigned TyWidth, SmallVectorImpl< char > &Str)
Convert character's value, interpreted as a code unit, to a string.
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD)
Check for invalid uses of an abstract type in a function declaration.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, unsigned &OutSize)
static Expr * CastForMoving(Sema &SemaRef, Expr *E)
static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef, const FunctionDecl *FD)
static void extendLeft(SourceRange &R, SourceRange Before)
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D, unsigned Kind)
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class....
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, UnresolvedSetImpl &Operators, OverloadedOperatorKind Op)
Perform the unqualified lookups that might be needed to form a defaulted comparison function for the ...
static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS)
static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message, ResultType &Result, ASTContext &Ctx, Sema::StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overridden methods from MD to Methods.
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD, QualType TypeParam, SourceLocation Loc)
AllocationOperatorKind
static NamespaceDecl * getNamespaceDecl(NamespaceBaseDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
static bool isDestroyingDeleteT(QualType Type)
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, CXXRecordDecl *Class)
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, const CXXCtorInitializer *Previous, const CXXCtorInitializer *Current)
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
static bool IsUnusedPrivateField(const FieldDecl *FD)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl)
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, unsigned NumElems)
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static bool HasAttribute(const QualType &T)
static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind, CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, bool ConstArg, TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
static TemplateArgumentLoc getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T)
static void findImplicitlyDeclaredEqualityComparisons(ASTContext &Ctx, CXXRecordDecl *RD, llvm::SmallVectorImpl< FunctionDecl * > &Spaceships)
Find the equality comparison functions that should be implicitly declared in a given class definition...
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl< const void * > &IdealInits)
ImplicitInitializerKind
ImplicitInitializerKind - How an implicit base or member initializer should initialize its base or me...
@ IIK_Default
@ IIK_Move
@ IIK_Inherit
@ IIK_Copy
static bool ConvertAPValueToString(const APValue &V, QualType T, SmallVectorImpl< char > &Str, ASTContext &Context)
Convert \V to a string we can present to the user in a diagnostic \T is the type of the expression th...
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
static ClassTemplateDecl * LookupStdClassTemplate(Sema &S, SourceLocation Loc, const char *ClassName, bool *WasMalformed)
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class)
static bool UsefulToPrintExpr(const Expr *E)
Some Expression types are not useful to print notes about, e.g.
static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec)
Find the direct and/or virtual base specifiers that correspond to the given base type,...
static bool checkLiteralOperatorTemplateParameterList(Sema &SemaRef, FunctionTemplateDecl *TpDecl)
static bool ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, llvm::function_ref< bool(const CXXMethodDecl *)> Report)
Report an error regarding overriding, along with any relevant overridden methods.
static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD, QualType DecompType, ArrayRef< BindingDecl * > Bindings, unsigned MemberCount)
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, TemplateArgumentListInfo &Args, const TemplateParameterList *Params)
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's return type is a literal type.
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer * > Inits)
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD)
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location, FieldDecl *Field)
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
@ TSK_CompleteObject
The object is actually the complete object.
@ TSK_Field
The subobject is a non-static data member.
@ TSK_BaseClass
The subobject is a base class.
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument.
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg, const char *ClassName, ClassTemplateDecl **CachedDecl, const Decl **MalformedDecl)
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location, CXXRecordDecl *ClassDecl)
static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc, const CXXRecordDecl *OrigRD, QualType DecompType, DeclAccessPair BasePair)
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, CXXSpecialMemberKind CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Determine whether the specified special member function would be constexpr if it were implicitly defi...
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, CXXSpecialMemberKind CSM, TrivialSubobjectKind Kind, TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected, Sema &S)
static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying)
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, CXXMethodDecl *MD)
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, unsigned I, QualType T)
static Sema::ImplicitExceptionSpecification ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM, Sema::InheritedConstructorInfo *ICI)
static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
static bool checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
static bool InitializationHasSideEffects(const FieldDecl &FD)
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc, Sema::CheckConstexprKind Kind)
Check the given declaration statement is legal within a constexpr function body.
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent",...
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, const BaseSet &Bases)
Determines if the given class is provably not derived from all of the prospective base classes.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
static void collectUnexpandedParameterPacks(Sema &S, TemplateParameterList *Params, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
a trap message and trap category.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const ConstantArrayType * getAsConstantArrayType(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:806
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:802
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:855
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType BuiltinFnTy
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:921
CanQualType getCanonicalTagType(const TagDecl *TD) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition DeclCXX.h:117
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
TypeLoc getElementLoc() const
Definition TypeLoc.h:1807
QualType getElementType() const
Definition TypeBase.h:3798
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
bool isInherited() const
Definition Attr.h:101
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition Attr.h:99
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3514
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3592
void addShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3504
shadow_iterator shadow_begin() const
Definition DeclCXX.h:3584
void removeShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3513
Expr * getLHS() const
Definition Expr.h:4094
Expr * getRHS() const
Definition Expr.h:4096
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5104
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
Opcode getOpcode() const
Definition Expr.h:4089
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2149
A binding in a decomposition declaration.
Definition DeclCXX.h:4203
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition DeclCXX.cpp:3695
void setBinding(QualType DeclaredType, Expr *Binding)
Set the binding for this BindingDecl, along with its declared type (which should be a possibly-cv-qua...
Definition DeclCXX.h:4241
void setDecomposedDecl(ValueDecl *Decomposed)
Set the decomposed variable for this BindingDecl.
Definition DeclCXX.h:4247
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6675
Wrapper for source info for block pointers.
Definition TypeLoc.h:1526
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
Kind getKind() const
Definition TypeBase.h:3276
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
DeclContext::lookup_iterator Decls
The declarations found inside this base class subobject.
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const CXXRecordDecl * getOrigin() const
Retrieve the type from which this base-paths search began.
CXXBasePath & front()
bool isRecordingPaths() const
Whether we are recording paths.
void setRecordingPaths(bool RP)
Specify whether we should be recording paths or not.
void setOrigin(const CXXRecordDecl *Rec)
void clear()
Clear the base-paths results.
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition DeclCXX.h:193
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition DeclCXX.h:230
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:727
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:28
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
static CXXConstructExpr * Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr * > Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, CXXConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Create a C++ construction expression.
Definition ExprCXX.cpp:1187
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
bool isImmediateEscalating() const
Definition ExprCXX.h:1710
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2873
bool isMoveConstructor(unsigned &TypeQuals) const
Determine whether this constructor is a move constructor (C++11 [class.copy]p3), which can be used to...
Definition DeclCXX.cpp:3061
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition DeclCXX.h:2727
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition DeclCXX.cpp:3038
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:3056
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3047
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition DeclCXX.h:2868
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3016
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclCXX.h:2705
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2965
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3001
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition DeclCXX.h:2570
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition DeclCXX.cpp:2964
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition DeclCXX.cpp:2951
bool isAnyMemberInitializer() const
Definition DeclCXX.h:2478
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition DeclCXX.h:2532
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2544
Represents a C++ destructor within a class.
Definition DeclCXX.h:2895
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3146
const FunctionDecl * getOperatorDelete() const
Definition DeclCXX.cpp:3218
A mapping from each virtual member function to its set of final overriders.
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1755
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:748
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2717
bool isVirtual() const
Definition DeclCXX.h:2200
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2502
unsigned getNumExplicitParams() const
Definition DeclCXX.h:2312
CXXMethodDecl * getMostRecentDecl()
Definition DeclCXX.h:2261
overridden_method_range overridden_methods() const
Definition DeclCXX.cpp:2826
unsigned size_overridden_methods() const
Definition DeclCXX.cpp:2820
method_iterator begin_overridden_methods() const
Definition DeclCXX.cpp:2810
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
bool isInstance() const
Definition DeclCXX.h:2172
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2749
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2308
bool isStatic() const
Definition DeclCXX.cpp:2415
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2254
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasConstexprDefaultConstructor() const
Determine whether this class has a constexpr default constructor.
Definition DeclCXX.h:1281
friend_range friends() const
Definition DeclFriend.h:258
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition DeclCXX.h:1352
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition DeclCXX.cpp:611
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1251
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1679
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1377
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition DeclCXX.h:1006
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition DeclCXX.h:822
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition DeclCXX.h:714
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition DeclCXX.h:1431
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1402
bool hasTrivialDestructorForCall() const
Definition DeclCXX.h:1381
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition DeclCXX.h:706
bool isLiteral() const
Determine whether this class is a literal type.
Definition DeclCXX.cpp:1506
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition DeclCXX.h:965
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1367
base_class_range bases()
Definition DeclCXX.h:608
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:604
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1023
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1312
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition DeclCXX.h:766
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition DeclCXX.h:894
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition DeclCXX.h:913
bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is provably not derived from the type Base.
method_range methods() const
Definition DeclCXX.h:650
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition DeclCXX.h:935
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition DeclCXX.h:1740
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1274
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1289
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition DeclCXX.h:977
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition DeclCXX.cpp:599
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1219
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition DeclCXX.h:697
bool hasTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1293
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
bool lambdaIsDefaultConstructibleAndAssignable() const
Determine whether this lambda should have an implicit default constructor and copy and move assignmen...
Definition DeclCXX.cpp:730
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2060
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition DeclCXX.h:1339
base_class_range vbases()
Definition DeclCXX.h:625
base_class_iterator vbases_begin()
Definition DeclCXX.h:632
ctor_range ctors() const
Definition DeclCXX.h:670
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition DeclCXX.h:869
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1226
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition DeclCXX.h:1241
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition DeclCXX.h:860
bool isDynamicClass() const
Definition DeclCXX.h:574
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1153
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition DeclCXX.h:800
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition DeclCXX.h:1413
bool hasNonTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1304
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition DeclCXX.h:1205
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition DeclCXX.h:794
bool hasDefinition() const
Definition DeclCXX.h:561
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition DeclCXX.h:919
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition DeclCXX.h:1012
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2052
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
bool needsOverloadResolutionForMoveConstructor() const
Determine whether we need to eagerly declare a defaulted move constructor for this class.
Definition DeclCXX.h:905
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2152
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition DeclCXX.h:999
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2127
bool hasNonTrivialDestructorForCall() const
Definition DeclCXX.h:1391
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition DeclCXX.h:1018
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition DeclCXX.h:1425
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition DeclCXX.cpp:1754
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition DeclCXX.h:807
CXXRecordDecl * getDefinitionOrSelf() const
Definition DeclCXX.h:555
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition DeclCXX.h:848
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition DeclCXX.h:987
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition DeclCXX.h:928
bool hasTrivialMoveConstructorForCall() const
Definition DeclCXX.h:1317
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition DeclCXX.h:950
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
Represents the this expression in C++.
Definition ExprCXX.h:1158
SourceLocation getBeginLoc() const
Definition ExprCXX.h:1178
bool isImplicit() const
Definition ExprCXX.h:1181
SourceLocation getLocation() const
Definition ExprCXX.h:1175
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:69
CXXCatchStmt * getHandler(unsigned i)
Definition StmtCXX.h:108
unsigned getNumHandlers() const
Definition StmtCXX.h:107
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
bool isCallToStdMove() const
Definition Expr.cpp:3651
Expr * getCallee()
Definition Expr.h:3096
arg_range arguments()
Definition Expr.h:3201
QualType withConst() const
Retrieves a version of this type with const applied.
CastKind getCastKind() const
Definition Expr.h:3726
Expr * getSubExpr()
Definition Expr.h:3732
static CharSourceRange getTokenRange(SourceRange R)
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
static StringRef getCategoryString(ComparisonCategoryType Kind)
static StringRef getResultString(ComparisonCategoryResult Kind)
static std::vector< ComparisonCategoryResult > getPossibleResultsForType(ComparisonCategoryType Type)
Return the list of results which are valid for the specified comparison category type.
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
ComparisonCategoryType Kind
The Kind of the comparison category type.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3339
QualType getElementType() const
Definition TypeBase.h:3349
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1750
body_range body()
Definition Stmt.h:1813
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition Stmt.cpp:399
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition DeclCXX.h:3695
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition DeclCXX.h:3759
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition DeclCXX.cpp:3486
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:5344
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
AccessSpecifier getAccess() const
The results of name lookup within a DeclContext.
Definition DeclBase.h:1395
DeclListNode::iterator iterator
Definition DeclBase.h:1405
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition DeclBase.h:2406
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2251
lookup_result::iterator lookup_iterator
Definition DeclBase.h:2591
bool isFileContext() const
Definition DeclBase.h:2193
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTranslationUnit() const
Definition DeclBase.h:2198
bool isRecord() const
Definition DeclBase.h:2202
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_iterator decls_end() const
Definition DeclBase.h:2388
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2386
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2115
DeclContext * getNonTransparentContext()
decl_iterator decls_begin() const
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:494
ValueDecl * getDecl()
Definition Expr.h:1344
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1474
SourceLocation getBeginLoc() const
Definition Expr.h:1355
bool isImmediateEscalating() const
Definition Expr.h:1484
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:655
bool isModulePrivateSpecified() const
Definition DeclSpec.h:836
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:698
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition DeclSpec.cpp:631
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:237
Expr * getPackIndexingExpr() const
Definition DeclSpec.h:545
void ClearStorageClassSpecs()
Definition DeclSpec.h:500
TST getTypeSpecType() const
Definition DeclSpec.h:522
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:495
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:559
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:602
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:661
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:834
ParsedType getRepAsType() const
Definition DeclSpec.h:532
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:487
bool isFriendSpecifiedFirst() const
Definition DeclSpec.h:832
ParsedAttributes & getAttributes()
Definition DeclSpec.h:880
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:609
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:603
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:662
Expr * getRepAsExpr() const
Definition DeclSpec.h:540
bool isInlineSpecified() const
Definition DeclSpec.h:644
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:604
TypeSpecifierType TST
Definition DeclSpec.h:250
bool SetTypeQual(TQ T, SourceLocation Loc)
void ClearConstexprSpec()
Definition DeclSpec.h:848
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:532
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:496
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:606
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:656
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:843
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:567
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition DeclSpec.cpp:427
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:647
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:607
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:605
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:828
bool hasExplicitSpecifier() const
Definition DeclSpec.h:658
bool hasConstexprSpecifier() const
Definition DeclSpec.h:844
static const TST TST_auto
Definition DeclSpec.h:291
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1641
decl_range decls()
Definition Stmt.h:1689
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:1667
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1074
bool isInStdNamespace() const
Definition DeclBase.cpp:450
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1239
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
Kind
Lists the kind of concrete classes of Decl.
Definition DeclBase.h:89
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:591
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1232
@ FOK_None
Not a friend object.
Definition DeclBase.h:1230
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2806
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
Definition DeclBase.h:596
unsigned getIdentifierNamespace() const
Definition DeclBase.h:902
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1182
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
void setLocalOwningModule(Module *M)
Definition DeclBase.h:837
void setImplicit(bool I=true)
Definition DeclBase.h:602
void setReferenced(bool R=true)
Definition DeclBase.h:631
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:576
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
void dropAttr()
Definition DeclBase.h:564
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:931
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
Definition DeclBase.h:229
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition DeclBase.h:894
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
std::string getAsString() const
Retrieve the human-readable string for this name.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2003
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
Definition Decl.h:862
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1952
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2508
bool isDeclarationOfFunction() const
Determine whether the declaration that will be produced from this declaration will be a function.
Definition DeclSpec.cpp:296
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2450
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2099
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2562
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2391
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2136
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2463
bool hasGroupingParens() const
Definition DeclSpec.h:2771
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2765
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2446
bool isRedeclaration() const
Definition DeclSpec.h:2817
DeclaratorContext getContext() const
Definition DeclSpec.h:2124
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2120
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
bool isFunctionDefinition() const
Definition DeclSpec.h:2789
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2118
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2114
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition DeclSpec.h:2701
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition DeclSpec.h:2708
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition DeclSpec.h:2263
bool isInvalidType() const
Definition DeclSpec.h:2766
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2134
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2378
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2106
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2539
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
A decomposition declaration.
Definition DeclCXX.h:4267
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4305
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1840
ArrayRef< Binding > bindings() const
Definition DeclSpec.h:1880
SourceRange getSourceRange() const
Definition DeclSpec.h:1888
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1886
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2601
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2590
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:960
virtual bool TraverseConstructorInitializer(MaybeConst< CXXCtorInitializer > *Init)
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5891
RAII object that enters a new expression evaluation context.
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3445
Represents an enum.
Definition Decl.h:4033
enumerator_range enumerators() const
Definition Decl.h:4179
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1944
const Expr * getExpr() const
Definition DeclCXX.h:1953
void setExpr(Expr *E)
Definition DeclCXX.h:1978
void setKind(ExplicitSpecKind Kind)
Definition DeclCXX.h:1977
This represents one expression.
Definition Expr.h:112
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3087
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3262
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3182
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3282
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4721
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3362
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4711
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3356
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition Decl.cpp:4731
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3418
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3429
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3288
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location.
Definition Diagnostic.h:117
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:104
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
void setUnsupportedFriend(bool Unsupported)
Definition DeclFriend.h:186
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList * > Params, FriendUnion Friend, SourceLocation FriendLoc)
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3116
Represents a function declaration or definition.
Definition Decl.h:2018
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2660
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3255
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition Decl.h:2887
bool isTrivialForCall() const
Definition Decl.h:2398
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2494
DefaultedOrDeletedFunctionInfo * getDefaultedOrDeletedInfo() const
Definition Decl.cpp:3170
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3823
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4169
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2332
bool isImmediateFunction() const
Definition Decl.cpp:3316
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition Decl.cpp:3136
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4000
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3527
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3841
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2939
SourceLocation getDefaultLoc() const
Definition Decl.h:2416
QualType getReturnType() const
Definition Decl.h:2863
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2792
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2407
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2395
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4289
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition Decl.h:2800
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3723
param_iterator param_begin()
Definition Decl.h:2804
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2841
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3109
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2344
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2558
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition Decl.h:2504
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4305
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3156
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4233
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2906
void setTrivial(bool IT)
Definition Decl.h:2396
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4120
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2488
static constexpr unsigned RequiredTypeAwareNewParameterCount
Count of mandatory parameters for type aware operator new.
Definition Decl.h:2656
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2371
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3594
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isImmediateEscalating() const
Definition Decl.cpp:3287
void setIsDestroyingOperatorDelete(bool IsDestroyingDelete)
Definition Decl.cpp:3531
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3535
void setIsTypeAwareOperatorNewOrDelete(bool IsTypeAwareOperator=true)
Definition Decl.cpp:3539
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2403
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4545
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2951
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4106
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2491
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4393
void setDefaulted(bool D=true)
Definition Decl.h:2404
bool isConsteval() const
Definition Decl.h:2500
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2428
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:2880
void setBody(Stmt *B)
Definition Decl.cpp:3267
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2362
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition Decl.cpp:3855
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3802
size_t param_size() const
Definition Decl.h:2808
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2229
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3175
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3222
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.h:2823
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2703
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5307
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:5805
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5339
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5171
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ValueDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ValueDecl * > Params)
Definition ExprCXX.cpp:1809
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5875
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5678
unsigned getNumParams() const
Definition TypeBase.h:5649
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5791
const QualType * param_type_iterator
Definition TypeBase.h:5809
QualType getParamType(unsigned i) const
Definition TypeBase.h:5651
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5736
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
ArrayRef< QualType > exceptions() const
Definition TypeBase.h:5825
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5840
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Wrapper for source info for functions.
Definition TypeLoc.h:1644
unsigned getNumParams() const
Definition TypeLoc.h:1716
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1722
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1723
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1725
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4790
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
CallingConv getCallConv() const
Definition TypeBase.h:4922
QualType getReturnType() const
Definition TypeBase.h:4907
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ReservedLiteralSuffixIdStatus isReservedLiteralSuffixId() const
Determine whether this is a name reserved for future standardization or the implementation (C++ [usrl...
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IfStmt - This represents an if/then/else.
Definition Stmt.h:2269
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1737
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2079
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6060
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3489
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3510
void setInherited(bool I)
Definition Attr.h:163
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2604
ConstructorUsingShadowDecl * getShadowDecl() const
Definition DeclCXX.h:2616
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5305
unsigned getNumInits() const
Definition Expr.h:5338
const Expr * getInit(unsigned Init) const
Definition Expr.h:5360
child_range children()
Definition Expr.h:5501
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a member subobject.
static InitializedEntity InitializeBinding(VarDecl *Binding)
Create the initialization entity for a structured binding.
static InitializedEntity InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member)
Create the initialization entity for a default member initializer.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeMemberImplicit(FieldDecl *Member)
Create the initialization entity for a member subobject with implicit field initializer.
static InitializedEntity InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:981
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3681
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition ExprCXX.cpp:1365
capture_range captures() const
Retrieve this lambda's captures.
Definition ExprCXX.cpp:1378
@ Default
Use default layout rules of the target.
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1074
Represents a linkage specification.
Definition DeclCXX.h:3033
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3301
void setRBraceLoc(SourceLocation L)
Definition DeclCXX.h:3075
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
iterator end() const
Definition Lookup.h:359
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition Lookup.h:358
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4362
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition DeclCXX.cpp:3770
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
Expr * getBase() const
Definition Expr.h:3447
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3565
Wrapper for source info for member pointers.
Definition TypeLoc.h:1544
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
Describes a module or submodule.
Definition Module.h:340
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:950
bool isExplicitGlobalModule() const
Definition Module.h:441
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:714
Represents a C++ namespace alias.
Definition DeclCXX.h:3219
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamespaceBaseDecl *Namespace)
Definition DeclCXX.cpp:3402
Represents C++ namespaces and their aliases.
Definition Decl.h:573
NamespaceDecl * getNamespace()
Definition DeclCXX.cpp:3339
Represent a C++ namespace.
Definition Decl.h:592
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition Decl.h:648
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3362
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace that inhabits this namespace, if any.
Definition Decl.h:675
void setRBraceLoc(SourceLocation L)
Definition Decl.h:694
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition ObjCRuntime.h:97
PtrTy get() const
Definition Ownership.h:81
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1171
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4976
Represents a parameter to a function.
Definition Decl.h:1808
void setDefaultArg(Expr *defarg)
Definition Decl.cpp:2998
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1949
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1937
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition Decl.cpp:3003
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3023
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1841
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1941
bool hasInheritedDefaultArg() const
Definition Decl.h:1953
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2933
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3028
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3034
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1957
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2956
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
IdentifierInfo * getPropertyDataSetter() const
Definition ParsedAttr.h:470
IdentifierInfo * getPropertyDataGetter() const
Definition ParsedAttr.h:464
static const ParsedAttributesView & none()
Definition ParsedAttr.h:817
const ParsedAttr * getMSPropertyAttr() const
Definition ParsedAttr.h:903
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:897
bool isAddressDiscriminated() const
Definition TypeBase.h:265
Wrapper for source info for pointers.
Definition TypeLoc.h:1513
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
ArrayRef< Expr * > semantics()
Definition Expr.h:6879
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1472
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8536
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1468
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1240
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1171
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8632
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1089
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8493
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1457
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2788
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8612
Represents a template name as written in source code.
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
void removeAddressSpace()
Definition TypeBase.h:596
void removeVolatile()
Definition TypeBase.h:469
LangAS getAddressSpace() const
Definition TypeBase.h:571
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3699
Represents a struct/union/class.
Definition Decl.h:4347
bool hasFlexibleArrayMember() const
Definition Decl.h:4380
bool hasObjectMember() const
Definition Decl.h:4407
field_iterator field_end() const
Definition Decl.h:4553
field_range fields() const
Definition Decl.h:4550
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4547
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4535
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4399
bool field_empty() const
Definition Decl.h:4558
field_iterator field_begin() const
Definition Decl.cpp:5271
RedeclarableTemplateDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5352
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3637
QualType getPointeeType() const
Definition TypeBase.h:3655
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void setEntity(DeclContext *E)
Definition Scope.h:391
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:284
void AddDecl(Decl *D)
Definition Scope.h:344
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:380
void RemoveDecl(Decl *D)
Definition Scope.h:352
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:383
Scope * getDeclParent()
Definition Scope.h:317
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
void PushUsingDirective(UsingDirectiveDecl *UDir)
Definition Scope.h:635
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
A RAII object to enter scope of a compound statement.
Definition Sema.h:1315
A RAII object to temporarily push a declaration context.
Definition Sema.h:3526
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6438
DefaultedComparisonKind asComparison() const
Definition Sema.h:6470
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6467
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition Sema.h:5536
void CalledStmt(Stmt *S)
Integrate an invoked statement into the collected data.
void CalledExpr(Expr *E)
Integrate an invoked expression into the collected data.
Definition Sema.h:5578
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method)
Integrate another called method into the collected data.
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition Sema.h:9378
CXXMethodDecl * getMethod() const
Definition Sema.h:9390
RAII object to handle the state changes required to synthesize a function body.
Definition Sema.h:13621
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7803
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13148
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
void DiagnoseAbstractType(const CXXRecordDecl *RD)
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R=nullptr, const UsingDecl *UD=nullptr)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
llvm::SmallPtrSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition Sema.h:6627
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6389
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9447
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9455
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9443
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9428
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:416
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD)
Evaluate the implicit exception specification for a defaulted special member function.
void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc)
Definition Sema.h:13766
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
void ActOnFinishCXXNonNestedClass()
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, ImplicitDeallocationParameters, bool Diagnose=true)
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, Expr *DefaultArg)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
void DiagnoseStaticAssertDetails(const Expr *E)
Try to print more useful information about a failed static_assert with expression \E.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1533
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6364
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
AccessResult CheckFriendAccess(NamedDecl *D)
Checks access to the target of a friend declaration.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1262
QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc)
Looks for the std::type_identity template and instantiates it with Type, or returns a null type if ty...
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D)
ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a C++ if/switch/while/for statem...
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
DelegatingCtorDeclsType DelegatingCtorDecls
All the delegating constructors seen so far in the file, used for cycle detection at the end of the T...
Definition Sema.h:6600
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs)
ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition Sema.h:6581
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
SemaCUDA & CUDA()
Definition Sema.h:1473
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7924
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicCallType::DoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
@ AR_dependent
Definition Sema.h:1688
@ AR_accessible
Definition Sema.h:1686
@ AR_inaccessible
Definition Sema.h:1687
@ AR_delayed
Definition Sema.h:1689
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2427
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
Annotation attributes are the only attributes allowed after an access specifier.
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
void referenceDLLExportedClassMethods()
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
Definition Sema.h:4198
@ Default
= default ;
Definition Sema.h:4200
@ Delete
deleted-function-body
Definition Sema.h:4206
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition SemaStmt.cpp:49
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2077
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD)
Diagnose methods which overload virtual methods in a base class without overriding any.
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a 'using' declaration.
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal, DeclarationName Name)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag)
Is the given member accessible for the purposes of deciding whether to define a special member functi...
BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, const ParsedAttributesView &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
void ActOnFinishFunctionDeclarationDeclarator(Declarator &D)
Called after parsing a function declarator belonging to a function declaration.
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1308
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
void DiagnoseTypeTraitDetails(const Expr *E)
If E represents a built-in type trait, or a known standard type trait, try to print more information ...
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument, const Decl **MalformedDecl=nullptr)
Tests whether Ty is an instance of std::type_identity and, if it is and TypeArgument is not NULL,...
SemaObjC & ObjC()
Definition Sema.h:1518
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TrivialABIHandling::IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
void CheckDelayedMemberExceptionSpecs()
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
ASTContext & getASTContext() const
Definition Sema.h:939
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6607
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
SmallVector< std::pair< FunctionDecl *, FunctionDecl * >, 2 > DelayedEquivalentExceptionSpecChecks
All the function redeclarations seen during a class definition that had their exception spec checks d...
Definition Sema.h:6691
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void PopExpressionEvaluationContext()
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Sema.h:6159
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Sema.h:6173
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Sema.h:6170
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Sema.h:6167
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6161
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Sema.h:6164
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMemberKind > SpecialMemberDecl
Definition Sema.h:6622
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
ValueDecl * tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase)
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists)
Builds a using declaration.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12250
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1744
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8448
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2446
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
FPOptions & getCurFPFeatures()
Definition Sema.h:934
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_RequiresClause
Definition Sema.h:14577
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14532
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14550
@ UPPC_Initializer
An initializer.
Definition Sema.h:14541
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14511
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14535
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14544
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14514
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14517
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14523
Decl * ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl, bool IsNested)
ActOnStartNamespaceDef - This is called at the start of a namespace definition.
const LangOptions & getLangOpts() const
Definition Sema.h:932
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent)
DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was not used in the declaration of ...
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition Sema.h:5938
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2558
AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field)
Checks implicit access to a member in a structured binding.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier * > Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1307
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
const LangOptions & LangOpts
Definition Sema.h:1306
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6585
SemaHLSL & HLSL()
Definition Sema.h:1483
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
CXXRecordDecl * getStdBadAlloc() const
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
llvm::DenseMap< CXXRecordDecl *, bool > VTablesUsed
The set of classes whose vtables have been used within this translation unit, and a bit that will be ...
Definition Sema.h:5944
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition Sema.h:5318
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5325
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6578
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
NamedDecl * BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, TypeSourceInfo *EnumType, EnumDecl *ED)
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedOverridingExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition Sema.h:6683
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6615
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed.
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS=nullptr)
Require that the EnumDecl is completed with its enumerators defined or instantiated.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
void MarkVirtualBaseDestructorsReferenced(SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl< const CXXRecordDecl * > *DirectVirtualBases=nullptr)
Mark destructors of virtual bases of this class referenced.
void ExitDeclaratorContext(Scope *S)
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
Decl * ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceRange TyLoc, const IdentifierInfo &II, ParsedType Ty, const CXXScopeSpec &SS)
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx, StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr)
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition Sema.h:13160
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
std::pair< CXXRecordDecl *, SourceLocation > VTableUse
The list of classes whose vtables have been used within this translation unit, and the source locatio...
Definition Sema.h:5934
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:644
bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15616
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9946
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7060
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6592
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause,...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
ClassTemplateDecl * StdTypeIdentity
The C++ "std::type_identity" template, which is defined in <type_traits>.
Definition Sema.h:6611
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8263
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD)
Check that the C++ class annoated with "trivial_abi" satisfies all the conditions that are needed for...
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref< Scope *()> EnterScope)
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14054
SourceManager & getSourceManager() const
Definition Sema.h:937
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:9406
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification,...
void FilterUsingLookup(Scope *S, LookupResult &lookup)
Remove decls we can't actually see from a lookup being used to declare shadow using decls.
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
StringEvaluationContext
Definition Sema.h:6054
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
FunctionDecl * BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl, QualType AllocType, SourceLocation)
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
void DiagnoseUnknownAttribute(const ParsedAttr &AL)
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15571
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
void CheckCompleteVariableDeclaration(VarDecl *VD)
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
RedeclarationKind forRedeclarationInCurContext() const
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6603
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1584
ASTConsumer & Consumer
Definition Sema.h:1309
void ActOnFinishCXXMemberDecls()
Perform any semantic analysis which needs to be delayed until all pending class member declarations h...
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4698
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:125
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6813
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6823
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6792
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void actOnDelayedExceptionSpecification(Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member or friend function (or function template).
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1267
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckExplicitObjectLambda(Declarator &D)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)
PopPragmaVisibility - Pop the top element of the visibility stack; used for '#pragma GCC visibility' ...
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1311
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc)
Handle a C++ member initializer using parentheses syntax.
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
DiagnosticsEngine & Diags
Definition Sema.h:1310
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7873
TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
NamespaceDecl * getStdNamespace() const
llvm::SmallPtrSet< const CXXRecordDecl *, 8 > RecordDeclSetTy
Definition Sema.h:6587
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
friend class InitializationSequence
Definition Sema.h:1588
void PopDeclContext()
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6619
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD)
Check that VTable Pointer authentication is only being set on the first first instantiation of the vt...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition SemaCast.cpp:338
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6363
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
UnsignedOrNone GetDecompositionElementCount(QualType DecompType, SourceLocation Loc)
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
Decl * ActOnDeclarator(Scope *S, Declarator &D)
AbstractDiagSelID
Definition Sema.h:6309
@ AbstractVariableType
Definition Sema.h:6313
@ AbstractReturnType
Definition Sema.h:6311
@ AbstractNone
Definition Sema.h:6310
@ AbstractFieldType
Definition Sema.h:6314
@ AbstractArrayType
Definition Sema.h:6317
@ AbstractParamType
Definition Sema.h:6312
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition Sema.h:8452
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
CheckConstexprKind
Definition Sema.h:6498
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6503
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6500
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList)
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition SemaStmt.cpp:437
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D)
void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl * > &OverloadedMethods)
Check if a method overloads virtual methods in a base class without overriding any.
IdentifierResolver IdResolver
Definition Sema.h:3519
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
ExprResult ActOnCXXThis(SourceLocation Loc)
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
void warnOnReservedIdentifier(const NamedDecl *D)
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, SourceLocation DefaultLoc)
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
bool isAbstractType(SourceLocation Loc, QualType T)
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:657
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8748
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *Message, SourceLocation RParenLoc, bool Failed)
Definition DeclCXX.cpp:3668
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1503
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
bool isUnevaluated() const
Definition Expr.h:1927
StringRef getString() const
Definition Expr.h:1873
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3739
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3860
StringRef getKindName() const
Definition Decl.h:3935
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3840
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4895
bool isUnion() const
Definition Decl.h:3950
TagKind getTagKind() const
Definition Decl.h:3939
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3885
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
A convenient class for passing around template argument information.
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
TypeSourceInfo * getTypeSourceInfo() const
Represents a template argument.
@ Type
The template argument is a type.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:1917
Declaration of a template type parameter.
unsigned getIndex() const
Retrieve the index of the template parameter.
unsigned getDepth() const
Retrieve the depth of the template parameter.
The top declaration context.
Definition Decl.h:105
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3710
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5813
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3729
Declaration of an alias template.
static TypeAliasTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Represents a declaration of a type.
Definition Decl.h:3535
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1437
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:160
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:116
bool isNull() const
Definition TypeLoc.h:121
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8418
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8429
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:1970
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
bool isUndeducedAutoType() const
Definition TypeBase.h:8880
bool isRValueReferenceType() const
Definition TypeBase.h:8716
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8783
bool isPointerType() const
Definition TypeBase.h:8684
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition Type.h:63
bool isLValueReferenceType() const
Definition TypeBase.h:8712
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9019
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2465
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3183
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9230
bool isFunctionProtoType() const
Definition TypeBase.h:2661
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9200
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2864
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isFunctionType() const
Definition TypeBase.h:8680
bool isStructureOrClassType() const
Definition Type.cpp:743
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2985
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2332
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isRecordType() const
Definition TypeBase.h:8811
bool isUnionType() const
Definition Type.cpp:755
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3584
QualType getUnderlyingType() const
Definition Decl.h:3639
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2346
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5161
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1075
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1251
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1248
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1083
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1097
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1086
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1067
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1121
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1091
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:437
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
The iterator over UnresolvedSets.
A set of unresolved declarations.
This node is generated when a using-declaration that was annotated with attribute((using_if_exists)) ...
Definition DeclCXX.h:4136
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition DeclCXX.cpp:3647
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3626
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3598
Represents a C++ using-declaration.
Definition DeclCXX.h:3609
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3658
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition DeclCXX.h:3646
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3650
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition DeclCXX.cpp:3535
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition DeclCXX.h:3636
Represents C++ using-directive.
Definition DeclCXX.h:3114
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition DeclCXX.cpp:3318
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3810
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition DeclCXX.cpp:3556
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition DeclCXX.cpp:3578
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3417
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition DeclCXX.h:3453
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3481
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3475
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5589
Represents a variable declaration or definition.
Definition Decl.h:924
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2770
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2130
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1582
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2239
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2169
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2796
void setCXXCondDecl()
Definition Decl.h:1628
bool isInlineSpecified() const
Definition Decl.h:1567
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2554
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1296
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1239
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1206
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2811
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1175
const Expr * getInit() const
Definition Decl.h:1381
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:950
void setInit(Expr *I)
Definition Decl.cpp:2456
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1166
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2507
void setExceptionVariable(bool EV)
Definition Decl.h:1510
Declaration of a variable template.
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
QualType getElementType() const
Definition TypeBase.h:4253
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2832
SourceLocation getOverrideLoc() const
Definition DeclSpec.h:2852
SourceLocation getLastLocation() const
Definition DeclSpec.h:2864
bool isOverrideSpecified() const
Definition DeclSpec.h:2851
SourceLocation getFinalLoc() const
Definition DeclSpec.h:2856
bool isFinalSpecified() const
Definition DeclSpec.h:2854
bool isFinalSpelledSealed() const
Definition DeclSpec.h:2855
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
bool FoundImmediateEscalatingExpression
Whether we found an immediate-escalating expression.
Definition ScopeInfo.h:179
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition Interp.h:1179
bool Inc(InterpState &S, CodePtr OpPC, bool CanOverflow)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition Interp.h:963
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_decltype
Definition Specifiers.h:90
@ TST_typename_pack_indexing
Definition Specifiers.h:98
@ TST_decltype_auto
Definition Specifiers.h:94
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:213
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus26
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
VariadicCallType
Definition Sema.h:513
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition DeclCXX.h:3025
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
LLVM_READONLY auto escapeCStyle(CharT Ch) -> StringRef
Return C-style escaped string for special characters, or an empty string if there is no such mapping.
Definition CharInfo.h:191
@ Comparison
A comparison.
Definition Sema.h:667
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:272
@ ICIS_ListInit
Direct list-initialization.
Definition Specifiers.h:275
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1797
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1803
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
CXXConstructionKind
Definition ExprCXX.h:1544
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:633
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:238
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:1035
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1033
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1031
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1027
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1025
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1023
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1017
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1029
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1019
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1021
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_public
Definition Specifiers.h:125
@ AS_protected
Definition Specifiers.h:126
@ AS_none
Definition Specifiers.h:128
@ AS_private
Definition Specifiers.h:127
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
StorageClass
Storage classes.
Definition Specifiers.h:249
@ SC_Static
Definition Specifiers.h:253
@ SC_None
Definition Specifiers.h:251
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
Language
The language for the input, used to select and validate the language standard and possible actions.
@ Default
Set to the current date and time.
StmtResult StmtError()
Definition Ownership.h:266
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
OptionalUnsigned< unsigned > UnsignedOrNone
llvm::Expected< QualType > ExpectedType
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl< char > &OutStr)
EscapeStringForDiagnostic - Append Str to the diagnostic buffer, escaping non-printable characters an...
ReservedLiteralSuffixIdStatus
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5995
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6000
@ Struct
The "struct" keyword.
Definition TypeBase.h:5997
@ Class
The "class" keyword.
Definition TypeBase.h:6006
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
@ Type
The name was classified as a type.
Definition Sema.h:564
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ CanPassInRegs
The argument of this type can be passed directly in registers.
Definition Decl.h:4326
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4340
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4335
AllowFoldKind
Definition Sema.h:655
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
@ TNK_Concept_template
The name refers to a concept.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
TypeAwareAllocationMode
Definition ExprCXX.h:2255
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1301
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TrivialABIHandling
Definition Sema.h:645
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:650
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:647
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:385
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
TypeAwareAllocationMode typeAwareAllocationModeFromBool(bool IsTypeAwareAllocation)
Definition ExprCXX.h:2262
U cast(CodeGen::Address addr)
Definition Address.h:327
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:849
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:847
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:845
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5970
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5991
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5981
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5984
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
bool isExternallyVisible(Linkage L)
Definition Linkage.h:90
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:178
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:91
Represents an element in a path from a derived class to a base class.
bool hasValidIntValue() const
True iff we've successfully evaluated the variable as a constant expression and extracted its integer...
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
SourceLocation getEndLoc() const LLVM_READONLY
bool containsUnexpandedParameterPack() const
Determine whether this name contains an unexpanded parameter pack.
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition DeclSpec.h:1412
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1472
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1421
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1475
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1573
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1447
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition DeclSpec.h:1602
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1605
void freeParams()
Reset the parameter list to having zero parameters.
Definition DeclSpec.h:1511
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1598
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition DeclSpec.h:1387
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1287
SourceRange getSourceRange() const
Definition DeclSpec.h:1299
FunctionTypeInfo Fun
Definition DeclSpec.h:1686
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
A simple structure that captures a vtable use for the purposes of the ExternalSemaSource.
Holds information about the various types of exception specification.
Definition TypeBase.h:5428
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5440
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5430
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5433
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5436
Extra information about a function prototype.
Definition TypeBase.h:5456
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:6034
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3385
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3367
Describes how types, statements, expressions, and declarations should be printed.
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13199
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13327
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13290
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13287
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13243
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13261
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13330
Abstract class used to diagnose incomplete types.
Definition Sema.h:8344
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
Information about a template-id annotation token.
TemplateNameKind Kind
The kind of template that Template refers to.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
OpaquePtr< T > get() const
Definition Ownership.h:105