clang 24.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"
50#include "clang/Sema/Template.h"
52#include "llvm/ADT/ArrayRef.h"
53#include "llvm/ADT/STLExtras.h"
54#include "llvm/ADT/StringExtras.h"
55#include "llvm/Support/ConvertUTF.h"
56#include "llvm/Support/SaveAndRestore.h"
57#include <map>
58#include <optional>
59#include <set>
60
61using namespace clang;
62
63//===----------------------------------------------------------------------===//
64// CheckDefaultArgumentVisitor
65//===----------------------------------------------------------------------===//
66
67namespace {
68/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
69/// the default argument of a parameter to determine whether it
70/// contains any ill-formed subexpressions. For example, this will
71/// diagnose the use of local variables or parameters within the
72/// default argument expression.
73class CheckDefaultArgumentVisitor
74 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
75 Sema &S;
76 const Expr *DefaultArg;
77
78public:
79 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
80 : S(S), DefaultArg(DefaultArg) {}
81
82 bool VisitExpr(const Expr *Node);
83 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
84 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
85 bool VisitLambdaExpr(const LambdaExpr *Lambda);
86 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
87 bool VisitCoawaitExpr(const CoawaitExpr *E);
88 bool VisitCoyieldExpr(const CoyieldExpr *E);
89};
90
91/// VisitExpr - Visit all of the children of this expression.
92bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
93 bool IsInvalid = false;
94 for (const Stmt *SubStmt : Node->children())
95 if (SubStmt)
96 IsInvalid |= Visit(SubStmt);
97 return IsInvalid;
98}
99
100/// VisitDeclRefExpr - Visit a reference to a declaration, to
101/// determine whether this declaration can be used in the default
102/// argument expression.
103bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
104 const ValueDecl *Decl = DRE->getDecl();
105
106 if (!isa<VarDecl, BindingDecl>(Decl))
107 return false;
108
109 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
110 // C++ [dcl.fct.default]p9:
111 // [...] parameters of a function shall not be used in default
112 // argument expressions, even if they are not evaluated. [...]
113 //
114 // C++17 [dcl.fct.default]p9 (by CWG 2082):
115 // [...] A parameter shall not appear as a potentially-evaluated
116 // expression in a default argument. [...]
117 //
118 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
119 return S.Diag(DRE->getBeginLoc(),
120 diag::err_param_default_argument_references_param)
121 << Param->getDeclName() << DefaultArg->getSourceRange();
122 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
123 // C++ [dcl.fct.default]p7:
124 // Local variables shall not be used in default argument
125 // expressions.
126 //
127 // C++17 [dcl.fct.default]p7 (by CWG 2082):
128 // A local variable shall not appear as a potentially-evaluated
129 // expression in a default argument.
130 //
131 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
132 // Note: A local variable cannot be odr-used (6.3) in a default
133 // argument.
134 //
135 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
136 return S.Diag(DRE->getBeginLoc(),
137 diag::err_param_default_argument_references_local)
138 << Decl << DefaultArg->getSourceRange();
139 }
140 return false;
141}
142
143/// VisitCXXThisExpr - Visit a C++ "this" expression.
144bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
145 // C++ [dcl.fct.default]p8:
146 // The keyword this shall not be used in a default argument of a
147 // member function.
148 return S.Diag(ThisE->getBeginLoc(),
149 diag::err_param_default_argument_references_this)
150 << ThisE->getSourceRange();
151}
152
153bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
154 const PseudoObjectExpr *POE) {
155 bool Invalid = false;
156 for (const Expr *E : POE->semantics()) {
157 // Look through bindings.
158 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
159 E = OVE->getSourceExpr();
160 assert(E && "pseudo-object binding without source expression?");
161 }
162
163 Invalid |= Visit(E);
164 }
165 return Invalid;
166}
167
168bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
169 // [expr.prim.lambda.capture]p9
170 // a lambda-expression appearing in a default argument cannot implicitly or
171 // explicitly capture any local entity. Such a lambda-expression can still
172 // have an init-capture if any full-expression in its initializer satisfies
173 // the constraints of an expression appearing in a default argument.
174 bool Invalid = false;
175 for (const LambdaCapture &LC : Lambda->captures()) {
176 if (!Lambda->isInitCapture(&LC))
177 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
178 // Init captures are always VarDecl.
179 auto *D = cast<VarDecl>(LC.getCapturedVar());
180 Invalid |= Visit(D->getInit());
181 }
182 return Invalid;
183}
184
185bool CheckDefaultArgumentVisitor::VisitCoawaitExpr(const CoawaitExpr *E) {
186 // [expr.await] An await-expression shall not appear in a default argument.
187 // Note that this is generally diagnosed by isValidCoroutineContext,
188 // however isValidCoroutineContext misses default argument in nested
189 // function declarations.
190 S.Diag(E->getBeginLoc(), diag::err_coroutine_outside_function)
191 << "co_await" << E->getSourceRange();
192 return true;
193}
194
195bool CheckDefaultArgumentVisitor::VisitCoyieldExpr(const CoyieldExpr *E) {
196 S.Diag(E->getBeginLoc(), diag::err_coroutine_outside_function)
197 << "co_yield" << E->getSourceRange();
198 return true;
199}
200
201} // namespace
202
203void
205 const CXXMethodDecl *Method) {
206 // If we have an MSAny spec already, don't bother.
207 if (!Method || ComputedEST == EST_MSAny)
208 return;
209
210 const FunctionProtoType *Proto
211 = Method->getType()->getAs<FunctionProtoType>();
212 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
213 if (!Proto)
214 return;
215
217
218 // If we have a throw-all spec at this point, ignore the function.
219 if (ComputedEST == EST_None)
220 return;
221
222 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
223 EST = EST_BasicNoexcept;
224
225 switch (EST) {
226 case EST_Unparsed:
228 case EST_Unevaluated:
229 llvm_unreachable("should not see unresolved exception specs here");
230
231 // If this function can throw any exceptions, make a note of that.
232 case EST_MSAny:
233 case EST_None:
234 // FIXME: Whichever we see last of MSAny and None determines our result.
235 // We should make a consistent, order-independent choice here.
236 ClearExceptions();
237 ComputedEST = EST;
238 return;
240 ClearExceptions();
241 ComputedEST = EST_None;
242 return;
243 // FIXME: If the call to this decl is using any of its default arguments, we
244 // need to search them for potentially-throwing calls.
245 // If this function has a basic noexcept, it doesn't affect the outcome.
247 case EST_NoexceptTrue:
248 case EST_NoThrow:
249 return;
250 // If we're still at noexcept(true) and there's a throw() callee,
251 // change to that specification.
252 case EST_DynamicNone:
253 if (ComputedEST == EST_BasicNoexcept)
254 ComputedEST = EST_DynamicNone;
255 return;
257 llvm_unreachable(
258 "should not generate implicit declarations for dependent cases");
259 case EST_Dynamic:
260 break;
261 }
262 assert(EST == EST_Dynamic && "EST case not considered earlier.");
263 assert(ComputedEST != EST_None &&
264 "Shouldn't collect exceptions when throw-all is guaranteed.");
265 ComputedEST = EST_Dynamic;
266 // Record the exceptions in this function's exception specification.
267 for (const auto &E : Proto->exceptions())
268 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
269 Exceptions.push_back(E);
270}
271
273 if (!S || ComputedEST == EST_MSAny)
274 return;
275
276 // FIXME:
277 //
278 // C++0x [except.spec]p14:
279 // [An] implicit exception-specification specifies the type-id T if and
280 // only if T is allowed by the exception-specification of a function directly
281 // invoked by f's implicit definition; f shall allow all exceptions if any
282 // function it directly invokes allows all exceptions, and f shall allow no
283 // exceptions if every function it directly invokes allows no exceptions.
284 //
285 // Note in particular that if an implicit exception-specification is generated
286 // for a function containing a throw-expression, that specification can still
287 // be noexcept(true).
288 //
289 // Note also that 'directly invoked' is not defined in the standard, and there
290 // is no indication that we should only consider potentially-evaluated calls.
291 //
292 // Ultimately we should implement the intent of the standard: the exception
293 // specification should be the set of exceptions which can be thrown by the
294 // implicit definition. For now, we assume that any non-nothrow expression can
295 // throw any exception.
296
297 if (Self->canThrow(S))
298 ComputedEST = EST_None;
299}
300
302 SourceLocation EqualLoc) {
303 if (RequireCompleteType(Param->getLocation(), Param->getType(),
304 diag::err_typecheck_decl_incomplete_type))
305 return true;
306
307 // C++ [dcl.fct.default]p5
308 // A default argument expression is implicitly converted (clause
309 // 4) to the parameter type. The default argument expression has
310 // the same semantic constraints as the initializer expression in
311 // a declaration of a variable of the parameter type, using the
312 // copy-initialization semantics (8.5).
314 Param);
315 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
316 EqualLoc);
317 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
318 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
319 if (Result.isInvalid())
320 return true;
321 Arg = Result.getAs<Expr>();
322
323 CheckCompletedExpr(Arg, EqualLoc);
325
326 return Arg;
327}
328
330 SourceLocation EqualLoc) {
331 // Add the default argument to the parameter
332 Param->setDefaultArg(Arg);
333
334 // We have already instantiated this parameter; provide each of the
335 // instantiations with the uninstantiated default argument.
336 UnparsedDefaultArgInstantiationsMap::iterator InstPos
338 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
339 for (auto &Instantiation : InstPos->second)
340 Instantiation->setUninstantiatedDefaultArg(Arg);
341
342 // We're done tracking this parameter's instantiations.
344 }
345}
346
347void
349 Expr *DefaultArg) {
350 if (!param || !DefaultArg)
351 return;
352
353 ParmVarDecl *Param = cast<ParmVarDecl>(param);
354 UnparsedDefaultArgLocs.erase(Param);
355
356 // Default arguments are only permitted in C++
357 if (!getLangOpts().CPlusPlus) {
358 Diag(EqualLoc, diag::err_param_default_argument)
359 << DefaultArg->getSourceRange();
360 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
361 }
362
363 // C++11 [dcl.fct.default]p3
364 // A default argument expression [...] shall not be specified for a
365 // parameter pack.
366 //
367 // Check this before looking for unexpanded parameter packs in DefaultArg:
368 // if DefaultArg references a pack from an enclosing lambda/block, that
369 // check would (incorrectly) mark the lambda as containing an unexpanded
370 // pack that never actually appears in the final AST once we discard
371 // DefaultArg below.
372 if (Param->isParameterPack()) {
373 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
374 << DefaultArg->getSourceRange();
375 // Recover by discarding the default argument.
376 Param->setDefaultArg(nullptr);
377 return;
378 }
379
380 // Check for unexpanded parameter packs.
382 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
383
384 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
385 if (Result.isInvalid())
386 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
387
388 DefaultArg = Result.getAs<Expr>();
389
390 // Check that the default argument is well-formed
391 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
392 if (DefaultArgChecker.Visit(DefaultArg))
393 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
394
395 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
396}
397
399 SourceLocation EqualLoc,
400 SourceLocation ArgLoc) {
401 if (!param)
402 return;
403
404 ParmVarDecl *Param = cast<ParmVarDecl>(param);
405 Param->setUnparsedDefaultArg();
406 UnparsedDefaultArgLocs[Param] = ArgLoc;
407}
408
410 Expr *DefaultArg) {
411 if (!param)
412 return;
413
414 ParmVarDecl *Param = cast<ParmVarDecl>(param);
415 Param->setInvalidDecl();
416 UnparsedDefaultArgLocs.erase(Param);
417 ExprResult RE;
418 if (DefaultArg) {
419 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
420 Param->getType().getNonReferenceType());
421 } else {
422 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
423 Param->getType().getNonReferenceType());
424 }
425 Param->setDefaultArg(RE.get());
426}
427
429 // C++ [dcl.fct.default]p3
430 // A default argument expression shall be specified only in the
431 // parameter-declaration-clause of a function declaration or in a
432 // template-parameter (14.1). It shall not be specified for a
433 // parameter pack. If it is specified in a
434 // parameter-declaration-clause, it shall not occur within a
435 // declarator or abstract-declarator of a parameter-declaration.
436 bool MightBeFunction = D.isFunctionDeclarationContext();
437 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
438 DeclaratorChunk &chunk = D.getTypeObject(i);
439 if (chunk.Kind == DeclaratorChunk::Function) {
440 if (MightBeFunction) {
441 // This is a function declaration. It can have default arguments, but
442 // keep looking in case its return type is a function type with default
443 // arguments.
444 MightBeFunction = false;
445 continue;
446 }
447 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
448 ++argIdx) {
449 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
450 if (Param->hasUnparsedDefaultArg()) {
451 std::unique_ptr<CachedTokens> Toks =
452 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
453 SourceRange SR;
454 if (Toks->size() > 1)
455 SR = SourceRange((*Toks)[1].getLocation(),
456 Toks->back().getLocation());
457 else
458 SR = UnparsedDefaultArgLocs[Param];
459 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
460 << SR;
461 } else if (Param->getDefaultArg()) {
462 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
463 << Param->getDefaultArg()->getSourceRange();
464 Param->setDefaultArg(nullptr);
465 }
466 }
467 } else if (chunk.Kind != DeclaratorChunk::Paren) {
468 MightBeFunction = false;
469 }
470 }
471}
472
474 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
475 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
476 });
477}
478
480 Scope *S) {
481 bool Invalid = false;
482
483 // The declaration context corresponding to the scope is the semantic
484 // parent, unless this is a local function declaration, in which case
485 // it is that surrounding function.
486 DeclContext *ScopeDC = New->isLocalExternDecl()
487 ? New->getLexicalDeclContext()
488 : New->getDeclContext();
489
490 // Find the previous declaration for the purpose of default arguments.
491 FunctionDecl *PrevForDefaultArgs = Old;
492 for (/**/; PrevForDefaultArgs;
493 // Don't bother looking back past the latest decl if this is a local
494 // extern declaration; nothing else could work.
495 PrevForDefaultArgs = New->isLocalExternDecl()
496 ? nullptr
497 : PrevForDefaultArgs->getPreviousDecl()) {
498 // Ignore hidden declarations.
499 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
500 continue;
501
502 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
503 !New->isCXXClassMember()) {
504 // Ignore default arguments of old decl if they are not in
505 // the same scope and this is not an out-of-line definition of
506 // a member function.
507 continue;
508 }
509
510 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
511 // If only one of these is a local function declaration, then they are
512 // declared in different scopes, even though isDeclInScope may think
513 // they're in the same scope. (If both are local, the scope check is
514 // sufficient, and if neither is local, then they are in the same scope.)
515 continue;
516 }
517
518 if (PrevForDefaultArgs->getFriendObjectKind()) {
519 // Don't inherit default arguments from a friend declaration. It's invalid
520 // to redeclare such a function at all if it owns the default arguments;
521 // we check for that later. Otherwise, it's not the declaration that we're
522 // inheriting them from.
523 continue;
524 }
525
526 // We found the right previous declaration.
527 break;
528 }
529
530 // C++ [dcl.fct.default]p4:
531 // For non-template functions, default arguments can be added in
532 // later declarations of a function in the same
533 // scope. Declarations in different scopes have completely
534 // distinct sets of default arguments. That is, declarations in
535 // inner scopes do not acquire default arguments from
536 // declarations in outer scopes, and vice versa. In a given
537 // function declaration, all parameters subsequent to a
538 // parameter with a default argument shall have default
539 // arguments supplied in this or previous declarations. A
540 // default argument shall not be redefined by a later
541 // declaration (not even to the same value).
542 //
543 // C++ [dcl.fct.default]p6:
544 // Except for member functions of class templates, the default arguments
545 // in a member function definition that appears outside of the class
546 // definition are added to the set of default arguments provided by the
547 // member function declaration in the class definition.
548 for (unsigned p = 0, NumParams = PrevForDefaultArgs
549 ? PrevForDefaultArgs->getNumParams()
550 : 0;
551 p < NumParams; ++p) {
552 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
553 ParmVarDecl *NewParam = New->getParamDecl(p);
554
555 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
556 bool NewParamHasDfl = NewParam->hasDefaultArg();
557
558 if (OldParamHasDfl && NewParamHasDfl) {
559 unsigned DiagDefaultParamID =
560 diag::err_param_default_argument_redefinition;
561
562 // MSVC accepts that default parameters be redefined for member functions
563 // of template class. The new default parameter's value is ignored.
564 Invalid = true;
565 if (getLangOpts().MicrosoftExt) {
566 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
567 if (MD && MD->getParent()->getDescribedClassTemplate()) {
568 // Merge the old default argument into the new parameter.
569 NewParam->setHasInheritedDefaultArg();
570 if (OldParam->hasUninstantiatedDefaultArg())
572 OldParam->getUninstantiatedDefaultArg());
573 else
574 NewParam->setDefaultArg(OldParam->getInit());
575 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
576 Invalid = false;
577 }
578 }
579
580 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
581 // hint here. Alternatively, we could walk the type-source information
582 // for NewParam to find the last source location in the type... but it
583 // isn't worth the effort right now. This is the kind of test case that
584 // is hard to get right:
585 // int f(int);
586 // void g(int (*fp)(int) = f);
587 // void g(int (*fp)(int) = &f);
588 Diag(NewParam->getLocation(), DiagDefaultParamID)
589 << NewParam->getDefaultArgRange();
590
591 // Look for the function declaration where the default argument was
592 // actually written, which may be a declaration prior to Old.
593 for (auto Older = PrevForDefaultArgs;
594 OldParam->hasInheritedDefaultArg(); /**/) {
595 Older = Older->getPreviousDecl();
596 OldParam = Older->getParamDecl(p);
597 }
598
599 Diag(OldParam->getLocation(), diag::note_previous_definition)
600 << OldParam->getDefaultArgRange();
601 } else if (OldParamHasDfl) {
602 // Merge the old default argument into the new parameter unless the new
603 // function is a friend declaration in a template class. In the latter
604 // case the default arguments will be inherited when the friend
605 // declaration will be instantiated.
606 if (New->getFriendObjectKind() == Decl::FOK_None ||
607 !New->getLexicalDeclContext()->isDependentContext()) {
608 // It's important to use getInit() here; getDefaultArg()
609 // strips off any top-level ExprWithCleanups.
610 NewParam->setHasInheritedDefaultArg();
611 if (OldParam->hasUnparsedDefaultArg())
612 NewParam->setUnparsedDefaultArg();
613 else if (OldParam->hasUninstantiatedDefaultArg())
615 OldParam->getUninstantiatedDefaultArg());
616 else
617 NewParam->setDefaultArg(OldParam->getInit());
618 }
619 } else if (NewParamHasDfl) {
620 if (New->getDescribedFunctionTemplate()) {
621 // Paragraph 4, quoted above, only applies to non-template functions.
622 Diag(NewParam->getLocation(),
623 diag::err_param_default_argument_template_redecl)
624 << NewParam->getDefaultArgRange();
625 Diag(PrevForDefaultArgs->getLocation(),
626 diag::note_template_prev_declaration)
627 << false;
628 } else if (New->getTemplateSpecializationKind()
630 New->getTemplateSpecializationKind() != TSK_Undeclared) {
631 // C++ [temp.expr.spec]p21:
632 // Default function arguments shall not be specified in a declaration
633 // or a definition for one of the following explicit specializations:
634 // - the explicit specialization of a function template;
635 // - the explicit specialization of a member function template;
636 // - the explicit specialization of a member function of a class
637 // template where the class template specialization to which the
638 // member function specialization belongs is implicitly
639 // instantiated.
640 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
641 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
642 << New->getDeclName()
643 << NewParam->getDefaultArgRange();
644 } else if (New->getDeclContext()
645 ->getEnclosingNonExpansionStatementContext()
646 ->isDependentContext()) {
647 // C++ [dcl.fct.default]p6 (DR217):
648 // Default arguments for a member function of a class template shall
649 // be specified on the initial declaration of the member function
650 // within the class template.
651 //
652 // Reading the tea leaves a bit in DR217 and its reference to DR205
653 // leads me to the conclusion that one cannot add default function
654 // arguments for an out-of-line definition of a member function of a
655 // dependent type.
656 int WhichKind = 2;
658 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
659 if (Record->getDescribedClassTemplate())
660 WhichKind = 0;
662 WhichKind = 1;
663 else
664 WhichKind = 2;
665 }
666
667 Diag(NewParam->getLocation(),
668 diag::err_param_default_argument_member_template_redecl)
669 << WhichKind
670 << NewParam->getDefaultArgRange();
671 }
672 }
673 }
674
675 // DR1344: If a default argument is added outside a class definition and that
676 // default argument makes the function a special member function, the program
677 // is ill-formed. This can only happen for constructors.
679 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
681 cast<CXXMethodDecl>(New)->getSpecialMemberKind(),
682 OldSM =
683 cast<CXXMethodDecl>(Old)->getSpecialMemberKind();
684 if (NewSM != OldSM) {
685 auto It = llvm::find_if(New->parameters(), [](const ParmVarDecl *P) {
686 return P->hasDefaultArg();
687 });
688 assert(It != New->param_end());
689 ParmVarDecl *NewParam = *It;
690 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
691 << NewParam->getDefaultArgRange() << NewSM;
692 Diag(Old->getLocation(), diag::note_previous_declaration);
693 }
694 }
695
696 const FunctionDecl *Def;
697 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
698 // template has a constexpr specifier then all its declarations shall
699 // contain the constexpr specifier.
700 if (New->getConstexprKind() != Old->getConstexprKind()) {
701 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
702 << New << static_cast<int>(New->getConstexprKind())
703 << static_cast<int>(Old->getConstexprKind());
704 Diag(Old->getLocation(), diag::note_previous_declaration);
705 Invalid = true;
706 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
707 Old->isDefined(Def) &&
708 // If a friend function is inlined but does not have 'inline'
709 // specifier, it is a definition. Do not report attribute conflict
710 // in this case, redefinition will be diagnosed later.
711 (New->isInlineSpecified() ||
712 New->getFriendObjectKind() == Decl::FOK_None)) {
713 // C++11 [dcl.fcn.spec]p4:
714 // If the definition of a function appears in a translation unit before its
715 // first declaration as inline, the program is ill-formed.
716 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
717 Diag(Def->getLocation(), diag::note_previous_definition);
718 Invalid = true;
719 }
720
721 // C++17 [temp.deduct.guide]p3:
722 // Two deduction guide declarations in the same translation unit
723 // for the same class template shall not have equivalent
724 // parameter-declaration-clauses.
726 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
727 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
728 Diag(Old->getLocation(), diag::note_previous_declaration);
729 }
730
731 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
732 // argument expression, that declaration shall be a definition and shall be
733 // the only declaration of the function or function template in the
734 // translation unit.
737 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
738 Diag(Old->getLocation(), diag::note_previous_declaration);
739 Invalid = true;
740 }
741
742 // C++11 [temp.friend]p4 (DR329):
743 // When a function is defined in a friend function declaration in a class
744 // template, the function is instantiated when the function is odr-used.
745 // The same restrictions on multiple declarations and definitions that
746 // apply to non-template function declarations and definitions also apply
747 // to these implicit definitions.
748 const FunctionDecl *OldDefinition = nullptr;
749 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
750 Old->isDefined(OldDefinition, true))
751 CheckForFunctionRedefinition(New, OldDefinition);
752
753 return Invalid;
754}
755
757 DiagCompat(Loc, diag_compat::placeholder_var_definition);
758}
759
760NamedDecl *
762 MultiTemplateParamsArg TemplateParamLists) {
763 assert(D.isDecompositionDeclarator());
765
766 // The syntax only allows a decomposition declarator as a simple-declaration,
767 // a for-range-declaration, or a condition in Clang, but we parse it in more
768 // cases than that.
770 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
771 << Decomp.getSourceRange();
772 return nullptr;
773 }
774
775 if (!TemplateParamLists.empty()) {
776 // C++17 [temp]/1:
777 // A template defines a family of class, functions, or variables, or an
778 // alias for a family of types.
779 //
780 // Structured bindings are not included.
781 Diag(TemplateParamLists.front()->getTemplateLoc(),
782 diag::err_decomp_decl_template);
783 return nullptr;
784 }
785
786 unsigned DiagID;
788 DiagID = diag::compat_pre_cxx17_decomp_decl;
790 DiagID = getLangOpts().CPlusPlus26
791 ? diag::compat_cxx26_decomp_decl_cond
792 : diag::compat_pre_cxx26_decomp_decl_cond;
793 else
794 DiagID = diag::compat_cxx17_decomp_decl;
795
796 Diag(Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
797
798 // The semantic context is always just the current context.
799 DeclContext *const DC = CurContext;
800
801 // C++17 [dcl.dcl]/8:
802 // The decl-specifier-seq shall contain only the type-specifier auto
803 // and cv-qualifiers.
804 // C++20 [dcl.dcl]/8:
805 // If decl-specifier-seq contains any decl-specifier other than static,
806 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
807 // C++23 [dcl.pre]/6:
808 // Each decl-specifier in the decl-specifier-seq shall be static,
809 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
810 // C++23 [dcl.pre]/7:
811 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
812 // constinit, static, thread_local, auto, or a cv-qualifier
813 auto &DS = D.getDeclSpec();
814 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
815 Diag(Loc, diag::err_decomp_decl_spec) << Name;
816 };
817
818 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
819 DiagCompat(Loc, diag_compat::decomp_decl_spec) << Name;
820 };
821
822 if (auto SCS = DS.getStorageClassSpec()) {
823 if (SCS == DeclSpec::SCS_static)
824 DiagCpp20Specifier(DeclSpec::getSpecifierName(SCS),
825 DS.getStorageClassSpecLoc());
826 else
827 DiagBadSpecifier(DeclSpec::getSpecifierName(SCS),
828 DS.getStorageClassSpecLoc());
829 }
830 if (auto TSCS = DS.getThreadStorageClassSpec())
831 DiagCpp20Specifier(DeclSpec::getSpecifierName(TSCS),
832 DS.getThreadStorageClassSpecLoc());
833
834 if (DS.isInlineSpecified())
835 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
836
837 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
838 ConstexprSpec != ConstexprSpecKind::Unspecified) {
839 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
841 DiagBadSpecifier(DeclSpec::getSpecifierName(ConstexprSpec),
842 DS.getConstexprSpecLoc());
843 }
844
845 // We can't recover from it being declared as a typedef.
846 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
847 return nullptr;
848
849 // C++2a [dcl.struct.bind]p1:
850 // A cv that includes volatile is deprecated
851 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
853 Diag(DS.getVolatileSpecLoc(),
854 diag::warn_deprecated_volatile_structured_binding);
855
857 QualType R = TInfo->getType();
858
861 D.setInvalidType();
862
863 // The syntax only allows a single ref-qualifier prior to the decomposition
864 // declarator. No other declarator chunks are permitted. Also check the type
865 // specifier here.
866 if (DS.getTypeSpecType() != DeclSpec::TST_auto || D.hasGroupingParens() ||
867 D.getNumTypeObjects() > 1 ||
868 (D.getNumTypeObjects() == 1 &&
870 Diag(Decomp.getLSquareLoc(),
871 (D.hasGroupingParens() ||
872 (D.getNumTypeObjects() &&
874 ? diag::err_decomp_decl_parens
875 : diag::err_decomp_decl_type)
876 << R;
877
878 // In most cases, there's no actual problem with an explicitly-specified
879 // type, but a function type won't work here, and ActOnVariableDeclarator
880 // shouldn't be called for such a type.
881 if (R->isFunctionType())
882 D.setInvalidType();
883
884 // Recover from an invalid 'auto *' structured binding by removing the
885 // pointer declarator. This allows type deduction to proceed and keeps
886 // the bindings usable in subsequent code.
887 if (D.getNumTypeObjects() == 1 &&
889 D.getTypeObject(0).Ptr.TypeQuals == 0) {
891 TInfo = GetTypeForDeclarator(D);
892 R = TInfo->getType();
893 }
894 }
895
896 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
897 if (DS.isConstrainedAuto()) {
898 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
899 assert(TemplRep->Kind == TNK_Concept_template &&
900 "No other template kind should be possible for a constrained auto");
901
902 SourceRange TemplRange{TemplRep->TemplateNameLoc,
903 TemplRep->RAngleLoc.isValid()
904 ? TemplRep->RAngleLoc
905 : TemplRep->TemplateNameLoc};
906 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
907 << TemplRange << FixItHint::CreateRemoval(TemplRange);
908 }
909
910 // Build the BindingDecls.
912
913 // Build the BindingDecls.
914 for (auto &B : D.getDecompositionDeclarator().bindings()) {
915 // Check for name conflicts.
916 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
917 IdentifierInfo *VarName = B.Name;
918 assert(VarName && "Cannot have an unnamed binding declaration");
919
923 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
924
925 // It's not permitted to shadow a template parameter name.
926 if (Previous.isSingleResult() &&
927 Previous.getFoundDecl()->isTemplateParameter()) {
928 DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());
929 Previous.clear();
930 }
931
932 QualType QT;
933 if (B.EllipsisLoc.isValid()) {
934 if (!cast<Decl>(DC)->isTemplated())
935 Diag(B.EllipsisLoc, diag::err_pack_outside_template);
936 QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,
937 /*ExpectsPackInType=*/false);
938 }
939
940 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
941
942 if (BD->isParameterPack()) {
944 CSI->LocalPacks.push_back(BD);
945 }
946
947 ProcessDeclAttributeList(S, BD, *B.Attrs);
948
949 // Find the shadowed declaration before filtering for scope.
950 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
952 : nullptr;
953
954 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
955 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
956 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
957 /*AllowInlineNamespace*/false);
958
959 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
960 DC->isFunctionOrMethod() && VarName->isPlaceholder();
961 if (!Previous.empty()) {
962 if (IsPlaceholder) {
963 bool sameDC = (Previous.end() - 1)
964 ->getDeclContext()
965 ->getRedeclContext()
966 ->Equals(DC->getRedeclContext());
967 if (sameDC &&
968 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
969 Previous.clear();
971 }
972 } else {
973 auto *Old = Previous.getRepresentativeDecl();
974 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
975 Diag(Old->getLocation(), diag::note_previous_definition);
976 }
977 } else if (ShadowedDecl && !D.isRedeclaration()) {
978 CheckShadow(BD, ShadowedDecl, Previous);
979 }
980 PushOnScopeChains(BD, S, true);
981 Bindings.push_back(BD);
982 ParsingInitForAutoVars.insert(BD);
983 }
984
985 // There are no prior lookup results for the variable itself, because it
986 // is unnamed.
987 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
988 Decomp.getLSquareLoc());
991
992 // Build the variable that holds the non-decomposed object.
993 bool AddToScope = true;
994 NamedDecl *New =
995 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
996 MultiTemplateParamsArg(), AddToScope, Bindings);
997 if (AddToScope) {
998 S->AddDecl(New);
999 CurContext->addHiddenDecl(New);
1000 }
1001
1002 if (OpenMP().isInOpenMPDeclareTargetContext())
1003 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
1004
1005 return New;
1006}
1007
1008// Check the arity of the structured bindings.
1009// Create the resolved pack expr if needed.
1011 QualType DecompType,
1013 unsigned MemberCount) {
1014 auto BindingWithPackItr = llvm::find_if(
1015 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1016 bool HasPack = BindingWithPackItr != Bindings.end();
1017 bool IsValid;
1018 if (!HasPack) {
1019 IsValid = Bindings.size() == MemberCount;
1020 } else {
1021 // There may not be more members than non-pack bindings.
1022 IsValid = MemberCount >= Bindings.size() - 1;
1023 }
1024
1025 if (IsValid && HasPack) {
1026 // Create the pack expr and assign it to the binding.
1027 unsigned PackSize = MemberCount - Bindings.size() + 1;
1028
1029 BindingDecl *BPack = *BindingWithPackItr;
1030 BPack->setDecomposedDecl(DD);
1031 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
1032 // Create the nested BindingDecls.
1033 for (unsigned I = 0; I < PackSize; ++I) {
1034 BindingDecl *NestedBD = BindingDecl::Create(
1035 S.Context, BPack->getDeclContext(), BPack->getLocation(),
1036 BPack->getIdentifier(), QualType());
1037 NestedBD->setDecomposedDecl(DD);
1038 NestedBDs[I] = NestedBD;
1039 }
1040
1042 S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);
1043 auto *PackExpr = FunctionParmPackExpr::Create(
1044 S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);
1045 BPack->setBinding(PackType, PackExpr);
1046 }
1047
1048 if (IsValid)
1049 return false;
1050
1051 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1052 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1053 << (MemberCount < Bindings.size());
1054 return true;
1055}
1056
1059 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1060 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1061 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1062 auto *DD = cast<DecompositionDecl>(Src);
1063
1064 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1065 return true;
1066
1067 unsigned I = 0;
1068 for (auto *B : DD->flat_bindings()) {
1069 SourceLocation Loc = B->getLocation();
1070 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1071 if (E.isInvalid())
1072 return true;
1073 E = GetInit(Loc, E.get(), I++);
1074 if (E.isInvalid())
1075 return true;
1076 B->setBinding(ElemType, E.get());
1077 }
1078
1079 return false;
1080}
1081
1084 ValueDecl *Src, QualType DecompType,
1085 const llvm::APSInt &NumElems,
1086 QualType ElemType) {
1088 S, Bindings, Src, DecompType, NumElems, ElemType,
1089 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1090 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1091 if (E.isInvalid())
1092 return ExprError();
1093 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1094 });
1095}
1096
1098 ValueDecl *Src, QualType DecompType,
1099 const ConstantArrayType *CAT) {
1100 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1101 llvm::APSInt(CAT->getSize()),
1102 CAT->getElementType());
1103}
1104
1106 ValueDecl *Src, QualType DecompType,
1107 const VectorType *VT) {
1109 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1111 DecompType.getQualifiers()));
1112}
1113
1116 ValueDecl *Src, QualType DecompType,
1117 const ComplexType *CT) {
1119 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1121 DecompType.getQualifiers()),
1122 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1123 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1124 });
1125}
1126
1129 const TemplateParameterList *Params) {
1131 llvm::raw_svector_ostream OS(SS);
1132 bool First = true;
1133 unsigned I = 0;
1134 for (auto &Arg : Args.arguments()) {
1135 if (!First)
1136 OS << ", ";
1137 Arg.getArgument().print(PrintingPolicy, OS,
1139 PrintingPolicy, Params, I));
1140 First = false;
1141 I++;
1142 }
1143 return std::string(OS.str());
1144}
1145
1146static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1147 TemplateArgumentListInfo &Args, unsigned DiagID) {
1148 auto DiagnoseMissing = [&] {
1149 if (DiagID)
1150 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1151 Args, /*Params*/ nullptr);
1152 return QualType();
1153 };
1154
1155 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1156 NamespaceDecl *Std = S.getStdNamespace();
1157 if (!Std)
1158 return DiagnoseMissing();
1159
1160 // Look up the trait itself, within namespace std. We can diagnose various
1161 // problems with this lookup even if we've been asked to not diagnose a
1162 // missing specialization, because this can only fail if the user has been
1163 // declaring their own names in namespace std or we don't support the
1164 // standard library implementation in use.
1165 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), Loc,
1167 if (!S.LookupQualifiedName(Result, Std))
1168 return DiagnoseMissing();
1169 if (Result.isAmbiguous())
1170 return QualType();
1171
1172 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1173 if (!TraitTD) {
1174 Result.suppressDiagnostics();
1175 NamedDecl *Found = *Result.begin();
1176 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1177 S.Diag(Found->getLocation(), diag::note_declared_at);
1178 return QualType();
1179 }
1180
1181 // Build the template-id.
1182 QualType TraitTy = S.CheckTemplateIdType(
1183 ElaboratedTypeKeyword::None, TemplateName(TraitTD), Loc, Args,
1184 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1185 if (TraitTy.isNull())
1186 return QualType();
1187
1188 if (!S.isCompleteType(Loc, TraitTy)) {
1189 if (DiagID)
1191 Loc, TraitTy, DiagID,
1193 TraitTD->getTemplateParameters()));
1194 return QualType();
1195 }
1196 return TraitTy;
1197}
1198
1199static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1200 LookupResult &MemberLookup) {
1201 assert(RD && "specialization of class template is not a class?");
1202 S.LookupQualifiedName(MemberLookup, RD);
1203 return MemberLookup.isAmbiguous();
1204}
1205
1206static TemplateArgumentLoc
1208 uint64_t I) {
1210 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1211}
1212
1213static TemplateArgumentLoc
1217
1218namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1219
1220static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1221 unsigned &OutSize) {
1224
1225 // Form template argument list for tuple_size<T>.
1226 TemplateArgumentListInfo Args(Loc, Loc);
1228
1229 QualType TraitTy = getStdTrait(S, Loc, "tuple_size", Args, /*DiagID=*/0);
1230 if (TraitTy.isNull())
1231 return IsTupleLike::NotTupleLike;
1232
1235
1236 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1237 // it's not tuple-like.
1238 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R) || R.empty())
1239 return IsTupleLike::NotTupleLike;
1240
1241 // If we get this far, we've committed to the tuple interpretation, but
1242 // we can still fail if there actually isn't a usable ::value.
1243
1244 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1245 LookupResult &R;
1247 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1248 : R(R), Args(Args) {}
1249 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1250 SourceLocation Loc) override {
1251 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1253 /*Params*/ nullptr);
1254 }
1255 } Diagnoser(R, Args);
1256
1257 ExprResult E =
1258 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1259 if (E.isInvalid())
1260 return IsTupleLike::Error;
1261
1262 llvm::APSInt Size;
1263 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1264 if (E.isInvalid())
1265 return IsTupleLike::Error;
1266
1267 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1268 // an UnsignedOrNone.
1269 if (Size < 0 || Size >= UINT_MAX) {
1271 Size.toString(Str);
1272 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_invalid)
1274 /*Params=*/nullptr)
1275 << StringRef(Str.data(), Str.size());
1276 return IsTupleLike::Error;
1277 }
1278
1279 OutSize = Size.getExtValue();
1280 return IsTupleLike::TupleLike;
1281}
1282
1283/// \return std::tuple_element<I, T>::type.
1285 unsigned I, QualType T) {
1286 // Form template argument list for tuple_element<I, T>.
1287 TemplateArgumentListInfo Args(Loc, Loc);
1288 Args.addArgument(
1291
1292 QualType TraitTy =
1293 getStdTrait(S, Loc, "tuple_element", Args,
1294 diag::err_decomp_decl_std_tuple_element_not_specialized);
1295 if (TraitTy.isNull())
1296 return QualType();
1297
1298 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1299 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1300 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R))
1301 return QualType();
1302
1303 auto *TD = R.getAsSingle<TypeDecl>();
1304 if (!TD) {
1305 R.suppressDiagnostics();
1306 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1308 /*Params*/ nullptr);
1309 if (!R.empty())
1310 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1311 return QualType();
1312 }
1313
1314 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1315 return S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, Qualifier, TD);
1316}
1317
1318namespace {
1319struct InitializingBinding {
1320 Sema &S;
1321 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1322 Sema::CodeSynthesisContext Ctx;
1325 Ctx.Entity = BD;
1327 }
1328 ~InitializingBinding() {
1330 }
1331};
1332}
1333
1336 VarDecl *Src, QualType DecompType,
1337 unsigned NumElems) {
1338 auto *DD = cast<DecompositionDecl>(Src);
1339 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1340 return true;
1341
1342 if (Bindings.empty())
1343 return false;
1344
1345 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1346
1347 // [dcl.decomp]p3:
1348 // The unqualified-id get is looked up in the scope of E by class member
1349 // access lookup ...
1350 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1351 bool UseMemberGet = false;
1352 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1353 if (auto *RD = DecompType->getAsCXXRecordDecl())
1354 S.LookupQualifiedName(MemberGet, RD);
1355 if (MemberGet.isAmbiguous())
1356 return true;
1357 // ... and if that finds at least one declaration that is a function
1358 // template whose first template parameter is a non-type parameter ...
1359 for (NamedDecl *D : MemberGet) {
1360 if (FunctionTemplateDecl *FTD =
1361 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1362 TemplateParameterList *TPL = FTD->getTemplateParameters();
1363 if (TPL->size() != 0 &&
1365 // ... the initializer is e.get<i>().
1366 UseMemberGet = true;
1367 break;
1368 }
1369 }
1370 }
1371 }
1372
1373 unsigned I = 0;
1374 for (auto *B : DD->flat_bindings()) {
1375 InitializingBinding InitContext(S, B);
1376 SourceLocation Loc = B->getLocation();
1377
1378 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1379 if (E.isInvalid())
1380 return true;
1381
1382 // e is an lvalue if the type of the entity is an lvalue reference and
1383 // an xvalue otherwise
1384 if (!Src->getType()->isLValueReferenceType())
1385 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1386 E.get(), nullptr, VK_XValue,
1388
1389 TemplateArgumentListInfo Args(Loc, Loc);
1390 Args.addArgument(
1392
1393 if (UseMemberGet) {
1394 // if [lookup of member get] finds at least one declaration, the
1395 // initializer is e.get<i-1>().
1396 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1397 CXXScopeSpec(), SourceLocation(), nullptr,
1398 MemberGet, &Args, nullptr);
1399 if (E.isInvalid())
1400 return true;
1401
1402 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1403 } else {
1404 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1405 // in the associated namespaces.
1408 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1410 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1411
1412 Expr *Arg = E.get();
1413 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1414 }
1415 if (E.isInvalid())
1416 return true;
1417 Expr *Init = E.get();
1418
1419 // Given the type T designated by std::tuple_element<i - 1, E>::type
1420 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1421 if (T.isNull())
1422 return true;
1423
1424 // C++26 [dcl.struct.bind]p7:
1425 // and the type Ui, defined as Ti if the initializer is a prvalue,
1426 // as "lvalue reference to Ti" if the initializer is an lvalue,
1427 // or as "rvalue reference to Ti" otherwise
1428 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1429 QualType U = E.get()->isPRValue()
1430 ? T
1431 : S.BuildReferenceType(T, E.get()->isLValue(), Loc,
1432 B->getDeclName());
1433 if (U.isNull())
1434 return true;
1435
1436 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1437 // entity and this type was never written in source code.
1438 auto *BindingVD =
1439 VarDecl::Create(S.Context, Src->getDeclContext(), Loc, Loc,
1440 B->getDeclName().getAsIdentifierInfo(), U,
1441 /*TInfo=*/nullptr, Src->getStorageClass());
1442 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1443 BindingVD->setTSCSpec(Src->getTSCSpec());
1444 BindingVD->setConstexpr(Src->isConstexpr());
1445 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1446 BindingVD->addAttr(CIAttr->clone(S.Context));
1447 BindingVD->setImplicit();
1448 if (Src->isInlineSpecified())
1449 BindingVD->setInlineSpecified();
1450 BindingVD->getLexicalDeclContext()->addHiddenDecl(BindingVD);
1451
1454 InitializationSequence Seq(S, Entity, Kind, Init);
1455 E = Seq.Perform(S, Entity, Kind, Init);
1456 if (E.isInvalid())
1457 return true;
1458 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1459 if (E.isInvalid())
1460 return true;
1461 BindingVD->setInit(E.get());
1463
1465 CXXScopeSpec(), DeclarationNameInfo(B->getDeclName(), Loc), BindingVD);
1466 if (E.isInvalid())
1467 return true;
1468
1469 B->setBinding(T, E.get());
1470 I++;
1471 }
1472
1473 return false;
1474}
1475
1476/// Find the base class to decompose in a built-in decomposition of a class type.
1477/// This base class search is, unfortunately, not quite like any other that we
1478/// perform anywhere else in C++.
1480 const CXXRecordDecl *RD,
1481 CXXCastPath &BasePath) {
1482 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1483 CXXBasePath &Path) {
1484 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1485 };
1486
1487 const CXXRecordDecl *ClassWithFields = nullptr;
1489 if (RD->hasDirectFields())
1490 // [dcl.decomp]p4:
1491 // Otherwise, all of E's non-static data members shall be public direct
1492 // members of E ...
1493 ClassWithFields = RD;
1494 else {
1495 // ... or of ...
1496 CXXBasePaths Paths;
1497 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1498 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1499 // If no classes have fields, just decompose RD itself. (This will work
1500 // if and only if zero bindings were provided.)
1501 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1502 }
1503
1504 CXXBasePath *BestPath = nullptr;
1505 for (auto &P : Paths) {
1506 if (!BestPath)
1507 BestPath = &P;
1508 else if (!S.Context.hasSameType(P.back().Base->getType(),
1509 BestPath->back().Base->getType())) {
1510 // ... the same ...
1511 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1512 << false << RD << BestPath->back().Base->getType()
1513 << P.back().Base->getType();
1514 return DeclAccessPair();
1515 } else if (P.Access < BestPath->Access) {
1516 BestPath = &P;
1517 }
1518 }
1519
1520 // ... unambiguous ...
1521 QualType BaseType = BestPath->back().Base->getType();
1522 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1523 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1524 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1525 return DeclAccessPair();
1526 }
1527
1528 // ... [accessible, implied by other rules] base class of E.
1529 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getCanonicalTagType(RD),
1530 *BestPath, diag::err_decomp_decl_inaccessible_base);
1531 AS = BestPath->Access;
1532
1533 ClassWithFields = BaseType->getAsCXXRecordDecl();
1534 S.BuildBasePathArray(Paths, BasePath);
1535 }
1536
1537 // The above search did not check whether the selected class itself has base
1538 // classes with fields, so check that now.
1539 CXXBasePaths Paths;
1540 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1541 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1542 << (ClassWithFields == RD) << RD << ClassWithFields
1543 << Paths.front().back().Base->getType();
1544 return DeclAccessPair();
1545 }
1546
1547 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1548}
1549
1551 const CXXRecordDecl *OrigRD,
1552 QualType DecompType,
1553 DeclAccessPair BasePair) {
1554 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1555 if (!RD)
1556 return true;
1557
1558 for (auto *FD : RD->fields()) {
1559 if (FD->isUnnamedBitField())
1560 continue;
1561
1562 // All the non-static data members are required to be nameable, so they
1563 // must all have names.
1564 if (!FD->getDeclName()) {
1565 if (RD->isLambda()) {
1566 S.Diag(Loc, diag::err_decomp_decl_lambda);
1567 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1568 return true;
1569 }
1570
1571 if (FD->isAnonymousStructOrUnion()) {
1572 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1573 << DecompType << FD->getType()->isUnionType();
1574 S.Diag(FD->getLocation(), diag::note_declared_at);
1575 return true;
1576 }
1577
1578 // FIXME: Are there any other ways we could have an anonymous member?
1579 }
1580 // The field must be accessible in the context of the structured binding.
1581 // We already checked that the base class is accessible.
1582 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1583 // const_cast here.
1585 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1587 BasePair.getAccess(), FD->getAccess())));
1588 }
1589 return false;
1590}
1591
1593 ValueDecl *Src, QualType DecompType,
1594 const CXXRecordDecl *OrigRD) {
1595 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1596 diag::err_incomplete_type))
1597 return true;
1598
1599 CXXCastPath BasePath;
1600 DeclAccessPair BasePair =
1601 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1602 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1603 if (!RD)
1604 return true;
1605 QualType BaseType = S.Context.getQualifiedType(
1606 S.Context.getCanonicalTagType(RD), DecompType.getQualifiers());
1607
1608 auto *DD = cast<DecompositionDecl>(Src);
1609 unsigned NumFields = llvm::count_if(
1610 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1611 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))
1612 return true;
1613
1614 // all of E's non-static data members shall be [...] well-formed
1615 // when named as e.name in the context of the structured binding,
1616 // E shall not have an anonymous union member, ...
1617 auto FlatBindings = DD->flat_bindings();
1618 assert(llvm::range_size(FlatBindings) == NumFields);
1619 auto FlatBindingsItr = FlatBindings.begin();
1620
1621 if (CheckMemberDecompositionFields(S, Src->getLocation(), OrigRD, DecompType,
1622 BasePair))
1623 return true;
1624
1625 for (auto *FD : RD->fields()) {
1626 if (FD->isUnnamedBitField())
1627 continue;
1628
1629 // We have a real field to bind.
1630 assert(FlatBindingsItr != FlatBindings.end());
1631 BindingDecl *B = *(FlatBindingsItr++);
1632 SourceLocation Loc = B->getLocation();
1633
1634 // Initialize the binding to Src.FD.
1635 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1636 if (E.isInvalid())
1637 return true;
1638 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1639 VK_LValue, &BasePath);
1640 if (E.isInvalid())
1641 return true;
1642 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1643 CXXScopeSpec(), FD,
1645 DeclarationNameInfo(FD->getDeclName(), Loc));
1646 if (E.isInvalid())
1647 return true;
1648
1649 // If the type of the member is T, the referenced type is cv T, where cv is
1650 // the cv-qualification of the decomposition expression.
1651 //
1652 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1653 // 'const' to the type of the field.
1654 Qualifiers Q = DecompType.getQualifiers();
1655 if (FD->isMutable())
1656 Q.removeConst();
1657 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1658 }
1659
1660 return false;
1661}
1662
1664 QualType DecompType = DD->getType();
1665
1666 // If the type of the decomposition is dependent, then so is the type of
1667 // each binding.
1668 if (DecompType->isDependentType()) {
1669 // Note that all of the types are still Null or PackExpansionType.
1670 for (auto *B : DD->bindings()) {
1671 // Do not overwrite any pack type.
1672 if (B->getType().isNull())
1673 B->setType(Context.DependentTy);
1674 }
1675 return;
1676 }
1677
1678 DecompType = DecompType.getNonReferenceType();
1680
1681 // C++1z [dcl.decomp]/2:
1682 // If E is an array type [...]
1683 // As an extension, we also support decomposition of built-in complex and
1684 // vector types.
1685 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1686 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1687 DD->setInvalidDecl();
1688 return;
1689 }
1690 if (auto *VT = DecompType->getAs<VectorType>()) {
1691 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1692 DD->setInvalidDecl();
1693 return;
1694 }
1695 if (auto *CT = DecompType->getAs<ComplexType>()) {
1696 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1697 DD->setInvalidDecl();
1698 return;
1699 }
1700
1701 // C++1z [dcl.decomp]/3:
1702 // if the expression std::tuple_size<E>::value is a well-formed integral
1703 // constant expression, [...]
1704 unsigned TupleSize;
1705 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1706 case IsTupleLike::Error:
1707 DD->setInvalidDecl();
1708 return;
1709
1710 case IsTupleLike::TupleLike:
1711 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1712 DD->setInvalidDecl();
1713 return;
1714
1715 case IsTupleLike::NotTupleLike:
1716 break;
1717 }
1718
1719 // C++1z [dcl.dcl]/8:
1720 // [E shall be of array or non-union class type]
1721 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1722 if (!RD || RD->isUnion()) {
1723 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1724 << DD << !RD << DecompType;
1725 DD->setInvalidDecl();
1726 return;
1727 }
1728
1729 // C++1z [dcl.decomp]/4:
1730 // all of E's non-static data members shall be [...] direct members of
1731 // E or of the same unambiguous public base class of E, ...
1732 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1733 DD->setInvalidDecl();
1734}
1735
1737 SourceLocation Loc) {
1738 const ASTContext &Ctx = getASTContext();
1739 assert(!T->isDependentType());
1740
1741 Qualifiers Quals;
1742 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1743 Quals.removeCVRQualifiers();
1744 T = Context.getQualifiedType(Unqual, Quals);
1745
1746 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1747 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1748 if (auto *VT = T->getAs<VectorType>())
1749 return VT->getNumElements();
1750 if (T->getAs<ComplexType>())
1751 return 2u;
1752
1753 unsigned TupleSize;
1754 switch (isTupleLike(*this, Loc, T, TupleSize)) {
1755 case IsTupleLike::Error:
1756 return std::nullopt;
1757 case IsTupleLike::TupleLike:
1758 return TupleSize;
1759 case IsTupleLike::NotTupleLike:
1760 break;
1761 }
1762
1763 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1764 if (!OrigRD || OrigRD->isUnion())
1765 return std::nullopt;
1766
1767 if (RequireCompleteType(Loc, T, diag::err_incomplete_type))
1768 return std::nullopt;
1769
1770 CXXCastPath BasePath;
1771 DeclAccessPair BasePair =
1772 findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);
1773 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1774 if (!RD)
1775 return std::nullopt;
1776
1777 unsigned NumFields = llvm::count_if(
1778 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1779
1780 if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))
1781 return std::nullopt;
1782
1783 return NumFields;
1784}
1785
1787 // Shortcut if exceptions are disabled.
1788 if (!getLangOpts().CXXExceptions)
1789 return;
1790
1791 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1792 "Should only be called if types are otherwise the same.");
1793
1794 QualType NewType = New->getType();
1795 QualType OldType = Old->getType();
1796
1797 // We're only interested in pointers and references to functions, as well
1798 // as pointers to member functions.
1799 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1800 NewType = R->getPointeeType();
1801 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1802 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1803 NewType = P->getPointeeType();
1804 OldType = OldType->castAs<PointerType>()->getPointeeType();
1805 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1806 NewType = M->getPointeeType();
1807 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1808 }
1809
1810 if (!NewType->isFunctionProtoType())
1811 return;
1812
1813 // There's lots of special cases for functions. For function pointers, system
1814 // libraries are hopefully not as broken so that we don't need these
1815 // workarounds.
1817 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1818 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1819 New->setInvalidDecl();
1820 }
1821}
1822
1823/// CheckCXXDefaultArguments - Verify that the default arguments for a
1824/// function declaration are well-formed according to C++
1825/// [dcl.fct.default].
1827 // This checking doesn't make sense for explicit specializations; their
1828 // default arguments are determined by the declaration we're specializing,
1829 // not by FD.
1831 return;
1832 if (auto *FTD = FD->getDescribedFunctionTemplate())
1833 if (FTD->isMemberSpecialization())
1834 return;
1835
1836 unsigned NumParams = FD->getNumParams();
1837 unsigned ParamIdx = 0;
1838
1839 // Find first parameter with a default argument
1840 for (; ParamIdx < NumParams; ++ParamIdx) {
1841 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1842 if (Param->hasDefaultArg())
1843 break;
1844 }
1845
1846 // C++20 [dcl.fct.default]p4:
1847 // In a given function declaration, each parameter subsequent to a parameter
1848 // with a default argument shall have a default argument supplied in this or
1849 // a previous declaration, unless the parameter was expanded from a
1850 // parameter pack, or shall be a function parameter pack.
1851 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1852 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1853 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1855 CurrentInstantiationScope->isLocalPackExpansion(Param)))
1856 continue;
1857 if (Param->isInvalidDecl())
1858 /* We already complained about this parameter. */;
1859 else if (Param->getIdentifier())
1860 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1861 << Param->getIdentifier();
1862 else
1863 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1864 }
1865}
1866
1867/// Check that the given type is a literal type. Issue a diagnostic if not,
1868/// if Kind is Diagnose.
1869/// \return \c true if a problem has been found (and optionally diagnosed).
1870template <typename... Ts>
1872 SourceLocation Loc, QualType T, unsigned DiagID,
1873 Ts &&...DiagArgs) {
1874 if (T->isDependentType())
1875 return false;
1876
1877 switch (Kind) {
1879 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1880 std::forward<Ts>(DiagArgs)...);
1881
1883 return !T->isLiteralType(SemaRef.Context);
1884 }
1885
1886 llvm_unreachable("unknown CheckConstexprKind");
1887}
1888
1889/// Determine whether a destructor cannot be constexpr due to
1891 const CXXDestructorDecl *DD,
1893 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1894 "this check is obsolete for C++23");
1895 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1896 const CXXRecordDecl *RD =
1897 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1898 if (!RD || RD->hasConstexprDestructor())
1899 return true;
1900
1902 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1903 << static_cast<int>(DD->getConstexprKind()) << !FD
1904 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1905 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1906 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1907 }
1908 return false;
1909 };
1910
1911 const CXXRecordDecl *RD = DD->getParent();
1912 for (const CXXBaseSpecifier &B : RD->bases())
1913 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1914 return false;
1915 for (const FieldDecl *FD : RD->fields())
1916 if (!Check(FD->getLocation(), FD->getType(), FD))
1917 return false;
1918 return true;
1919}
1920
1921/// Check whether a function's parameter types are all literal types. If so,
1922/// return true. If not, produce a suitable diagnostic and return false.
1924 const FunctionDecl *FD,
1926 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1927 "this check is obsolete for C++23");
1928 unsigned ArgIndex = 0;
1929 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1930 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1931 e = FT->param_type_end();
1932 i != e; ++i, ++ArgIndex) {
1933 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1934 assert(PD && "null in a parameter list");
1935 SourceLocation ParamLoc = PD->getLocation();
1936 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1937 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1939 FD->isConsteval()))
1940 return false;
1941 }
1942 return true;
1943}
1944
1945/// Check whether a function's return type is a literal type. If so, return
1946/// true. If not, produce a suitable diagnostic and return false.
1947static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1949 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1950 "this check is obsolete for C++23");
1951 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1952 diag::err_constexpr_non_literal_return,
1953 FD->isConsteval()))
1954 return false;
1955 return true;
1956}
1957
1958/// Get diagnostic %select index for tag kind for
1959/// record diagnostic message.
1960/// WARNING: Indexes apply to particular diagnostics only!
1961///
1962/// \returns diagnostic %select index.
1964 switch (Tag) {
1966 return 0;
1968 return 1;
1969 case TagTypeKind::Class:
1970 return 2;
1971 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1972 }
1973}
1974
1975static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1976 Stmt *Body,
1978static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1979
1981 CheckConstexprKind Kind) {
1982 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1983 if (!getLangOpts().CPlusPlus26 && MD && MD->isInstance()) {
1984 // C++11 [dcl.constexpr]p4:
1985 // The definition of a constexpr constructor shall satisfy the following
1986 // constraints:
1987 // - the class shall not have any virtual base classes;
1988 //
1989 // FIXME: This only applies to constructors and destructors, not arbitrary
1990 // member functions.
1991 const CXXRecordDecl *RD = MD->getParent();
1992 if (RD->getNumVBases()) {
1994 return false;
1995
1996 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1997 << isa<CXXConstructorDecl>(NewFD)
1999 for (const auto &I : RD->vbases())
2000 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
2001 << I.getSourceRange();
2002 return false;
2003 }
2004 }
2005
2006 if (!isa<CXXConstructorDecl>(NewFD)) {
2007 // C++11 [dcl.constexpr]p3:
2008 // The definition of a constexpr function shall satisfy the following
2009 // constraints:
2010 // - it shall not be virtual; (removed in C++20)
2011 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
2012 if (Method && Method->isVirtual()) {
2013 if (getLangOpts().CPlusPlus20) {
2014 if (Kind == CheckConstexprKind::Diagnose)
2015 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
2016 } else {
2018 return false;
2019
2020 Method = Method->getCanonicalDecl();
2021 Diag(Method->getLocation(), diag::err_constexpr_virtual);
2022
2023 // If it's not obvious why this function is virtual, find an overridden
2024 // function which uses the 'virtual' keyword.
2025 const CXXMethodDecl *WrittenVirtual = Method;
2026 while (!WrittenVirtual->isVirtualAsWritten())
2027 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
2028 if (WrittenVirtual != Method)
2029 Diag(WrittenVirtual->getLocation(),
2030 diag::note_overridden_virtual_function);
2031 return false;
2032 }
2033 }
2034
2035 // - its return type shall be a literal type; (removed in C++23)
2036 if (!getLangOpts().CPlusPlus23 &&
2037 !CheckConstexprReturnType(*this, NewFD, Kind))
2038 return false;
2039 }
2040
2041 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
2042 // A destructor can be constexpr only if the defaulted destructor could be;
2043 // we don't need to check the members and bases if we already know they all
2044 // have constexpr destructors. (removed in C++23)
2045 if (!getLangOpts().CPlusPlus23 &&
2046 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2048 return false;
2049 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
2050 return false;
2051 }
2052 }
2053
2054 // - each of its parameter types shall be a literal type; (removed in C++23)
2055 if (!getLangOpts().CPlusPlus23 &&
2056 !CheckConstexprParameterTypes(*this, NewFD, Kind))
2057 return false;
2058
2059 Stmt *Body = NewFD->getBody();
2060 assert(Body &&
2061 "CheckConstexprFunctionDefinition called on function with no body");
2062 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
2063}
2064
2065/// Check the given declaration statement is legal within a constexpr function
2066/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2067///
2068/// \return true if the body is OK (maybe only as an extension), false if we
2069/// have diagnosed a problem.
2070static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2071 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2073 // C++11 [dcl.constexpr]p3 and p4:
2074 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2075 // contain only
2076 for (const auto *DclIt : DS->decls()) {
2077 switch (DclIt->getKind()) {
2078 case Decl::StaticAssert:
2079 case Decl::Using:
2080 case Decl::UsingShadow:
2081 case Decl::UsingDirective:
2082 case Decl::UnresolvedUsingTypename:
2083 case Decl::UnresolvedUsingValue:
2084 case Decl::UsingEnum:
2085 // - static_assert-declarations
2086 // - using-declarations,
2087 // - using-directives,
2088 // - using-enum-declaration
2089 continue;
2090
2091 case Decl::Typedef:
2092 case Decl::TypeAlias: {
2093 // - typedef declarations and alias-declarations that do not define
2094 // classes or enumerations,
2095 const auto *TN = cast<TypedefNameDecl>(DclIt);
2096 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2097 // Don't allow variably-modified types in constexpr functions.
2099 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2100 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
2101 << TL.getSourceRange() << TL.getType()
2103 }
2104 return false;
2105 }
2106 continue;
2107 }
2108
2109 case Decl::Enum:
2110 case Decl::CXXRecord:
2111 // C++1y allows types to be defined, not just declared.
2112 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
2114 SemaRef.DiagCompat(DS->getBeginLoc(),
2115 diag_compat::constexpr_type_definition)
2117 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2118 return false;
2119 }
2120 }
2121 continue;
2122
2123 case Decl::EnumConstant:
2124 case Decl::IndirectField:
2125 case Decl::ParmVar:
2126 // These can only appear with other declarations which are banned in
2127 // C++11 and permitted in C++1y, so ignore them.
2128 continue;
2129
2130 case Decl::Var:
2131 case Decl::Decomposition: {
2132 // C++1y [dcl.constexpr]p3 allows anything except:
2133 // a definition of a variable of non-literal type or of static or
2134 // thread storage duration or [before C++2a] for which no
2135 // initialization is performed.
2136 const auto *VD = cast<VarDecl>(DclIt);
2137 if (VD->isThisDeclarationADefinition()) {
2138 if (VD->isStaticLocal()) {
2140 SemaRef.DiagCompat(VD->getLocation(),
2141 diag_compat::constexpr_static_var)
2143 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2144 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2145 return false;
2146 }
2147 }
2148 if (SemaRef.LangOpts.CPlusPlus23) {
2149 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
2150 diag::warn_cxx20_compat_constexpr_var,
2152 } else if (CheckLiteralType(
2153 SemaRef, Kind, VD->getLocation(), VD->getType(),
2154 diag::err_constexpr_local_var_non_literal_type,
2156 return false;
2157 }
2158 if (!VD->getType()->isDependentType() &&
2159 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2161 SemaRef.DiagCompat(VD->getLocation(),
2162 diag_compat::constexpr_local_var_no_init)
2164 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2165 return false;
2166 }
2167 continue;
2168 }
2169 }
2171 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2173 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2174 return false;
2175 }
2176 continue;
2177 }
2178
2179 case Decl::NamespaceAlias:
2180 case Decl::Function:
2181 // These are disallowed in C++11 and permitted in C++1y. Allow them
2182 // everywhere as an extension.
2183 if (!Cxx1yLoc.isValid())
2184 Cxx1yLoc = DS->getBeginLoc();
2185 continue;
2186
2187 default:
2189 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2190 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2191 }
2192 return false;
2193 }
2194 }
2195
2196 return true;
2197}
2198
2199/// Check that the given field is initialized within a constexpr constructor.
2200///
2201/// \param Dcl The constexpr constructor being checked.
2202/// \param Field The field being checked. This may be a member of an anonymous
2203/// struct or union nested within the class being checked.
2204/// \param Inits All declarations, including anonymous struct/union members and
2205/// indirect members, for which any initialization was provided.
2206/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2207/// multiple notes for different members to the same error.
2208/// \param Kind Whether we're diagnosing a constructor as written or determining
2209/// whether the formal requirements are satisfied.
2210/// \return \c false if we're checking for validity and the constructor does
2211/// not satisfy the requirements on a constexpr constructor.
2213 const FunctionDecl *Dcl,
2214 FieldDecl *Field,
2216 bool &Diagnosed,
2218 // In C++20 onwards, there's nothing to check for validity.
2220 SemaRef.getLangOpts().CPlusPlus20)
2221 return true;
2222
2223 if (Field->isInvalidDecl())
2224 return true;
2225
2226 if (Field->isUnnamedBitField())
2227 return true;
2228
2229 // Anonymous unions with no variant members and empty anonymous structs do not
2230 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2231 // indirect fields don't need initializing.
2232 if (Field->isAnonymousStructOrUnion() &&
2233 (Field->getType()->isUnionType()
2234 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2235 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2236 return true;
2237
2238 if (!Inits.count(Field)) {
2240 if (!Diagnosed) {
2241 SemaRef.DiagCompat(Dcl->getLocation(),
2242 diag_compat::constexpr_ctor_missing_init);
2243 Diagnosed = true;
2244 }
2245 SemaRef.Diag(Field->getLocation(),
2246 diag::note_constexpr_ctor_missing_init);
2247 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2248 return false;
2249 }
2250 } else if (Field->isAnonymousStructOrUnion()) {
2251 const auto *RD = Field->getType()->castAsRecordDecl();
2252 for (auto *I : RD->fields())
2253 // If an anonymous union contains an anonymous struct of which any member
2254 // is initialized, all members must be initialized.
2255 if (!RD->isUnion() || Inits.count(I))
2256 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2257 Kind))
2258 return false;
2259 }
2260 return true;
2261}
2262
2263/// Check the provided statement is allowed in a constexpr function
2264/// definition.
2265static bool
2268 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2269 SourceLocation &Cxx2bLoc,
2271 auto CheckChildren = [&] {
2272 for (Stmt *SubStmt : S->children()) {
2273 if (SubStmt &&
2274 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2275 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2276 return false;
2277 }
2278 return true;
2279 };
2280
2281 // - its function-body shall be [...] a compound-statement that contains only
2282 switch (S->getStmtClass()) {
2283 case Stmt::NullStmtClass:
2284 // - null statements,
2285 return true;
2286
2287 case Stmt::DeclStmtClass: {
2288 auto *DS = cast<DeclStmt>(S);
2289
2290 // Expansion statement 'declarations' have substatements, so we need to
2291 // handle them separately.
2292 if (DS->isSingleDecl()) {
2293 if (auto *ESD = dyn_cast<CXXExpansionStmtDecl>(DS->getSingleDecl())) {
2294 // Don't check unexpanded expansion statements.
2295 if (!ESD->getInstantiations())
2296 return true;
2297 for (auto *BodyIt : ESD->getInstantiations()->getInstantiations()) {
2298 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2299 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2300 return false;
2301 }
2302 return true;
2303 }
2304 }
2305
2306 // - static_assert-declarations
2307 // - using-declarations,
2308 // - using-directives,
2309 // - typedef declarations and alias-declarations that do not define
2310 // classes or enumerations,
2311 return CheckConstexprDeclStmt(SemaRef, Dcl, DS, Cxx1yLoc, Kind);
2312 }
2313
2314 case Stmt::ReturnStmtClass:
2315 // - and exactly one return statement;
2316 if (isa<CXXConstructorDecl>(Dcl)) {
2317 // C++1y allows return statements in constexpr constructors.
2318 if (!Cxx1yLoc.isValid())
2319 Cxx1yLoc = S->getBeginLoc();
2320 return true;
2321 }
2322
2323 ReturnStmts.push_back(S->getBeginLoc());
2324 return true;
2325
2326 case Stmt::AttributedStmtClass:
2327 // Attributes on a statement don't affect its formal kind and hence don't
2328 // affect its validity in a constexpr function.
2330 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2331 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2332
2333 case Stmt::CompoundStmtClass:
2334 // C++1y allows compound-statements.
2335 if (!Cxx1yLoc.isValid())
2336 Cxx1yLoc = S->getBeginLoc();
2337 return CheckChildren();
2338
2339 case Stmt::IfStmtClass: {
2340 // C++1y allows if-statements.
2341 if (!Cxx1yLoc.isValid())
2342 Cxx1yLoc = S->getBeginLoc();
2343
2344 IfStmt *If = cast<IfStmt>(S);
2345 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2346 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2347 return false;
2348 if (If->getElse() &&
2349 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2350 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2351 return false;
2352 return true;
2353 }
2354
2355 case Stmt::WhileStmtClass:
2356 case Stmt::DoStmtClass:
2357 case Stmt::ForStmtClass:
2358 case Stmt::CXXForRangeStmtClass:
2359 case Stmt::ContinueStmtClass:
2360 // C++1y allows all of these. We don't allow them as extensions in C++11,
2361 // because they don't make sense without variable mutation.
2362 if (!SemaRef.getLangOpts().CPlusPlus14)
2363 break;
2364 [[fallthrough]];
2365
2366 case Stmt::SwitchStmtClass:
2367 case Stmt::CaseStmtClass:
2368 case Stmt::DefaultStmtClass:
2369 case Stmt::BreakStmtClass:
2370 // C++1y allows switch-statements, and since they don't need variable
2371 // mutation, we can reasonably allow them in C++11 as an extension.
2372 if (!Cxx1yLoc.isValid())
2373 Cxx1yLoc = S->getBeginLoc();
2374 return CheckChildren();
2375
2376 case Stmt::LabelStmtClass:
2377 case Stmt::GotoStmtClass:
2378 case Stmt::IndirectGotoStmtClass:
2379 if (Cxx2bLoc.isInvalid())
2380 Cxx2bLoc = S->getBeginLoc();
2381 return CheckChildren();
2382
2383 case Stmt::GCCAsmStmtClass:
2384 case Stmt::MSAsmStmtClass:
2385 // C++2a allows inline assembly statements.
2386 case Stmt::CXXTryStmtClass:
2387 if (Cxx2aLoc.isInvalid())
2388 Cxx2aLoc = S->getBeginLoc();
2389 return CheckChildren();
2390
2391 case Stmt::CXXCatchStmtClass:
2392 // Do not bother checking the language mode (already covered by the
2393 // try block check).
2395 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2396 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2397
2398 default:
2399 if (!isa<Expr>(S))
2400 break;
2401
2402 // C++1y allows expression-statements.
2403 if (!Cxx1yLoc.isValid())
2404 Cxx1yLoc = S->getBeginLoc();
2405 return true;
2406 }
2407
2409 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2410 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2411 }
2412 return false;
2413}
2414
2415/// Check the body for the given constexpr function declaration only contains
2416/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2417///
2418/// \return true if the body is OK, false if we have found or diagnosed a
2419/// problem.
2420static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2421 Stmt *Body,
2424
2425 if (isa<CXXTryStmt>(Body)) {
2426 // C++11 [dcl.constexpr]p3:
2427 // The definition of a constexpr function shall satisfy the following
2428 // constraints: [...]
2429 // - its function-body shall be = delete, = default, or a
2430 // compound-statement
2431 //
2432 // C++11 [dcl.constexpr]p4:
2433 // In the definition of a constexpr constructor, [...]
2434 // - its function-body shall not be a function-try-block;
2435 //
2436 // This restriction is lifted in C++2a, as long as inner statements also
2437 // apply the general constexpr rules.
2438 switch (Kind) {
2440 if (!SemaRef.getLangOpts().CPlusPlus20)
2441 return false;
2442 break;
2443
2445 SemaRef.DiagCompat(Body->getBeginLoc(),
2446 diag_compat::constexpr_function_try_block)
2448 break;
2449 }
2450 }
2451
2452 // - its function-body shall be [...] a compound-statement that contains only
2453 // [... list of cases ...]
2454 //
2455 // Note that walking the children here is enough to properly check for
2456 // CompoundStmt and CXXTryStmt body.
2457 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2458 for (Stmt *SubStmt : Body->children()) {
2459 if (SubStmt &&
2460 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2461 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2462 return false;
2463 }
2464
2466 // If this is only valid as an extension, report that we don't satisfy the
2467 // constraints of the current language.
2468 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2469 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2470 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2471 return false;
2472 } else if (Cxx2bLoc.isValid()) {
2473 SemaRef.DiagCompat(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2475 } else if (Cxx2aLoc.isValid()) {
2476 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2478 } else if (Cxx1yLoc.isValid()) {
2479 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2481 }
2482
2484 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2485 const CXXRecordDecl *RD = Constructor->getParent();
2486 // DR1359:
2487 // - every non-variant non-static data member and base class sub-object
2488 // shall be initialized;
2489 // DR1460:
2490 // - if the class is a union having variant members, exactly one of them
2491 // shall be initialized;
2492 if (RD->isUnion()) {
2493 if (Constructor->getNumCtorInitializers() == 0 &&
2494 RD->hasVariantMembers()) {
2496 SemaRef.DiagCompat(Dcl->getLocation(),
2497 diag_compat::constexpr_union_ctor_no_init);
2498 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2499 return false;
2500 }
2501 }
2502 } else if (!Constructor->isDependentContext() &&
2503 !Constructor->isDelegatingConstructor()) {
2504 // Skip detailed checking if we have enough initializers, and we would
2505 // allow at most one initializer per member.
2506 bool AnyAnonStructUnionMembers = false;
2507 unsigned Fields = 0;
2509 E = RD->field_end(); I != E; ++I, ++Fields) {
2510 if (I->isAnonymousStructOrUnion()) {
2511 AnyAnonStructUnionMembers = true;
2512 break;
2513 }
2514 }
2515 // DR1460:
2516 // - if the class is a union-like class, but is not a union, for each of
2517 // its anonymous union members having variant members, exactly one of
2518 // them shall be initialized;
2519 if (AnyAnonStructUnionMembers ||
2520 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2521 // Check initialization of non-static data members. Base classes are
2522 // always initialized so do not need to be checked. Dependent bases
2523 // might not have initializers in the member initializer list.
2525 for (const auto *I: Constructor->inits()) {
2526 if (FieldDecl *FD = I->getMember())
2527 Inits.insert(FD);
2528 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2529 Inits.insert(ID->chain_begin(), ID->chain_end());
2530 }
2531
2532 bool Diagnosed = false;
2533 for (auto *I : RD->fields())
2534 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2535 Kind))
2536 return false;
2537 }
2538 }
2539 } else {
2540 if (ReturnStmts.empty()) {
2541 switch (Kind) {
2543 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2544 return false;
2545 break;
2546
2548 // The formal requirements don't include this rule in C++14, even
2549 // though the "must be able to produce a constant expression" rules
2550 // still imply it in some cases.
2551 if (!SemaRef.getLangOpts().CPlusPlus14)
2552 return false;
2553 break;
2554 }
2555 } else if (ReturnStmts.size() > 1) {
2556 switch (Kind) {
2558 SemaRef.DiagCompat(ReturnStmts.back(),
2559 diag_compat::constexpr_body_multiple_return);
2560 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2561 SemaRef.Diag(ReturnStmts[I],
2562 diag::note_constexpr_body_previous_return);
2563 break;
2564
2566 if (!SemaRef.getLangOpts().CPlusPlus14)
2567 return false;
2568 break;
2569 }
2570 }
2571 }
2572
2573 // C++11 [dcl.constexpr]p5:
2574 // if no function argument values exist such that the function invocation
2575 // substitution would produce a constant expression, the program is
2576 // ill-formed; no diagnostic required.
2577 // C++11 [dcl.constexpr]p3:
2578 // - every constructor call and implicit conversion used in initializing the
2579 // return value shall be one of those allowed in a constant expression.
2580 // C++11 [dcl.constexpr]p4:
2581 // - every constructor involved in initializing non-static data members and
2582 // base class sub-objects shall be a constexpr constructor.
2583 //
2584 // Note that this rule is distinct from the "requirements for a constexpr
2585 // function", so is not checked in CheckValid mode. Because the check for
2586 // constexpr potential is expensive, skip the check if the diagnostic is
2587 // disabled, the function is declared in a system header, or we're in C++23
2588 // or later mode (see https://wg21.link/P2448).
2589 bool SkipCheck =
2590 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2591 SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||
2592 SemaRef.getDiagnostics().isIgnored(
2593 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2595 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2596 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2597 SemaRef.Diag(Dcl->getLocation(),
2598 diag::ext_constexpr_function_never_constant_expr)
2599 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2600 << Dcl->getNameInfo().getSourceRange();
2601 for (const auto &Diag : Diags)
2602 SemaRef.Diag(Diag.first, Diag.second);
2603 // Don't return false here: we allow this for compatibility in
2604 // system headers.
2605 }
2606
2607 return true;
2608}
2609
2611 const FunctionDecl *Dcl) {
2612 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2614 // Skip emitting a missing return error diagnostic for non-void functions
2615 // since C++23 no longer mandates constexpr functions to yield constant
2616 // expressions.
2617 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2618 return true;
2619
2620 // C++14 doesn't require constexpr functions to contain a 'return'
2621 // statement. We still do, unless the return type might be void, because
2622 // otherwise if there's no return statement, the function cannot
2623 // be used in a core constant expression.
2624 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2625 SemaRef.Diag(Dcl->getLocation(),
2626 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2627 : diag::err_constexpr_body_no_return)
2628 << Dcl->isConsteval();
2629 return OK;
2630}
2631
2633 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2635 return true;
2639 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2640 if (it != UndefinedButUsed.end()) {
2641 Diag(it->second, diag::err_immediate_function_used_before_definition)
2642 << it->first;
2643 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2644 if (FD->isImmediateFunction() && !FD->isConsteval())
2646 return false;
2647 }
2648 }
2649 return true;
2650}
2651
2653 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2654 "expected an immediate function");
2655 assert(FD->hasBody() && "expected the function to have a body");
2656 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2657 Sema &SemaRef;
2658
2659 const FunctionDecl *ImmediateFn;
2660 bool ImmediateFnIsConstructor;
2661 CXXConstructorDecl *CurrentConstructor = nullptr;
2662 CXXCtorInitializer *CurrentInit = nullptr;
2663
2664 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2665 : SemaRef(SemaRef), ImmediateFn(FD),
2666 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2667 ShouldVisitImplicitCode = true;
2668 ShouldVisitLambdaBody = false;
2669 }
2670
2671 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2672 SourceLocation Loc = E->getBeginLoc();
2673 SourceRange Range = E->getSourceRange();
2674 if (CurrentConstructor && CurrentInit) {
2675 Loc = CurrentConstructor->getLocation();
2676 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2677 : SourceRange();
2678 }
2679
2680 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2681
2682 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2683 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2684 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2685 << (InitializedField != nullptr)
2686 << (CurrentInit && !CurrentInit->isWritten())
2687 << InitializedField << Range;
2688 }
2689 bool TraverseCallExpr(CallExpr *E) override {
2690 if (const auto *DR =
2691 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2692 DR && DR->isImmediateEscalating()) {
2693 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2694 return false;
2695 }
2696
2697 for (Expr *A : E->arguments())
2698 if (!TraverseStmt(A))
2699 return false;
2700
2701 return true;
2702 }
2703
2704 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2705 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2706 ReferencedFn && E->isImmediateEscalating()) {
2707 Diag(E, ReferencedFn, /*IsCall=*/false);
2708 return false;
2709 }
2710
2711 return true;
2712 }
2713
2714 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2716 if (E->isImmediateEscalating()) {
2717 Diag(E, D, /*IsCall=*/true);
2718 return false;
2719 }
2720 return true;
2721 }
2722
2723 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2724 llvm::SaveAndRestore RAII(CurrentInit, Init);
2726 }
2727
2728 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2729 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2730 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2731 }
2732
2733 bool TraverseType(QualType T, bool TraverseQualifier) override {
2734 return true;
2735 }
2736 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2737
2738 } Visitor(*this, FD);
2739 Visitor.TraverseDecl(FD);
2740}
2741
2743 assert(getLangOpts().CPlusPlus && "No class names in C!");
2744
2745 if (SS && SS->isInvalid())
2746 return nullptr;
2747
2748 if (SS && SS->isNotEmpty()) {
2749 DeclContext *DC = computeDeclContext(*SS, true);
2750 return dyn_cast_or_null<CXXRecordDecl>(DC);
2751 }
2752
2753 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2754}
2755
2757 const CXXScopeSpec *SS) {
2758 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2759 return CurDecl && &II == CurDecl->getIdentifier();
2760}
2761
2763 assert(getLangOpts().CPlusPlus && "No class names in C!");
2764
2765 if (!getLangOpts().SpellChecking)
2766 return false;
2767
2768 CXXRecordDecl *CurDecl;
2769 if (SS && SS->isSet() && !SS->isInvalid()) {
2770 DeclContext *DC = computeDeclContext(*SS, true);
2771 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2772 } else
2773 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2774
2775 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2776 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2777 < II->getLength()) {
2778 II = CurDecl->getIdentifier();
2779 return true;
2780 }
2781
2782 return false;
2783}
2784
2786 SourceRange SpecifierRange,
2787 bool Virtual, AccessSpecifier Access,
2788 TypeSourceInfo *TInfo,
2789 SourceLocation EllipsisLoc) {
2790 QualType BaseType = TInfo->getType();
2791 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2792 if (BaseType->containsErrors()) {
2793 // Already emitted a diagnostic when parsing the error type.
2794 return nullptr;
2795 }
2796
2797 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2798 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2799 << TInfo->getTypeLoc().getSourceRange();
2800 EllipsisLoc = SourceLocation();
2801 }
2802
2803 auto *BaseDecl =
2804 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2805 // C++ [class.derived.general]p2:
2806 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2807 // that is not an incompletely defined class; any cv-qualifiers are
2808 // ignored.
2809 if (BaseDecl) {
2810 // C++ [class.union.general]p4:
2811 // [...] A union shall not be used as a base class.
2812 if (BaseDecl->isUnion()) {
2813 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2814 return nullptr;
2815 }
2816
2817 if (BaseType.hasQualifiers()) {
2818 std::string Quals =
2819 BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
2820 Diag(BaseLoc, diag::warn_qual_base_type)
2821 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2822 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2823 }
2824
2825 // For the MS ABI, propagate DLL attributes to base class templates.
2826 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2827 Context.getTargetInfo().getTriple().isPS()) {
2828 if (Attr *ClassAttr = getDLLAttr(Class)) {
2829 if (auto *BaseSpec =
2830 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2831 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2832 BaseLoc);
2833 }
2834 }
2835 }
2836
2837 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2838 SpecifierRange)) {
2839 Class->setInvalidDecl();
2840 return nullptr;
2841 }
2842
2843 BaseDecl = BaseDecl->getDefinition();
2844 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2845
2846 // Microsoft docs say:
2847 // "If a base-class has a code_seg attribute, derived classes must have the
2848 // same attribute."
2849 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2850 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2851 if ((DerivedCSA || BaseCSA) &&
2852 (!BaseCSA || !DerivedCSA ||
2853 BaseCSA->getName() != DerivedCSA->getName())) {
2854 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2855 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2856 << BaseDecl;
2857 return nullptr;
2858 }
2859
2860 // A class which contains a flexible array member is not suitable for use as
2861 // a base class:
2862 // - If the layout determines that a base comes before another base,
2863 // the flexible array member would index into the subsequent base.
2864 // - If the layout determines that base comes before the derived class,
2865 // the flexible array member would index into the derived class.
2866 if (BaseDecl->hasFlexibleArrayMember()) {
2867 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2868 << BaseDecl->getDeclName();
2869 return nullptr;
2870 }
2871
2872 // C++ [class]p3:
2873 // If a class is marked final and it appears as a base-type-specifier in
2874 // base-clause, the program is ill-formed.
2875 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2876 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2877 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2878 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2879 << BaseDecl->getDeclName() << FA->getRange();
2880 return nullptr;
2881 }
2882
2883 // If the base class is invalid the derived class is as well.
2884 if (BaseDecl->isInvalidDecl())
2885 Class->setInvalidDecl();
2886 } else if (BaseType->isDependentType()) {
2887 // Make sure that we don't make an ill-formed AST where the type of the
2888 // Class is non-dependent and its attached base class specifier is an
2889 // dependent type, which violates invariants in many clang code paths (e.g.
2890 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2891 // explicitly mark the Class decl invalid. The diagnostic was already
2892 // emitted.
2893 if (!Class->isDependentContext())
2894 Class->setInvalidDecl();
2895 } else {
2896 // The base class is some non-dependent non-class type.
2897 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2898 return nullptr;
2899 }
2900
2901 // In HLSL, unspecified class access is public rather than private.
2902 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2903 Access == AS_none)
2904 Access = AS_public;
2905
2906 // Create the base specifier.
2907 return new (Context) CXXBaseSpecifier(
2908 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2909 Access, TInfo, EllipsisLoc);
2910}
2911
2913 const ParsedAttributesView &Attributes,
2914 bool Virtual, AccessSpecifier Access,
2915 ParsedType basetype, SourceLocation BaseLoc,
2916 SourceLocation EllipsisLoc) {
2917 if (!classdecl)
2918 return true;
2919
2920 AdjustDeclIfTemplate(classdecl);
2921 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2922 if (!Class)
2923 return true;
2924
2925 // We haven't yet attached the base specifiers.
2926 Class->setIsParsingBaseSpecifiers();
2927
2928 // We do not support any C++11 attributes on base-specifiers yet.
2929 // Diagnose any attributes we see.
2930 for (const ParsedAttr &AL : Attributes) {
2931 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2932 continue;
2933 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2935 else
2936 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2937 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2938 }
2939
2940 TypeSourceInfo *TInfo = nullptr;
2941 GetTypeFromParser(basetype, &TInfo);
2942
2943 if (EllipsisLoc.isInvalid() &&
2944 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2946 return true;
2947
2948 // C++ [class.union.general]p4:
2949 // [...] A union shall not have base classes.
2950 if (Class->isUnion()) {
2951 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2952 << SpecifierRange;
2953 return true;
2954 }
2955
2956 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2957 Virtual, Access, TInfo,
2958 EllipsisLoc))
2959 return BaseSpec;
2960
2961 Class->setInvalidDecl();
2962 return true;
2963}
2964
2965/// Use small set to collect indirect bases. As this is only used
2966/// locally, there's no need to abstract the small size parameter.
2968
2969/// Recursively add the bases of Type. Don't add Type itself.
2970static void
2972 const QualType &Type)
2973{
2974 // Even though the incoming type is a base, it might not be
2975 // a class -- it could be a template parm, for instance.
2976 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2977 // Iterate over its bases.
2978 for (const auto &BaseSpec : Decl->bases()) {
2979 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2980 .getUnqualifiedType();
2981 if (Set.insert(Base).second)
2982 // If we've not already seen it, recurse.
2983 NoteIndirectBases(Context, Set, Base);
2984 }
2985 }
2986}
2987
2990 if (Bases.empty())
2991 return false;
2992
2993 // Used to keep track of which base types we have already seen, so
2994 // that we can properly diagnose redundant direct base types. Note
2995 // that the key is always the unqualified canonical type of the base
2996 // class.
2997 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2998
2999 // Used to track indirect bases so we can see if a direct base is
3000 // ambiguous.
3001 IndirectBaseSet IndirectBaseTypes;
3002
3003 // Copy non-redundant base specifiers into permanent storage.
3004 unsigned NumGoodBases = 0;
3005 bool Invalid = false;
3006 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
3007 QualType NewBaseType
3008 = Context.getCanonicalType(Bases[idx]->getType());
3009 NewBaseType = NewBaseType.getLocalUnqualifiedType();
3010
3011 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
3012 if (KnownBase) {
3013 // C++ [class.mi]p3:
3014 // A class shall not be specified as a direct base class of a
3015 // derived class more than once.
3016 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
3017 << KnownBase->getType() << Bases[idx]->getSourceRange();
3018
3019 // Delete the duplicate base class specifier; we're going to
3020 // overwrite its pointer later.
3021 Context.Deallocate(Bases[idx]);
3022
3023 Invalid = true;
3024 } else {
3025 // Okay, add this new base class.
3026 KnownBase = Bases[idx];
3027 Bases[NumGoodBases++] = Bases[idx];
3028
3029 if (NewBaseType->isDependentType())
3030 continue;
3031 // Note this base's direct & indirect bases, if there could be ambiguity.
3032 if (Bases.size() > 1)
3033 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
3034
3035 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3036 if (Class->isInterface() &&
3037 (!RD->isInterfaceLike() ||
3038 KnownBase->getAccessSpecifier() != AS_public)) {
3039 // The Microsoft extension __interface does not permit bases that
3040 // are not themselves public interfaces.
3041 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
3042 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
3043 << RD->getSourceRange();
3044 Invalid = true;
3045 }
3046 if (RD->hasAttr<WeakAttr>())
3047 Class->addAttr(WeakAttr::CreateImplicit(Context));
3048 }
3049 }
3050 }
3051
3052 // Attach the remaining base class specifiers to the derived class.
3053 Class->setBases(Bases.data(), NumGoodBases);
3054
3055 // Check that the only base classes that are duplicate are virtual.
3056 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3057 // Check whether this direct base is inaccessible due to ambiguity.
3058 QualType BaseType = Bases[idx]->getType();
3059
3060 // Skip all dependent types in templates being used as base specifiers.
3061 // Checks below assume that the base specifier is a CXXRecord.
3062 if (BaseType->isDependentType())
3063 continue;
3064
3065 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3066 .getUnqualifiedType();
3067
3068 if (IndirectBaseTypes.count(CanonicalBase)) {
3069 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3070 /*DetectVirtual=*/true);
3071 bool found
3072 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3073 assert(found);
3074 (void)found;
3075
3076 if (Paths.isAmbiguous(CanonicalBase))
3077 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3078 << BaseType << getAmbiguousPathsDisplayString(Paths)
3079 << Bases[idx]->getSourceRange();
3080 else
3081 assert(Bases[idx]->isVirtual());
3082 }
3083
3084 // Delete the base class specifier, since its data has been copied
3085 // into the CXXRecordDecl.
3086 Context.Deallocate(Bases[idx]);
3087 }
3088
3089 return Invalid;
3090}
3091
3094 if (!ClassDecl || Bases.empty())
3095 return;
3096
3097 AdjustDeclIfTemplate(ClassDecl);
3098 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3099}
3100
3102 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3103 if (!getLangOpts().CPlusPlus)
3104 return false;
3105
3106 if (!Base || !Derived)
3107 return false;
3108
3109 // If either the base or the derived type is invalid, don't try to
3110 // check whether one is derived from the other.
3111 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3112 return false;
3113
3114 // FIXME: In a modules build, do we need the entire path to be visible for us
3115 // to be able to use the inheritance relationship?
3116 if (!isCompleteType(Loc, Context.getCanonicalTagType(Derived)) &&
3117 !Derived->isBeingDefined())
3118 return false;
3119
3120 return Derived->isDerivedFrom(Base, Paths);
3121}
3122
3125 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3126 /*DetectVirtual=*/false);
3127 return IsDerivedFrom(Loc, Derived, Base, Paths);
3128}
3129
3131 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3132 /*DetectVirtual=*/false);
3133 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3134 Base->getAsCXXRecordDecl(), Paths);
3135}
3136
3138 CXXBasePaths &Paths) {
3139 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3140 Base->getAsCXXRecordDecl(), Paths);
3141}
3142
3143static void BuildBasePathArray(const CXXBasePath &Path,
3144 CXXCastPath &BasePathArray) {
3145 // We first go backward and check if we have a virtual base.
3146 // FIXME: It would be better if CXXBasePath had the base specifier for
3147 // the nearest virtual base.
3148 unsigned Start = 0;
3149 for (unsigned I = Path.size(); I != 0; --I) {
3150 if (Path[I - 1].Base->isVirtual()) {
3151 Start = I - 1;
3152 break;
3153 }
3154 }
3155
3156 // Now add all bases.
3157 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3158 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3159}
3160
3161
3163 CXXCastPath &BasePathArray) {
3164 assert(BasePathArray.empty() && "Base path array must be empty!");
3165 assert(Paths.isRecordingPaths() && "Must record paths!");
3166 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3167}
3168
3169bool
3171 unsigned InaccessibleBaseID,
3172 unsigned AmbiguousBaseConvID,
3173 SourceLocation Loc, SourceRange Range,
3174 DeclarationName Name,
3175 CXXCastPath *BasePath,
3176 bool IgnoreAccess) {
3177 // First, determine whether the path from Derived to Base is
3178 // ambiguous. This is slightly more expensive than checking whether
3179 // the Derived to Base conversion exists, because here we need to
3180 // explore multiple paths to determine if there is an ambiguity.
3181 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3182 /*DetectVirtual=*/false);
3183 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3184 if (!DerivationOkay)
3185 return true;
3186
3187 const CXXBasePath *Path = nullptr;
3188 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3189 Path = &Paths.front();
3190
3191 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3192 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3193 // user to access such bases.
3194 if (!Path && getLangOpts().MSVCCompat) {
3195 for (const CXXBasePath &PossiblePath : Paths) {
3196 if (PossiblePath.size() == 1) {
3197 Path = &PossiblePath;
3198 if (AmbiguousBaseConvID)
3199 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3200 << Base << Derived << Range;
3201 break;
3202 }
3203 }
3204 }
3205
3206 if (Path) {
3207 if (!IgnoreAccess) {
3208 // Check that the base class can be accessed.
3209 switch (
3210 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3211 case AR_inaccessible:
3212 return true;
3213 case AR_accessible:
3214 case AR_dependent:
3215 case AR_delayed:
3216 break;
3217 }
3218 }
3219
3220 // Build a base path if necessary.
3221 if (BasePath)
3222 ::BuildBasePathArray(*Path, *BasePath);
3223 return false;
3224 }
3225
3226 if (AmbiguousBaseConvID) {
3227 // We know that the derived-to-base conversion is ambiguous, and
3228 // we're going to produce a diagnostic. Perform the derived-to-base
3229 // search just one more time to compute all of the possible paths so
3230 // that we can print them out. This is more expensive than any of
3231 // the previous derived-to-base checks we've done, but at this point
3232 // performance isn't as much of an issue.
3233 Paths.clear();
3234 Paths.setRecordingPaths(true);
3235 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3236 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3237 (void)StillOkay;
3238
3239 // Build up a textual representation of the ambiguous paths, e.g.,
3240 // D -> B -> A, that will be used to illustrate the ambiguous
3241 // conversions in the diagnostic. We only print one of the paths
3242 // to each base class subobject.
3243 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3244
3245 Diag(Loc, AmbiguousBaseConvID)
3246 << Derived << Base << PathDisplayStr << Range << Name;
3247 }
3248 return true;
3249}
3250
3251bool
3253 SourceLocation Loc, SourceRange Range,
3254 CXXCastPath *BasePath,
3255 bool IgnoreAccess) {
3257 Derived, Base, diag::err_upcast_to_inaccessible_base,
3258 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3259 BasePath, IgnoreAccess);
3260}
3261
3263 std::string PathDisplayStr;
3264 std::set<unsigned> DisplayedPaths;
3265 for (const CXXBasePath &Path : Paths) {
3266 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
3267 // We haven't displayed a path to this particular base
3268 // class subobject yet.
3269 PathDisplayStr += "\n ";
3270 PathDisplayStr += QualType(Context.getCanonicalTagType(Paths.getOrigin()))
3271 .getAsString();
3272 for (const CXXBasePathElement &Element : Path)
3273 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3274 }
3275 }
3276
3277 return PathDisplayStr;
3278}
3279
3280//===----------------------------------------------------------------------===//
3281// C++ class member Handling
3282//===----------------------------------------------------------------------===//
3283
3285 SourceLocation ColonLoc,
3286 const ParsedAttributesView &Attrs) {
3287 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3289 ASLoc, ColonLoc);
3290 CurContext->addHiddenDecl(ASDecl);
3291 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3292}
3293
3295 if (D->isInvalidDecl())
3296 return;
3297
3298 // We only care about "override" and "final" declarations.
3299 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3300 return;
3301
3302 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3303
3304 // We can't check dependent instance methods.
3305 if (MD && MD->isInstance() &&
3306 (MD->getParent()->hasAnyDependentBases() ||
3307 MD->getType()->isDependentType()))
3308 return;
3309
3310 if (MD && !MD->isVirtual()) {
3311 // If we have a non-virtual method, check if it hides a virtual method.
3312 // (In that case, it's most likely the method has the wrong type.)
3313 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3314 FindHiddenVirtualMethods(MD, OverloadedMethods);
3315
3316 if (!OverloadedMethods.empty()) {
3317 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3318 Diag(OA->getLocation(),
3319 diag::override_keyword_hides_virtual_member_function)
3320 << "override" << (OverloadedMethods.size() > 1);
3321 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3322 Diag(FA->getLocation(),
3323 diag::override_keyword_hides_virtual_member_function)
3324 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3325 << (OverloadedMethods.size() > 1);
3326 }
3327 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3328 MD->setInvalidDecl();
3329 return;
3330 }
3331 // Fall through into the general case diagnostic.
3332 // FIXME: We might want to attempt typo correction here.
3333 }
3334
3335 if (!MD || !MD->isVirtual()) {
3336 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3337 Diag(OA->getLocation(),
3338 diag::override_keyword_only_allowed_on_virtual_member_functions)
3339 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3340 D->dropAttr<OverrideAttr>();
3341 }
3342 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3343 Diag(FA->getLocation(),
3344 diag::override_keyword_only_allowed_on_virtual_member_functions)
3345 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3346 << FixItHint::CreateRemoval(FA->getLocation());
3347 D->dropAttr<FinalAttr>();
3348 }
3349 return;
3350 }
3351
3352 // C++11 [class.virtual]p5:
3353 // If a function is marked with the virt-specifier override and
3354 // does not override a member function of a base class, the program is
3355 // ill-formed.
3356 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3357 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3358 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3359 << MD->getDeclName();
3360}
3361
3363 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3364 return;
3365 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3366 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3367 return;
3368
3369 SourceLocation Loc = MD->getLocation();
3370 SourceLocation SpellingLoc = Loc;
3371 if (getSourceManager().isMacroArgExpansion(Loc))
3372 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3373 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3374 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3375 return;
3376
3377 if (MD->size_overridden_methods() > 0) {
3378 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3379 unsigned DiagID =
3380 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3381 ? DiagInconsistent
3382 : DiagSuggest;
3383 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3384 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3385 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3386 };
3387 if (isa<CXXDestructorDecl>(MD))
3388 EmitDiag(
3389 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3390 diag::warn_suggest_destructor_marked_not_override_overriding);
3391 else
3392 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3393 diag::warn_suggest_function_marked_not_override_overriding);
3394 }
3395}
3396
3398 const CXXMethodDecl *Old) {
3399 FinalAttr *FA = Old->getAttr<FinalAttr>();
3400 if (!FA)
3401 return false;
3402
3403 Diag(New->getLocation(), diag::err_final_function_overridden)
3404 << New->getDeclName()
3405 << FA->isSpelledAsSealed();
3406 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3407 return true;
3408}
3409
3411 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3412 // FIXME: Destruction of ObjC lifetime types has side-effects.
3413 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3414 return !RD->isCompleteDefinition() ||
3415 !RD->hasTrivialDefaultConstructor() ||
3416 !RD->hasTrivialDestructor();
3417 return false;
3418}
3419
3420void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3421 DeclarationName FieldName,
3422 const CXXRecordDecl *RD,
3423 bool DeclIsField) {
3424 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3425 return;
3426
3427 // To record a shadowed field in a base
3428 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3429 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3430 CXXBasePath &Path) {
3431 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3432 // Record an ambiguous path directly
3433 if (Bases.find(Base) != Bases.end())
3434 return true;
3435 for (const auto Field : Base->lookup(FieldName)) {
3436 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3437 Field->getAccess() != AS_private) {
3438 assert(Field->getAccess() != AS_none);
3439 assert(Bases.find(Base) == Bases.end());
3440 Bases[Base] = Field;
3441 return true;
3442 }
3443 }
3444 return false;
3445 };
3446
3447 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3448 /*DetectVirtual=*/true);
3449 if (!RD->lookupInBases(FieldShadowed, Paths))
3450 return;
3451
3452 for (const auto &P : Paths) {
3453 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3454 auto It = Bases.find(Base);
3455 // Skip duplicated bases
3456 if (It == Bases.end())
3457 continue;
3458 auto BaseField = It->second;
3459 assert(BaseField->getAccess() != AS_private);
3460 if (AS_none !=
3461 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3462 Diag(Loc, diag::warn_shadow_field)
3463 << FieldName << RD << Base << DeclIsField;
3464 Diag(BaseField->getLocation(), diag::note_shadow_field);
3465 Bases.erase(It);
3466 }
3467 }
3468}
3469
3470template <typename AttrType>
3471inline static bool HasAttribute(const QualType &T) {
3472 if (const TagDecl *TD = T->getAsTagDecl())
3473 return TD->hasAttr<AttrType>();
3474 if (const TypedefType *TDT = T->getAs<TypedefType>())
3475 return TDT->getDecl()->hasAttr<AttrType>();
3476 return false;
3477}
3478
3479static bool IsUnusedPrivateField(const FieldDecl *FD) {
3480 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3481 QualType FieldType = FD->getType();
3482 if (HasAttribute<WarnUnusedAttr>(FieldType))
3483 return true;
3484
3485 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3486 !FD->getParent()->isDependentContext() &&
3487 !HasAttribute<UnusedAttr>(FieldType) &&
3489 }
3490 return false;
3491}
3492
3493NamedDecl *
3495 MultiTemplateParamsArg TemplateParameterLists,
3496 Expr *BitWidth, const VirtSpecifiers &VS,
3497 InClassInitStyle InitStyle) {
3498 const DeclSpec &DS = D.getDeclSpec();
3500 DeclarationName Name = NameInfo.getName();
3501 SourceLocation Loc = NameInfo.getLoc();
3502
3503 // For anonymous bitfields, the location should point to the type.
3504 if (Loc.isInvalid())
3505 Loc = D.getBeginLoc();
3506
3508 assert(!DS.isFriendSpecified());
3509
3510 bool isFunc = D.isDeclarationOfFunction();
3511 const ParsedAttr *MSPropertyAttr =
3513
3514 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3515 // The Microsoft extension __interface only permits public member functions
3516 // and prohibits constructors, destructors, operators, non-public member
3517 // functions, static methods and data members.
3518 unsigned InvalidDecl;
3519 bool ShowDeclName = true;
3520 if (!isFunc &&
3521 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3522 InvalidDecl = 0;
3523 else if (!isFunc)
3524 InvalidDecl = 1;
3525 else if (AS != AS_public)
3526 InvalidDecl = 2;
3528 InvalidDecl = 3;
3529 else switch (Name.getNameKind()) {
3531 InvalidDecl = 4;
3532 ShowDeclName = false;
3533 break;
3534
3536 InvalidDecl = 5;
3537 ShowDeclName = false;
3538 break;
3539
3542 InvalidDecl = 6;
3543 break;
3544
3545 default:
3546 InvalidDecl = 0;
3547 break;
3548 }
3549
3550 if (InvalidDecl) {
3551 if (ShowDeclName)
3552 Diag(Loc, diag::err_invalid_member_in_interface)
3553 << (InvalidDecl-1) << Name;
3554 else
3555 Diag(Loc, diag::err_invalid_member_in_interface)
3556 << (InvalidDecl-1) << "";
3557 return nullptr;
3558 }
3559 }
3560
3561 // HLSL prohibits user defined constructors and destructors.
3562 if (getLangOpts().HLSL) {
3563 switch (Name.getNameKind()) {
3566 Diag(Loc, diag::err_hlsl_cstor_dstor);
3567 return nullptr;
3568 default:
3569 break;
3570 }
3571 }
3572
3573 // C++ 9.2p6: A member shall not be declared to have automatic storage
3574 // duration (auto, register) or with the extern storage-class-specifier.
3575 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3576 // data members and cannot be applied to names declared const or static,
3577 // and cannot be applied to reference members.
3578 switch (DS.getStorageClassSpec()) {
3582 break;
3584 if (isFunc) {
3585 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3586
3587 // FIXME: It would be nicer if the keyword was ignored only for this
3588 // declarator. Otherwise we could get follow-up errors.
3590 }
3591 break;
3592 default:
3594 diag::err_storageclass_invalid_for_member);
3596 break;
3597 }
3598
3599 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3601 !isFunc && TemplateParameterLists.empty();
3602
3603 if (DS.hasConstexprSpecifier() && isInstField) {
3605 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3606 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3607 if (InitStyle == ICIS_NoInit) {
3608 B << 0 << 0;
3610 B << FixItHint::CreateRemoval(ConstexprLoc);
3611 else {
3612 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3614 const char *PrevSpec;
3615 unsigned DiagID;
3616 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3617 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3618 (void)Failed;
3619 assert(!Failed && "Making a constexpr member const shouldn't fail");
3620 }
3621 } else {
3622 B << 1;
3623 const char *PrevSpec;
3624 unsigned DiagID;
3626 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3627 Context.getPrintingPolicy())) {
3629 "This is the only DeclSpec that should fail to be applied");
3630 B << 1;
3631 } else {
3632 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3633 isInstField = false;
3634 }
3635 }
3636 }
3637
3639 if (isInstField) {
3640 CXXScopeSpec &SS = D.getCXXScopeSpec();
3641
3642 // Data members must have identifiers for names.
3643 if (!Name.isIdentifier()) {
3644 Diag(Loc, diag::err_bad_variable_name)
3645 << Name;
3646 return nullptr;
3647 }
3648
3651 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3652 << II
3656 D.SetIdentifier(II, Loc);
3657 }
3658
3659 if (SS.isSet() && !SS.isInvalid()) {
3660 // The user provided a superfluous scope specifier inside a class
3661 // definition:
3662 //
3663 // class X {
3664 // int X::member;
3665 // };
3666 if (DeclContext *DC = computeDeclContext(SS, false)) {
3667 TemplateIdAnnotation *TemplateId =
3669 ? D.getName().TemplateId
3670 : nullptr;
3672 TemplateId,
3673 /*IsMemberSpecialization=*/false);
3674 } else {
3675 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3676 << Name << SS.getRange();
3677 }
3678 SS.clear();
3679 }
3680
3681 if (MSPropertyAttr) {
3683 BitWidth, InitStyle, AS, *MSPropertyAttr);
3684 if (!Member)
3685 return nullptr;
3686 isInstField = false;
3687 } else {
3689 BitWidth, InitStyle, AS);
3690 if (!Member)
3691 return nullptr;
3692 }
3693
3694 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3695 } else {
3696 Member = HandleDeclarator(S, D, TemplateParameterLists);
3697 if (!Member)
3698 return nullptr;
3699
3700 // Non-instance-fields can't have a bitfield.
3701 if (BitWidth) {
3702 if (Member->isInvalidDecl()) {
3703 // don't emit another diagnostic.
3705 // C++ 9.6p3: A bit-field shall not be a static member.
3706 // "static member 'A' cannot be a bit-field"
3707 Diag(Loc, diag::err_static_not_bitfield)
3708 << Name << BitWidth->getSourceRange();
3709 } else if (isa<TypedefDecl>(Member)) {
3710 // "typedef member 'x' cannot be a bit-field"
3711 Diag(Loc, diag::err_typedef_not_bitfield)
3712 << Name << BitWidth->getSourceRange();
3713 } else {
3714 // A function typedef ("typedef int f(); f a;").
3715 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3716 Diag(Loc, diag::err_not_integral_type_bitfield)
3717 << Name << cast<ValueDecl>(Member)->getType()
3718 << BitWidth->getSourceRange();
3719 }
3720
3721 BitWidth = nullptr;
3722 Member->setInvalidDecl();
3723 }
3724
3725 NamedDecl *NonTemplateMember = Member;
3726 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3727 NonTemplateMember = FunTmpl->getTemplatedDecl();
3728 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3729 NonTemplateMember = VarTmpl->getTemplatedDecl();
3730
3731 Member->setAccess(AS);
3732
3733 // If we have declared a member function template or static data member
3734 // template, set the access of the templated declaration as well.
3735 if (NonTemplateMember != Member)
3736 NonTemplateMember->setAccess(AS);
3737
3738 // C++ [temp.deduct.guide]p3:
3739 // A deduction guide [...] for a member class template [shall be
3740 // declared] with the same access [as the template].
3741 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3742 auto *TD = DG->getDeducedTemplate();
3743 // Access specifiers are only meaningful if both the template and the
3744 // deduction guide are from the same scope.
3745 if (AS != TD->getAccess() &&
3746 TD->getDeclContext()->getRedeclContext()->Equals(
3747 DG->getDeclContext()->getRedeclContext())) {
3748 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3749 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3750 << TD->getAccess();
3751 const AccessSpecDecl *LastAccessSpec = nullptr;
3752 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3753 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3754 LastAccessSpec = AccessSpec;
3755 }
3756 assert(LastAccessSpec && "differing access with no access specifier");
3757 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3758 << AS;
3759 }
3760 }
3761 }
3762
3763 if (VS.isOverrideSpecified())
3764 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3765 if (VS.isFinalSpecified())
3766 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3768 ? FinalAttr::Keyword_sealed
3769 : FinalAttr::Keyword_final));
3770
3771 if (VS.getLastLocation().isValid()) {
3772 // Update the end location of a method that has a virt-specifiers.
3773 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3774 MD->setRangeEnd(VS.getLastLocation());
3775 }
3776
3778
3779 assert((Name || isInstField) && "No identifier for non-field ?");
3780
3781 if (isInstField) {
3783 FieldCollector->Add(FD);
3784
3785 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3787 // Remember all explicit private FieldDecls that have a name, no side
3788 // effects and are not part of a dependent type declaration.
3789 UnusedPrivateFields.insert(FD);
3790 }
3791 }
3792
3793 return Member;
3794}
3795
3796namespace {
3797 class UninitializedFieldVisitor
3798 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3799 Sema &S;
3800 // List of Decls to generate a warning on. Also remove Decls that become
3801 // initialized.
3802 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3803 // List of base classes of the record. Classes are removed after their
3804 // initializers.
3805 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3806 // Vector of decls to be removed from the Decl set prior to visiting the
3807 // nodes. These Decls may have been initialized in the prior initializer.
3809 // If non-null, add a note to the warning pointing back to the constructor.
3811 // Variables to hold state when processing an initializer list. When
3812 // InitList is true, special case initialization of FieldDecls matching
3813 // InitListFieldDecl.
3814 bool InitList;
3815 FieldDecl *InitListFieldDecl;
3816 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3817
3818 public:
3820 UninitializedFieldVisitor(Sema &S,
3821 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3822 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3823 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3824 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3825
3826 // Returns true if the use of ME is not an uninitialized use.
3827 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3828 bool CheckReferenceOnly) {
3830 bool ReferenceField = false;
3831 while (ME) {
3832 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3833 if (!FD)
3834 return false;
3835 Fields.push_back(FD);
3836 if (FD->getType()->isReferenceType())
3837 ReferenceField = true;
3838 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3839 }
3840
3841 // Binding a reference to an uninitialized field is not an
3842 // uninitialized use.
3843 if (CheckReferenceOnly && !ReferenceField)
3844 return true;
3845
3846 // Discard the first field since it is the field decl that is being
3847 // initialized.
3848 auto UsedFields = llvm::drop_begin(llvm::reverse(Fields));
3849 auto UsedIter = UsedFields.begin();
3850 const auto UsedEnd = UsedFields.end();
3851
3852 for (const unsigned Orig : InitFieldIndex) {
3853 if (UsedIter == UsedEnd)
3854 break;
3855 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3856 if (UsedIndex < Orig)
3857 return true;
3858 if (UsedIndex > Orig)
3859 break;
3860 ++UsedIter;
3861 }
3862
3863 return false;
3864 }
3865
3866 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3867 bool AddressOf) {
3869 return;
3870
3871 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3872 // or union.
3873 MemberExpr *FieldME = ME;
3874
3875 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3876
3877 Expr *Base = ME;
3878 while (MemberExpr *SubME =
3879 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3880
3881 if (isa<VarDecl>(SubME->getMemberDecl()))
3882 return;
3883
3884 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3885 if (!FD->isAnonymousStructOrUnion())
3886 FieldME = SubME;
3887
3888 if (!FieldME->getType().isPODType(S.Context))
3889 AllPODFields = false;
3890
3891 Base = SubME->getBase();
3892 }
3893
3894 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3895 Visit(Base);
3896 return;
3897 }
3898
3899 if (AddressOf && AllPODFields)
3900 return;
3901
3902 ValueDecl* FoundVD = FieldME->getMemberDecl();
3903
3904 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3905 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3906 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3907 }
3908
3909 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3910 QualType T = BaseCast->getType();
3911 if (T->isPointerType() &&
3912 BaseClasses.count(T->getPointeeType())) {
3913 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3914 << T->getPointeeType() << FoundVD;
3915 }
3916 }
3917 }
3918
3919 if (!Decls.count(FoundVD))
3920 return;
3921
3922 const bool IsReference = FoundVD->getType()->isReferenceType();
3923
3924 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3925 // Special checking for initializer lists.
3926 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3927 return;
3928 }
3929 } else {
3930 // Prevent double warnings on use of unbounded references.
3931 if (CheckReferenceOnly && !IsReference)
3932 return;
3933 }
3934
3935 unsigned diag = IsReference
3936 ? diag::warn_reference_field_is_uninit
3937 : diag::warn_field_is_uninit;
3938 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3939 if (Constructor)
3940 S.Diag(Constructor->getLocation(),
3941 diag::note_uninit_in_this_constructor)
3942 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3943
3944 }
3945
3946 void HandleValue(Expr *E, bool AddressOf) {
3947 E = E->IgnoreParens();
3948
3949 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3950 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3951 AddressOf /*AddressOf*/);
3952 return;
3953 }
3954
3955 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3956 Visit(CO->getCond());
3957 HandleValue(CO->getTrueExpr(), AddressOf);
3958 HandleValue(CO->getFalseExpr(), AddressOf);
3959 return;
3960 }
3961
3962 if (BinaryConditionalOperator *BCO =
3963 dyn_cast<BinaryConditionalOperator>(E)) {
3964 Visit(BCO->getCond());
3965 HandleValue(BCO->getFalseExpr(), AddressOf);
3966 return;
3967 }
3968
3969 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3970 HandleValue(OVE->getSourceExpr(), AddressOf);
3971 return;
3972 }
3973
3974 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3975 switch (BO->getOpcode()) {
3976 default:
3977 break;
3978 case(BO_PtrMemD):
3979 case(BO_PtrMemI):
3980 HandleValue(BO->getLHS(), AddressOf);
3981 Visit(BO->getRHS());
3982 return;
3983 case(BO_Comma):
3984 Visit(BO->getLHS());
3985 HandleValue(BO->getRHS(), AddressOf);
3986 return;
3987 }
3988 }
3989
3990 Visit(E);
3991 }
3992
3993 void CheckInitListExpr(InitListExpr *ILE) {
3994 InitFieldIndex.push_back(0);
3995 for (auto *Child : ILE->children()) {
3996 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3997 CheckInitListExpr(SubList);
3998 } else {
3999 Visit(Child);
4000 }
4001 ++InitFieldIndex.back();
4002 }
4003 InitFieldIndex.pop_back();
4004 }
4005
4006 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
4007 FieldDecl *Field, const Type *BaseClass) {
4008 // Remove Decls that may have been initialized in the previous
4009 // initializer.
4010 for (ValueDecl* VD : DeclsToRemove)
4011 Decls.erase(VD);
4012 DeclsToRemove.clear();
4013
4014 Constructor = FieldConstructor;
4015 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
4016
4017 if (ILE && Field) {
4018 InitList = true;
4019 InitListFieldDecl = Field;
4020 InitFieldIndex.clear();
4021 CheckInitListExpr(ILE);
4022 } else {
4023 InitList = false;
4024 Visit(E);
4025 }
4026
4027 if (Field)
4028 Decls.erase(Field);
4029 if (BaseClass)
4030 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
4031 }
4032
4033 void VisitMemberExpr(MemberExpr *ME) {
4034 // All uses of unbounded reference fields will warn.
4035 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4036 }
4037
4038 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4039 if (E->getCastKind() == CK_LValueToRValue) {
4040 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4041 return;
4042 }
4043
4044 Inherited::VisitImplicitCastExpr(E);
4045 }
4046
4047 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4048 if (E->getConstructor()->isCopyConstructor()) {
4049 Expr *ArgExpr = E->getArg(0);
4050 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4051 if (ILE->getNumInits() == 1)
4052 ArgExpr = ILE->getInit(0);
4053 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4054 if (ICE->getCastKind() == CK_NoOp)
4055 ArgExpr = ICE->getSubExpr();
4056 HandleValue(ArgExpr, false /*AddressOf*/);
4057 return;
4058 }
4059 Inherited::VisitCXXConstructExpr(E);
4060 }
4061
4062 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4063 Expr *Callee = E->getCallee();
4064 if (isa<MemberExpr>(Callee)) {
4065 HandleValue(Callee, false /*AddressOf*/);
4066 for (auto *Arg : E->arguments())
4067 Visit(Arg);
4068 return;
4069 }
4070
4071 Inherited::VisitCXXMemberCallExpr(E);
4072 }
4073
4074 void VisitCallExpr(CallExpr *E) {
4075 // Treat std::move as a use.
4076 if (E->isCallToStdMove()) {
4077 HandleValue(E->getArg(0), /*AddressOf=*/false);
4078 return;
4079 }
4080
4081 Inherited::VisitCallExpr(E);
4082 }
4083
4084 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4085 Expr *Callee = E->getCallee();
4086
4087 if (isa<UnresolvedLookupExpr>(Callee))
4088 return Inherited::VisitCXXOperatorCallExpr(E);
4089
4090 Visit(Callee);
4091 for (auto *Arg : E->arguments())
4092 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4093 }
4094
4095 void VisitBinaryOperator(BinaryOperator *E) {
4096 // If a field assignment is detected, remove the field from the
4097 // uninitiailized field set.
4098 if (E->getOpcode() == BO_Assign)
4099 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4100 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4101 if (!FD->getType()->isReferenceType())
4102 DeclsToRemove.push_back(FD);
4103
4104 if (E->isCompoundAssignmentOp()) {
4105 HandleValue(E->getLHS(), false /*AddressOf*/);
4106 Visit(E->getRHS());
4107 return;
4108 }
4109
4110 Inherited::VisitBinaryOperator(E);
4111 }
4112
4113 void VisitUnaryOperator(UnaryOperator *E) {
4114 if (E->isIncrementDecrementOp()) {
4115 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4116 return;
4117 }
4118 if (E->getOpcode() == UO_AddrOf) {
4119 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4120 HandleValue(ME->getBase(), true /*AddressOf*/);
4121 return;
4122 }
4123 }
4124
4125 Inherited::VisitUnaryOperator(E);
4126 }
4127 };
4128
4129 // Diagnose value-uses of fields to initialize themselves, e.g.
4130 // foo(foo)
4131 // where foo is not also a parameter to the constructor.
4132 // Also diagnose across field uninitialized use such as
4133 // x(y), y(x)
4134 // TODO: implement -Wuninitialized and fold this into that framework.
4135 static void DiagnoseUninitializedFields(
4136 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4137
4138 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4139 Constructor->getLocation())) {
4140 return;
4141 }
4142
4143 if (Constructor->isInvalidDecl())
4144 return;
4145
4146 const CXXRecordDecl *RD = Constructor->getParent();
4147
4148 if (RD->isDependentContext())
4149 return;
4150
4151 // Holds fields that are uninitialized.
4152 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4153
4154 // At the beginning, all fields are uninitialized.
4155 for (auto *I : RD->decls()) {
4156 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4157 UninitializedFields.insert(FD);
4158 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4159 UninitializedFields.insert(IFD->getAnonField());
4160 }
4161 }
4162
4163 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4164 for (const auto &I : RD->bases()) {
4165 // Virtual bases are initialized from the most derived class, so an
4166 // abstract base class constructor can assume it to be initialized.
4167 if (I.isVirtual() && RD->isAbstract())
4168 continue;
4169 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4170 }
4171
4172 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4173 return;
4174
4175 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4176 UninitializedFields,
4177 UninitializedBaseClasses);
4178
4179 for (const auto *FieldInit : Constructor->inits()) {
4180 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4181 break;
4182
4183 Expr *InitExpr = FieldInit->getInit();
4184 if (!InitExpr)
4185 continue;
4186
4187 if (CXXDefaultInitExpr *Default =
4188 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4189 InitExpr = Default->getExpr();
4190 if (!InitExpr)
4191 continue;
4192 // In class initializers will point to the constructor.
4193 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4194 FieldInit->getAnyMember(),
4195 FieldInit->getBaseClass());
4196 } else {
4197 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4198 FieldInit->getAnyMember(),
4199 FieldInit->getBaseClass());
4200 }
4201 }
4202 }
4203} // namespace
4204
4206 // Create a synthetic function scope to represent the call to the constructor
4207 // that notionally surrounds a use of this initializer.
4209}
4210
4212 if (!D.isFunctionDeclarator())
4213 return;
4214 auto &FTI = D.getFunctionTypeInfo();
4215 if (!FTI.Params)
4216 return;
4217 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4218 FTI.NumParams)) {
4219 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4220 if (ParamDecl->getDeclName())
4221 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4222 }
4223}
4224
4226 return ActOnRequiresClause(ConstraintExpr);
4227}
4228
4230 if (ConstraintExpr.isInvalid())
4231 return ExprError();
4232
4233 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4235 return ExprError();
4236
4237 return ConstraintExpr;
4238}
4239
4247
4249 FieldDecl *FD, const InitializedEntity &Entity, Expr *InitExpr,
4250 SourceLocation InitLoc) {
4251 InitializationKind Kind =
4254 InitExpr->getBeginLoc(),
4255 InitExpr->getEndLoc())
4256 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4257 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4258 return Seq.Perform(*this, Entity, Kind, InitExpr);
4259}
4260
4262 SourceLocation InitLoc,
4263 ExprResult InitExpr) {
4264 // Pop the notional constructor scope we created earlier.
4265 PopFunctionScopeInfo(nullptr, D);
4266
4267 // Microsoft C++'s property declaration cannot have a default member
4268 // initializer.
4269 if (isa<MSPropertyDecl>(D)) {
4270 D->setInvalidDecl();
4271 return;
4272 }
4273
4274 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4275 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4276 "must set init style when field is created");
4277
4278 if (!InitExpr.isUsable() ||
4280 FD->setInvalidDecl();
4281 ExprResult RecoveryInit =
4282 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4283 if (RecoveryInit.isUsable())
4284 FD->setInClassInitializer(RecoveryInit.get());
4285 return;
4286 }
4287
4288 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4289 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr.get(), InitLoc);
4290 // C++11 [class.base.init]p7:
4291 // The initialization of each base and member constitutes a
4292 // full-expression.
4293 if (!InitExpr.isInvalid())
4294 InitExpr = ActOnFinishFullExpr(InitExpr.get(), /*DiscarededValue=*/false);
4295 if (InitExpr.isInvalid()) {
4296 FD->setInvalidDecl();
4297 return;
4298 }
4299 }
4300
4301 FD->setInClassInitializer(InitExpr.get());
4302}
4303
4304/// Find the direct and/or virtual base specifiers that
4305/// correspond to the given base type, for use in base initialization
4306/// within a constructor.
4307static bool FindBaseInitializer(Sema &SemaRef,
4308 CXXRecordDecl *ClassDecl,
4309 QualType BaseType,
4310 const CXXBaseSpecifier *&DirectBaseSpec,
4311 const CXXBaseSpecifier *&VirtualBaseSpec) {
4312 // First, check for a direct base class.
4313 DirectBaseSpec = nullptr;
4314 for (const auto &Base : ClassDecl->bases()) {
4315 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4316 // We found a direct base of this type. That's what we're
4317 // initializing.
4318 DirectBaseSpec = &Base;
4319 break;
4320 }
4321 }
4322
4323 // Check for a virtual base class.
4324 // FIXME: We might be able to short-circuit this if we know in advance that
4325 // there are no virtual bases.
4326 VirtualBaseSpec = nullptr;
4327 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4328 // We haven't found a base yet; search the class hierarchy for a
4329 // virtual base class.
4330 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4331 /*DetectVirtual=*/false);
4332 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4333 SemaRef.Context.getCanonicalTagType(ClassDecl),
4334 BaseType, Paths)) {
4335 for (const CXXBasePath &Path : Paths) {
4336 if (Path.back().Base->isVirtual()) {
4337 VirtualBaseSpec = Path.back().Base;
4338 break;
4339 }
4340 }
4341 }
4342 }
4343
4344 return DirectBaseSpec || VirtualBaseSpec;
4345}
4346
4349 Scope *S,
4350 CXXScopeSpec &SS,
4351 IdentifierInfo *MemberOrBase,
4352 ParsedType TemplateTypeTy,
4353 const DeclSpec &DS,
4354 SourceLocation IdLoc,
4355 Expr *InitList,
4356 SourceLocation EllipsisLoc) {
4357 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4358 DS, IdLoc, InitList,
4359 EllipsisLoc);
4360}
4361
4364 Scope *S,
4365 CXXScopeSpec &SS,
4366 IdentifierInfo *MemberOrBase,
4367 ParsedType TemplateTypeTy,
4368 const DeclSpec &DS,
4369 SourceLocation IdLoc,
4370 SourceLocation LParenLoc,
4371 ArrayRef<Expr *> Args,
4372 SourceLocation RParenLoc,
4373 SourceLocation EllipsisLoc) {
4374 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4375 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4376 DS, IdLoc, List, EllipsisLoc);
4377}
4378
4379namespace {
4380
4381// Callback to only accept typo corrections that can be a valid C++ member
4382// initializer: either a non-static field member or a base class.
4383class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4384public:
4385 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4386 : ClassDecl(ClassDecl) {}
4387
4388 bool ValidateCandidate(const TypoCorrection &candidate) override {
4389 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4390 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4391 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4392 return isa<TypeDecl>(ND);
4393 }
4394 return false;
4395 }
4396
4397 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4398 return std::make_unique<MemInitializerValidatorCCC>(*this);
4399 }
4400
4401private:
4402 CXXRecordDecl *ClassDecl;
4403};
4404
4405}
4406
4408 RecordDecl *ClassDecl,
4409 const IdentifierInfo *Name) {
4410 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4412 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4413 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4415 });
4416 // We did not find a placeholder variable
4417 if (Found == Result.end())
4418 return false;
4419 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4420 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4421 const NamedDecl *ND = *It;
4422 if (ND->getDeclContext() != ND->getDeclContext())
4423 break;
4426 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4427 }
4428 return true;
4429}
4430
4431ValueDecl *
4433 const IdentifierInfo *MemberOrBase) {
4434 ValueDecl *ND = nullptr;
4435 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4437 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4438 if (ND) {
4439 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4440 return nullptr;
4441 break;
4442 }
4443 if (!IsPlaceholder)
4444 return cast<ValueDecl>(D);
4445 ND = cast<ValueDecl>(D);
4446 }
4447 }
4448 return ND;
4449}
4450
4452 CXXScopeSpec &SS,
4453 ParsedType TemplateTypeTy,
4454 IdentifierInfo *MemberOrBase) {
4455 if (SS.getScopeRep() || TemplateTypeTy)
4456 return nullptr;
4457 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4458}
4459
4462 Scope *S,
4463 CXXScopeSpec &SS,
4464 IdentifierInfo *MemberOrBase,
4465 ParsedType TemplateTypeTy,
4466 const DeclSpec &DS,
4467 SourceLocation IdLoc,
4468 Expr *Init,
4469 SourceLocation EllipsisLoc) {
4470 if (!ConstructorD || !Init)
4471 return true;
4472
4473 AdjustDeclIfTemplate(ConstructorD);
4474
4476 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4477 if (!Constructor) {
4478 // The user wrote a constructor initializer on a function that is
4479 // not a C++ constructor. Ignore the error for now, because we may
4480 // have more member initializers coming; we'll diagnose it just
4481 // once in ActOnMemInitializers.
4482 return true;
4483 }
4484
4485 CXXRecordDecl *ClassDecl = Constructor->getParent();
4486
4487 // C++ [class.base.init]p2:
4488 // Names in a mem-initializer-id are looked up in the scope of the
4489 // constructor's class and, if not found in that scope, are looked
4490 // up in the scope containing the constructor's definition.
4491 // [Note: if the constructor's class contains a member with the
4492 // same name as a direct or virtual base class of the class, a
4493 // mem-initializer-id naming the member or base class and composed
4494 // of a single identifier refers to the class member. A
4495 // mem-initializer-id for the hidden base class may be specified
4496 // using a qualified name. ]
4497
4498 // Look for a member, first.
4500 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4501 if (EllipsisLoc.isValid())
4502 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4503 << MemberOrBase
4504 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4505
4506 return BuildMemberInitializer(Member, Init, IdLoc);
4507 }
4508 // It didn't name a member, so see if it names a class.
4509 QualType BaseType;
4510 TypeSourceInfo *TInfo = nullptr;
4511
4512 if (TemplateTypeTy) {
4513 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4514 if (BaseType.isNull())
4515 return true;
4516 } else if (DS.getTypeSpecType() == TST_decltype) {
4517 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4518 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4519 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4520 return true;
4521 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4522 BaseType = GetTypeFromParser(DS.getRepAsType(), &TInfo);
4523 if (BaseType.isNull())
4524 return true;
4525 } else {
4526 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4527 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4528
4529 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4530 if (!TyD) {
4531 if (R.isAmbiguous()) return true;
4532
4533 // We don't want access-control diagnostics here.
4534 R.suppressDiagnostics();
4535
4536 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4537 bool NotUnknownSpecialization = false;
4538 DeclContext *DC = computeDeclContext(SS, false);
4539 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4540 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4541
4542 if (!NotUnknownSpecialization) {
4543 // When the scope specifier can refer to a member of an unknown
4544 // specialization, we take it as a type name.
4545 BaseType = CheckTypenameType(
4547 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4548 if (BaseType.isNull())
4549 return true;
4550
4551 TInfo = Context.CreateTypeSourceInfo(BaseType);
4554 if (!TL.isNull()) {
4555 TL.setNameLoc(IdLoc);
4558 }
4559
4560 R.clear();
4561 R.setLookupName(MemberOrBase);
4562 }
4563 }
4564
4565 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4566 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4567 auto *TempSpec = cast<TemplateSpecializationType>(
4568 UnqualifiedBase->getCanonicalInjectedSpecializationType(Context));
4569 TemplateName TN = TempSpec->getTemplateName();
4570 for (auto const &Base : ClassDecl->bases()) {
4571 auto BaseTemplate =
4572 Base.getType()->getAs<TemplateSpecializationType>();
4573 if (BaseTemplate &&
4574 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4575 /*IgnoreDeduced=*/true)) {
4576 Diag(IdLoc, diag::ext_unqualified_base_class)
4577 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4578 BaseType = Base.getType();
4579 break;
4580 }
4581 }
4582 }
4583 }
4584
4585 // If no results were found, try to correct typos.
4586 TypoCorrection Corr;
4587 MemInitializerValidatorCCC CCC(ClassDecl);
4588 if (R.empty() && BaseType.isNull() &&
4589 (Corr =
4590 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4591 CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {
4593 // We have found a non-static data member with a similar
4594 // name to what was typed; complain and initialize that
4595 // member.
4596 diagnoseTypo(Corr,
4597 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4598 << MemberOrBase << true);
4599 return BuildMemberInitializer(Member, Init, IdLoc);
4600 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4601 const CXXBaseSpecifier *DirectBaseSpec;
4602 const CXXBaseSpecifier *VirtualBaseSpec;
4603 if (FindBaseInitializer(*this, ClassDecl,
4604 Context.getTypeDeclType(Type),
4605 DirectBaseSpec, VirtualBaseSpec)) {
4606 // We have found a direct or virtual base class with a
4607 // similar name to what was typed; complain and initialize
4608 // that base class.
4609 diagnoseTypo(Corr,
4610 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4611 << MemberOrBase << false,
4612 PDiag() /*Suppress note, we provide our own.*/);
4613
4614 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4615 : VirtualBaseSpec;
4616 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4617 << BaseSpec->getType() << BaseSpec->getSourceRange();
4618
4619 TyD = Type;
4620 }
4621 }
4622 }
4623
4624 if (!TyD && BaseType.isNull()) {
4625 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4626 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4627 return true;
4628 }
4629 }
4630
4631 if (BaseType.isNull()) {
4632 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4633
4634 TypeLocBuilder TLB;
4635 // FIXME: This is missing building the UsingType for TyD, if any.
4636 if (const auto *TD = dyn_cast<TagDecl>(TyD)) {
4637 BaseType = Context.getTagType(ElaboratedTypeKeyword::None,
4638 SS.getScopeRep(), TD, /*OwnsTag=*/false);
4639 auto TL = TLB.push<TagTypeLoc>(BaseType);
4641 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4642 TL.setNameLoc(IdLoc);
4643 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TyD)) {
4644 BaseType = Context.getTypedefType(ElaboratedTypeKeyword::None,
4645 SS.getScopeRep(), TN);
4646 TLB.push<TypedefTypeLoc>(BaseType).set(
4647 /*ElaboratedKeywordLoc=*/SourceLocation(),
4648 SS.getWithLocInContext(Context), IdLoc);
4649 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TyD)) {
4650 BaseType = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
4651 SS.getScopeRep(), UD);
4652 TLB.push<UnresolvedUsingTypeLoc>(BaseType).set(
4653 /*ElaboratedKeywordLoc=*/SourceLocation(),
4654 SS.getWithLocInContext(Context), IdLoc);
4655 } else {
4656 // FIXME: What else can appear here?
4657 assert(SS.isEmpty());
4658 BaseType = Context.getTypeDeclType(TyD);
4659 TLB.pushTypeSpec(BaseType).setNameLoc(IdLoc);
4660 }
4661 TInfo = TLB.getTypeSourceInfo(Context, BaseType);
4662 }
4663 }
4664
4665 if (!TInfo)
4666 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4667
4668 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4669}
4670
4673 SourceLocation IdLoc) {
4674 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4675 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4676 assert((DirectMember || IndirectMember) &&
4677 "Member must be a FieldDecl or IndirectFieldDecl");
4678
4680 return true;
4681
4682 if (Member->isInvalidDecl())
4683 return true;
4684
4685 MultiExprArg Args;
4686 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4687 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4688 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4689 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4690 } else if (auto *ParenListInit = dyn_cast<CXXParenListInitExpr>(Init)) {
4691 // Template instantiation reverts the elements to their syntactic form;
4692 // redo the initialization from the written arguments.
4693 Args = ParenListInit->getUserSpecifiedInitExprs();
4694 } else {
4695 // Template instantiation doesn't reconstruct ParenListExprs for us.
4696 Args = Init;
4697 }
4698
4699 SourceRange InitRange = Init->getSourceRange();
4700
4701 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4702 // Can't check initialization for a member of dependent type or when
4703 // any of the arguments are type-dependent expressions.
4705 } else {
4706 bool InitList = false;
4707 if (isa<InitListExpr>(Init)) {
4708 InitList = true;
4709 Args = Init;
4710 }
4711
4712 // Initialize the member.
4713 InitializedEntity MemberEntity =
4714 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4715 : InitializedEntity::InitializeMember(IndirectMember,
4716 nullptr);
4717 InitializationKind Kind =
4719 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4720 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4721 InitRange.getEnd());
4722
4723 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4724 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4725 nullptr);
4726 if (!MemberInit.isInvalid()) {
4727 // C++11 [class.base.init]p7:
4728 // The initialization of each base and member constitutes a
4729 // full-expression.
4730 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4731 /*DiscardedValue*/ false);
4732 }
4733
4734 if (MemberInit.isInvalid()) {
4735 // Args were sensible expressions but we couldn't initialize the member
4736 // from them. Preserve them in a RecoveryExpr instead.
4737 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4738 Member->getType())
4739 .get();
4740 if (!Init)
4741 return true;
4742 } else {
4743 Init = MemberInit.get();
4744 }
4745 }
4746
4747 if (DirectMember) {
4748 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4749 InitRange.getBegin(), Init,
4750 InitRange.getEnd());
4751 } else {
4752 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4753 InitRange.getBegin(), Init,
4754 InitRange.getEnd());
4755 }
4756}
4757
4760 CXXRecordDecl *ClassDecl) {
4761 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4762 if (!LangOpts.CPlusPlus11)
4763 return Diag(NameLoc, diag::err_delegating_ctor)
4764 << TInfo->getTypeLoc().getSourceRange();
4765 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4766
4767 bool InitList = true;
4768 MultiExprArg Args = Init;
4769 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4770 InitList = false;
4771 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4772 }
4773
4774 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
4775
4776 SourceRange InitRange = Init->getSourceRange();
4777 // Initialize the object.
4778 InitializedEntity DelegationEntity =
4780 InitializationKind Kind =
4782 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4783 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4784 InitRange.getEnd());
4785 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4786 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4787 Args, nullptr);
4788 if (!DelegationInit.isInvalid()) {
4789 assert((DelegationInit.get()->containsErrors() ||
4790 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4791 "Delegating constructor with no target?");
4792
4793 // C++11 [class.base.init]p7:
4794 // The initialization of each base and member constitutes a
4795 // full-expression.
4796 DelegationInit = ActOnFinishFullExpr(
4797 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4798 }
4799
4800 if (DelegationInit.isInvalid()) {
4801 DelegationInit = CreateRecoveryExpr(InitRange.getBegin(),
4802 InitRange.getEnd(), Args, ClassType);
4803 if (DelegationInit.isInvalid())
4804 return true;
4805 } else {
4806 // If we are in a dependent context, template instantiation will
4807 // perform this type-checking again. Just save the arguments that we
4808 // received in a ParenListExpr.
4809 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4810 // of the information that we have about the base
4811 // initializer. However, deconstructing the ASTs is a dicey process,
4812 // and this approach is far more likely to get the corner cases right.
4813 if (CurContext->isDependentContext())
4814 DelegationInit = Init;
4815 }
4816
4817 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4818 DelegationInit.getAs<Expr>(),
4819 InitRange.getEnd());
4820}
4821
4824 Expr *Init, CXXRecordDecl *ClassDecl,
4825 SourceLocation EllipsisLoc) {
4826 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4827
4828 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4829 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4830 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4831
4832 // C++ [class.base.init]p2:
4833 // [...] Unless the mem-initializer-id names a nonstatic data
4834 // member of the constructor's class or a direct or virtual base
4835 // of that class, the mem-initializer is ill-formed. A
4836 // mem-initializer-list can initialize a base class using any
4837 // name that denotes that base class type.
4838
4839 // We can store the initializers in "as-written" form and delay analysis until
4840 // instantiation if the constructor is dependent. But not for dependent
4841 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4842 bool Dependent = CurContext->isDependentContext() &&
4843 (BaseType->isDependentType() || Init->isTypeDependent());
4844
4845 SourceRange InitRange = Init->getSourceRange();
4846 if (EllipsisLoc.isValid()) {
4847 // This is a pack expansion.
4848 if (!BaseType->containsUnexpandedParameterPack()) {
4849 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4850 << SourceRange(BaseLoc, InitRange.getEnd());
4851
4852 EllipsisLoc = SourceLocation();
4853 }
4854 } else {
4855 // Check for any unexpanded parameter packs.
4856 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4857 return true;
4858
4860 return true;
4861 }
4862
4863 // Check for direct and virtual base classes.
4864 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4865 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4866 if (!Dependent) {
4867 if (declaresSameEntity(ClassDecl, BaseType->getAsCXXRecordDecl()))
4868 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4869
4870 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4871 VirtualBaseSpec);
4872
4873 // C++ [base.class.init]p2:
4874 // Unless the mem-initializer-id names a nonstatic data member of the
4875 // constructor's class or a direct or virtual base of that class, the
4876 // mem-initializer is ill-formed.
4877 if (!DirectBaseSpec && !VirtualBaseSpec) {
4878 // If the class has any dependent bases, then it's possible that
4879 // one of those types will resolve to the same type as
4880 // BaseType. Therefore, just treat this as a dependent base
4881 // class initialization. FIXME: Should we try to check the
4882 // initialization anyway? It seems odd.
4883 if (ClassDecl->hasAnyDependentBases())
4884 Dependent = true;
4885 else
4886 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4887 << BaseType << Context.getCanonicalTagType(ClassDecl)
4888 << BaseTInfo->getTypeLoc().getSourceRange();
4889 }
4890 }
4891
4892 if (Dependent) {
4894
4895 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4896 /*IsVirtual=*/false,
4897 InitRange.getBegin(), Init,
4898 InitRange.getEnd(), EllipsisLoc);
4899 }
4900
4901 // C++ [base.class.init]p2:
4902 // If a mem-initializer-id is ambiguous because it designates both
4903 // a direct non-virtual base class and an inherited virtual base
4904 // class, the mem-initializer is ill-formed.
4905 if (DirectBaseSpec && VirtualBaseSpec)
4906 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4907 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4908
4909 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4910 if (!BaseSpec)
4911 BaseSpec = VirtualBaseSpec;
4912
4913 // Initialize the base.
4914 bool InitList = true;
4915 MultiExprArg Args = Init;
4916 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4917 InitList = false;
4918 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4919 }
4920
4921 InitializedEntity BaseEntity =
4922 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4923 InitializationKind Kind =
4924 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4925 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4926 InitRange.getEnd());
4927 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4928 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4929 if (!BaseInit.isInvalid()) {
4930 // C++11 [class.base.init]p7:
4931 // The initialization of each base and member constitutes a
4932 // full-expression.
4933 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4934 /*DiscardedValue*/ false);
4935 }
4936
4937 if (BaseInit.isInvalid()) {
4938 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4939 Args, BaseType);
4940 if (BaseInit.isInvalid())
4941 return true;
4942 } else {
4943 // If we are in a dependent context, template instantiation will
4944 // perform this type-checking again. Just save the arguments that we
4945 // received in a ParenListExpr.
4946 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4947 // of the information that we have about the base
4948 // initializer. However, deconstructing the ASTs is a dicey process,
4949 // and this approach is far more likely to get the corner cases right.
4950 if (CurContext->isDependentContext())
4951 BaseInit = Init;
4952 }
4953
4954 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4955 BaseSpec->isVirtual(),
4956 InitRange.getBegin(),
4957 BaseInit.getAs<Expr>(),
4958 InitRange.getEnd(), EllipsisLoc);
4959}
4960
4961// Create a static_cast<T&&>(expr).
4962static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4963 QualType TargetType =
4964 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4966 SourceLocation ExprLoc = E->getBeginLoc();
4967 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4968 TargetType, ExprLoc);
4969
4970 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4971 SourceRange(ExprLoc, ExprLoc),
4972 E->getSourceRange()).get();
4973}
4974
4975/// ImplicitInitializerKind - How an implicit base or member initializer should
4976/// initialize its base or member.
4983
4984static bool
4986 ImplicitInitializerKind ImplicitInitKind,
4987 CXXBaseSpecifier *BaseSpec,
4988 bool IsInheritedVirtualBase,
4989 CXXCtorInitializer *&CXXBaseInit) {
4990 InitializedEntity InitEntity
4991 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4992 IsInheritedVirtualBase);
4993
4994 ExprResult BaseInit;
4995
4996 switch (ImplicitInitKind) {
4997 case IIK_Inherit:
4998 case IIK_Default: {
4999 InitializationKind InitKind
5001 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5002 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5003 break;
5004 }
5005
5006 case IIK_Move:
5007 case IIK_Copy: {
5008 bool Moving = ImplicitInitKind == IIK_Move;
5009 ParmVarDecl *Param = Constructor->getParamDecl(0);
5010 QualType ParamType = Param->getType().getNonReferenceType();
5011
5012 Expr *CopyCtorArg =
5014 SourceLocation(), Param, false,
5015 Constructor->getLocation(), ParamType,
5016 VK_LValue, nullptr);
5017
5018 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
5019
5020 // Cast to the base class to avoid ambiguities.
5021 QualType ArgTy =
5022 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
5023 ParamType.getQualifiers());
5024
5025 if (Moving) {
5026 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
5027 }
5028
5029 CXXCastPath BasePath;
5030 BasePath.push_back(BaseSpec);
5031 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
5032 CK_UncheckedDerivedToBase,
5033 Moving ? VK_XValue : VK_LValue,
5034 &BasePath).get();
5035
5036 InitializationKind InitKind
5039 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5040 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
5041 break;
5042 }
5043 }
5044
5045 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
5046 if (BaseInit.isInvalid())
5047 return true;
5048
5049 CXXBaseInit =
5050 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5051 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
5052 SourceLocation()),
5053 BaseSpec->isVirtual(),
5055 BaseInit.getAs<Expr>(),
5057 SourceLocation());
5058
5059 return false;
5060}
5061
5062static bool RefersToRValueRef(Expr *MemRef) {
5063 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5064 return Referenced->getType()->isRValueReferenceType();
5065}
5066
5067static bool
5069 ImplicitInitializerKind ImplicitInitKind,
5070 FieldDecl *Field, IndirectFieldDecl *Indirect,
5071 CXXCtorInitializer *&CXXMemberInit) {
5072 if (Field->isInvalidDecl())
5073 return true;
5074
5075 SourceLocation Loc = Constructor->getLocation();
5076
5077 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5078 bool Moving = ImplicitInitKind == IIK_Move;
5079 ParmVarDecl *Param = Constructor->getParamDecl(0);
5080 QualType ParamType = Param->getType().getNonReferenceType();
5081
5082 // Suppress copying zero-width bitfields.
5083 if (Field->isZeroLengthBitField())
5084 return false;
5085
5086 Expr *MemberExprBase =
5088 SourceLocation(), Param, false,
5089 Loc, ParamType, VK_LValue, nullptr);
5090
5091 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5092
5093 if (Moving) {
5094 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5095 }
5096
5097 // Build a reference to this field within the parameter.
5098 CXXScopeSpec SS;
5099 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5101 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5102 : cast<ValueDecl>(Field), AS_public);
5103 MemberLookup.resolveKind();
5104 ExprResult CtorArg
5105 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5106 ParamType, Loc,
5107 /*IsArrow=*/false,
5108 SS,
5109 /*TemplateKWLoc=*/SourceLocation(),
5110 /*FirstQualifierInScope=*/nullptr,
5111 MemberLookup,
5112 /*TemplateArgs=*/nullptr,
5113 /*S*/nullptr);
5114 if (CtorArg.isInvalid())
5115 return true;
5116
5117 // C++11 [class.copy]p15:
5118 // - if a member m has rvalue reference type T&&, it is direct-initialized
5119 // with static_cast<T&&>(x.m);
5120 if (RefersToRValueRef(CtorArg.get())) {
5121 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5122 }
5123
5124 InitializedEntity Entity =
5127
5128 // Direct-initialize to use the copy constructor.
5129 InitializationKind InitKind =
5131
5132 Expr *CtorArgE = CtorArg.getAs<Expr>();
5133 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5134 ExprResult MemberInit =
5135 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5136 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5137 if (MemberInit.isInvalid())
5138 return true;
5139
5140 if (Indirect)
5141 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5142 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5143 else
5144 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5145 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5146 return false;
5147 }
5148
5149 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5150 "Unhandled implicit init kind!");
5151
5152 QualType FieldBaseElementType =
5153 SemaRef.Context.getBaseElementType(Field->getType());
5154
5155 if (FieldBaseElementType->isRecordType()) {
5156 InitializedEntity InitEntity =
5159 InitializationKind InitKind =
5161
5162 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5163 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5164
5165 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5166 if (MemberInit.isInvalid())
5167 return true;
5168
5169 if (Indirect)
5170 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5171 Indirect, Loc,
5172 Loc,
5173 MemberInit.get(),
5174 Loc);
5175 else
5176 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5177 Field, Loc, Loc,
5178 MemberInit.get(),
5179 Loc);
5180 return false;
5181 }
5182
5183 if (!Field->getParent()->isUnion()) {
5184 if (FieldBaseElementType->isReferenceType()) {
5185 SemaRef.Diag(Constructor->getLocation(),
5186 diag::err_uninitialized_member_in_ctor)
5187 << (int)Constructor->isImplicit()
5188 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 0
5189 << Field->getDeclName();
5190 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5191 return true;
5192 }
5193
5194 if (FieldBaseElementType.isConstQualified()) {
5195 SemaRef.Diag(Constructor->getLocation(),
5196 diag::err_uninitialized_member_in_ctor)
5197 << (int)Constructor->isImplicit()
5198 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 1
5199 << Field->getDeclName();
5200 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5201 return true;
5202 }
5203 }
5204
5205 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5206 // ARC and Weak:
5207 // Default-initialize Objective-C pointers to NULL.
5208 CXXMemberInit
5209 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5210 Loc, Loc,
5211 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5212 Loc);
5213 return false;
5214 }
5215
5216 // Nothing to initialize.
5217 CXXMemberInit = nullptr;
5218 return false;
5219}
5220
5221namespace {
5222struct BaseAndFieldInfo {
5223 Sema &S;
5224 CXXConstructorDecl *Ctor;
5225 bool AnyErrorsInInits;
5227 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5228 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5229 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5230
5231 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5232 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5233 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5234 if (Ctor->getInheritedConstructor())
5235 IIK = IIK_Inherit;
5236 else if (Generated && Ctor->isCopyConstructor())
5237 IIK = IIK_Copy;
5238 else if (Generated && Ctor->isMoveConstructor())
5239 IIK = IIK_Move;
5240 else
5241 IIK = IIK_Default;
5242 }
5243
5244 bool isImplicitCopyOrMove() const {
5245 switch (IIK) {
5246 case IIK_Copy:
5247 case IIK_Move:
5248 return true;
5249
5250 case IIK_Default:
5251 case IIK_Inherit:
5252 return false;
5253 }
5254
5255 llvm_unreachable("Invalid ImplicitInitializerKind!");
5256 }
5257
5258 bool addFieldInitializer(CXXCtorInitializer *Init) {
5259 AllToInit.push_back(Init);
5260
5261 // Check whether this initializer makes the field "used".
5262 if (Init->getInit()->HasSideEffects(S.Context))
5263 S.UnusedPrivateFields.remove(Init->getAnyMember());
5264
5265 return false;
5266 }
5267
5268 bool isInactiveUnionMember(FieldDecl *Field) {
5269 RecordDecl *Record = Field->getParent();
5270 if (!Record->isUnion())
5271 return false;
5272
5273 if (FieldDecl *Active =
5274 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5275 return Active != Field->getCanonicalDecl();
5276
5277 // In an implicit copy or move constructor, ignore any in-class initializer.
5278 if (isImplicitCopyOrMove())
5279 return true;
5280
5281 // If there's no explicit initialization, the field is active only if it
5282 // has an in-class initializer...
5283 if (Field->hasInClassInitializer())
5284 return false;
5285 // ... or it's an anonymous struct or union whose class has an in-class
5286 // initializer.
5287 if (!Field->isAnonymousStructOrUnion())
5288 return true;
5289 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5290 return !FieldRD->hasInClassInitializer();
5291 }
5292
5293 /// Determine whether the given field is, or is within, a union member
5294 /// that is inactive (because there was an initializer given for a different
5295 /// member of the union, or because the union was not initialized at all).
5296 bool isWithinInactiveUnionMember(FieldDecl *Field,
5297 IndirectFieldDecl *Indirect) {
5298 if (!Indirect)
5299 return isInactiveUnionMember(Field);
5300
5301 for (auto *C : Indirect->chain()) {
5302 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5303 if (Field && isInactiveUnionMember(Field))
5304 return true;
5305 }
5306 return false;
5307 }
5308};
5309}
5310
5311/// Determine whether the given type is an incomplete or zero-lenfgth
5312/// array type.
5314 if (T->isIncompleteArrayType())
5315 return true;
5316
5317 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5318 if (ArrayT->isZeroSize())
5319 return true;
5320
5321 T = ArrayT->getElementType();
5322 }
5323
5324 return false;
5325}
5326
5327static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5328 FieldDecl *Field,
5329 IndirectFieldDecl *Indirect = nullptr) {
5330 if (Field->isInvalidDecl())
5331 return false;
5332
5333 // Overwhelmingly common case: we have a direct initializer for this field.
5335 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5336 return Info.addFieldInitializer(Init);
5337
5338 // C++11 [class.base.init]p8:
5339 // if the entity is a non-static data member that has a
5340 // brace-or-equal-initializer and either
5341 // -- the constructor's class is a union and no other variant member of that
5342 // union is designated by a mem-initializer-id or
5343 // -- the constructor's class is not a union, and, if the entity is a member
5344 // of an anonymous union, no other member of that union is designated by
5345 // a mem-initializer-id,
5346 // the entity is initialized as specified in [dcl.init].
5347 //
5348 // We also apply the same rules to handle anonymous structs within anonymous
5349 // unions.
5350 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5351 return false;
5352
5353 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5354 ExprResult DIE =
5355 SemaRef.BuildCXXCtorDefaultInitExpr(Info.Ctor->getLocation(), Field);
5356 if (DIE.isInvalid())
5357 return true;
5358
5360 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5361
5363 if (Indirect)
5364 Init = new (SemaRef.Context)
5365 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5366 SourceLocation(), DIE.get(), SourceLocation());
5367 else
5368 Init = new (SemaRef.Context)
5369 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5370 SourceLocation(), DIE.get(), SourceLocation());
5371 return Info.addFieldInitializer(Init);
5372 }
5373
5374 // Don't initialize incomplete or zero-length arrays.
5375 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5376 return false;
5377
5378 // Don't try to build an implicit initializer if there were semantic
5379 // errors in any of the initializers (and therefore we might be
5380 // missing some that the user actually wrote).
5381 if (Info.AnyErrorsInInits)
5382 return false;
5383
5384 CXXCtorInitializer *Init = nullptr;
5385 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5386 Indirect, Init))
5387 return true;
5388
5389 if (!Init)
5390 return false;
5391
5392 return Info.addFieldInitializer(Init);
5393}
5394
5395bool
5398 assert(Initializer->isDelegatingInitializer());
5399 Constructor->setNumCtorInitializers(1);
5400 CXXCtorInitializer **initializer =
5401 new (Context) CXXCtorInitializer*[1];
5402 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5403 Constructor->setCtorInitializers(initializer);
5404
5405 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5406 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5407 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5408 }
5409
5411
5412 DiagnoseUninitializedFields(*this, Constructor);
5413
5414 return false;
5415}
5416
5418 CXXRecordDecl *Class) {
5419 if (Class->isInvalidDecl())
5420 return nullptr;
5421 if (Class->hasIrrelevantDestructor())
5422 return nullptr;
5423
5424 // Dtor might still be missing, e.g because it's invalid.
5425 return S.LookupDestructor(Class);
5426}
5427
5429 FieldDecl *Field) {
5430 if (Field->isInvalidDecl())
5431 return;
5432
5433 // Don't destroy incomplete or zero-length arrays.
5434 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5435 return;
5436
5437 QualType FieldType = S.Context.getBaseElementType(Field->getType());
5438
5439 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5440 if (!FieldClassDecl)
5441 return;
5442
5443 // The destructor for an implicit anonymous union member is never invoked.
5444 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5445 return;
5446
5447 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5448 if (!Dtor)
5449 return;
5450
5451 S.CheckDestructorAccess(Field->getLocation(), Dtor,
5452 S.PDiag(diag::err_access_dtor_field)
5453 << Field->getDeclName() << FieldType);
5454
5455 S.MarkFunctionReferenced(Location, Dtor);
5456 S.DiagnoseUseOfDecl(Dtor, Location);
5457}
5458
5460 CXXRecordDecl *ClassDecl) {
5461 if (ClassDecl->isDependentContext())
5462 return;
5463
5464 // We only potentially invoke the destructors of potentially constructed
5465 // subobjects.
5466 bool VisitVirtualBases = !ClassDecl->isAbstract();
5467
5468 // If the destructor exists and has already been marked used in the MS ABI,
5469 // then virtual base destructors have already been checked and marked used.
5470 // Skip checking them again to avoid duplicate diagnostics.
5472 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5473 if (Dtor && Dtor->isUsed())
5474 VisitVirtualBases = false;
5475 }
5476
5478
5479 // Bases.
5480 for (const auto &Base : ClassDecl->bases()) {
5481 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5482 if (!BaseClassDecl)
5483 continue;
5484
5485 // Remember direct virtual bases.
5486 if (Base.isVirtual()) {
5487 if (!VisitVirtualBases)
5488 continue;
5489 DirectVirtualBases.insert(BaseClassDecl);
5490 }
5491
5492 auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);
5493 if (!Dtor)
5494 continue;
5495
5496 // FIXME: caret should be on the start of the class name
5497 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5498 S.PDiag(diag::err_access_dtor_base)
5499 << Base.getType() << Base.getSourceRange(),
5500 S.Context.getCanonicalTagType(ClassDecl));
5501
5502 S.MarkFunctionReferenced(Location, Dtor);
5503 S.DiagnoseUseOfDecl(Dtor, Location);
5504 }
5505
5506 if (VisitVirtualBases)
5507 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5508 &DirectVirtualBases);
5509}
5510
5512 ArrayRef<CXXCtorInitializer *> Initializers) {
5513 if (Constructor->isDependentContext()) {
5514 // Just store the initializers as written, they will be checked during
5515 // instantiation.
5516 if (!Initializers.empty()) {
5517 Constructor->setNumCtorInitializers(Initializers.size());
5518 CXXCtorInitializer **baseOrMemberInitializers =
5519 new (Context) CXXCtorInitializer*[Initializers.size()];
5520 memcpy(baseOrMemberInitializers, Initializers.data(),
5521 Initializers.size() * sizeof(CXXCtorInitializer*));
5522 Constructor->setCtorInitializers(baseOrMemberInitializers);
5523 }
5524
5525 // Let template instantiation know whether we had errors.
5526 if (AnyErrors)
5527 Constructor->setInvalidDecl();
5528
5529 return false;
5530 }
5531
5532 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5533
5534 // We need to build the initializer AST according to order of construction
5535 // and not what user specified in the Initializers list.
5536 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5537 if (!ClassDecl)
5538 return true;
5539
5540 bool HadError = false;
5541
5542 for (CXXCtorInitializer *Member : Initializers) {
5543 if (Member->isBaseInitializer())
5544 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5545 Member;
5546 else {
5547 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5548
5549 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5550 for (auto *C : F->chain()) {
5551 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5552 if (FD && FD->getParent()->isUnion())
5553 Info.ActiveUnionMember.insert(std::make_pair(
5555 }
5556 } else if (FieldDecl *FD = Member->getMember()) {
5557 if (FD->getParent()->isUnion())
5558 Info.ActiveUnionMember.insert(std::make_pair(
5560 }
5561 }
5562 }
5563
5564 // Keep track of the direct virtual bases.
5566 for (auto &I : ClassDecl->bases()) {
5567 if (I.isVirtual())
5568 DirectVBases.insert(&I);
5569 }
5570
5571 // Push virtual bases before others.
5572 for (auto &VBase : ClassDecl->vbases()) {
5573 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5574 VBase.getType()->getAsCanonical<RecordType>())) {
5575 // [class.base.init]p7, per DR257:
5576 // A mem-initializer where the mem-initializer-id names a virtual base
5577 // class is ignored during execution of a constructor of any class that
5578 // is not the most derived class.
5579 if (ClassDecl->isAbstract()) {
5580 // FIXME: Provide a fixit to remove the base specifier. This requires
5581 // tracking the location of the associated comma for a base specifier.
5582 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5583 << VBase.getType() << ClassDecl;
5584 DiagnoseAbstractType(ClassDecl);
5585 }
5586
5587 Info.AllToInit.push_back(Value);
5588 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5589 // [class.base.init]p8, per DR257:
5590 // If a given [...] base class is not named by a mem-initializer-id
5591 // [...] and the entity is not a virtual base class of an abstract
5592 // class, then [...] the entity is default-initialized.
5593 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5594 CXXCtorInitializer *CXXBaseInit;
5595 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5596 &VBase, IsInheritedVirtualBase,
5597 CXXBaseInit)) {
5598 HadError = true;
5599 continue;
5600 }
5601
5602 Info.AllToInit.push_back(CXXBaseInit);
5603 }
5604 }
5605
5606 // Non-virtual bases.
5607 for (auto &Base : ClassDecl->bases()) {
5608 // Virtuals are in the virtual base list and already constructed.
5609 if (Base.isVirtual())
5610 continue;
5611
5612 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5613 Base.getType()->getAsCanonical<RecordType>())) {
5614 Info.AllToInit.push_back(Value);
5615 } else if (!AnyErrors) {
5616 CXXCtorInitializer *CXXBaseInit;
5617 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5618 &Base, /*IsInheritedVirtualBase=*/false,
5619 CXXBaseInit)) {
5620 HadError = true;
5621 continue;
5622 }
5623
5624 Info.AllToInit.push_back(CXXBaseInit);
5625 }
5626 }
5627
5628 // Fields.
5629 for (auto *Mem : ClassDecl->decls()) {
5630 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5631 // C++ [class.bit]p2:
5632 // A declaration for a bit-field that omits the identifier declares an
5633 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5634 // initialized.
5635 if (F->isUnnamedBitField())
5636 continue;
5637
5638 // If we're not generating the implicit copy/move constructor, then we'll
5639 // handle anonymous struct/union fields based on their individual
5640 // indirect fields.
5641 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5642 continue;
5643
5644 if (CollectFieldInitializer(*this, Info, F))
5645 HadError = true;
5646 continue;
5647 }
5648
5649 // Beyond this point, we only consider default initialization.
5650 if (Info.isImplicitCopyOrMove())
5651 continue;
5652
5653 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5654 if (F->getType()->isIncompleteArrayType()) {
5655 assert(ClassDecl->hasFlexibleArrayMember() &&
5656 "Incomplete array type is not valid");
5657 continue;
5658 }
5659
5660 // Initialize each field of an anonymous struct individually.
5661 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5662 HadError = true;
5663
5664 continue;
5665 }
5666 }
5667
5668 unsigned NumInitializers = Info.AllToInit.size();
5669 if (NumInitializers > 0) {
5670 Constructor->setNumCtorInitializers(NumInitializers);
5671 CXXCtorInitializer **baseOrMemberInitializers =
5672 new (Context) CXXCtorInitializer*[NumInitializers];
5673 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5674 NumInitializers * sizeof(CXXCtorInitializer*));
5675 Constructor->setCtorInitializers(baseOrMemberInitializers);
5676
5677 SourceLocation Location = Constructor->getLocation();
5678
5679 // Constructors implicitly reference the base and member
5680 // destructors.
5681
5682 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5683 FieldDecl *Field = Initializer->getAnyMember();
5684 if (!Field)
5685 continue;
5686
5687 // C++ [class.base.init]p12:
5688 // In a non-delegating constructor, the destructor for each
5689 // potentially constructed subobject of class type is potentially
5690 // invoked.
5691 MarkFieldDestructorReferenced(*this, Location, Field);
5692 }
5693
5694 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5695 }
5696
5697 return HadError;
5698}
5699
5701 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5702 const RecordDecl *RD = RT->getDecl();
5703 if (RD->isAnonymousStructOrUnion()) {
5704 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5705 PopulateKeysForFields(Field, IdealInits);
5706 return;
5707 }
5708 }
5709 IdealInits.push_back(Field->getCanonicalDecl());
5710}
5711
5712static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5713 return Context.getCanonicalType(BaseType).getTypePtr();
5714}
5715
5716static const void *GetKeyForMember(ASTContext &Context,
5718 if (!Member->isAnyMemberInitializer())
5719 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5720
5721 return Member->getAnyMember()->getCanonicalDecl();
5722}
5723
5726 const CXXCtorInitializer *Current) {
5727 if (Previous->isAnyMemberInitializer())
5728 Diag << 0 << Previous->getAnyMember();
5729 else
5730 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5731
5732 if (Current->isAnyMemberInitializer())
5733 Diag << 0 << Current->getAnyMember();
5734 else
5735 Diag << 1 << Current->getTypeSourceInfo()->getType();
5736}
5737
5739 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5741 if (Constructor->getDeclContext()->isDependentContext())
5742 return;
5743
5744 // Don't check initializers order unless the warning is enabled at the
5745 // location of at least one initializer.
5746 bool ShouldCheckOrder = false;
5747 for (const CXXCtorInitializer *Init : Inits) {
5748 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5749 Init->getSourceLocation())) {
5750 ShouldCheckOrder = true;
5751 break;
5752 }
5753 }
5754 if (!ShouldCheckOrder)
5755 return;
5756
5757 // Build the list of bases and members in the order that they'll
5758 // actually be initialized. The explicit initializers should be in
5759 // this same order but may be missing things.
5760 SmallVector<const void*, 32> IdealInitKeys;
5761
5762 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5763
5764 // 1. Virtual bases.
5765 for (const auto &VBase : ClassDecl->vbases())
5766 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5767
5768 // 2. Non-virtual bases.
5769 for (const auto &Base : ClassDecl->bases()) {
5770 if (Base.isVirtual())
5771 continue;
5772 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5773 }
5774
5775 // 3. Direct fields.
5776 for (auto *Field : ClassDecl->fields()) {
5777 if (Field->isUnnamedBitField())
5778 continue;
5779
5780 PopulateKeysForFields(Field, IdealInitKeys);
5781 }
5782
5783 unsigned NumIdealInits = IdealInitKeys.size();
5784 unsigned IdealIndex = 0;
5785
5786 // Track initializers that are in an incorrect order for either a warning or
5787 // note if multiple ones occur.
5788 SmallVector<unsigned> WarnIndexes;
5789 // Correlates the index of an initializer in the init-list to the index of
5790 // the field/base in the class.
5791 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5792
5793 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5794 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5795
5796 // Scan forward to try to find this initializer in the idealized
5797 // initializers list.
5798 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5799 if (InitKey == IdealInitKeys[IdealIndex])
5800 break;
5801
5802 // If we didn't find this initializer, it must be because we
5803 // scanned past it on a previous iteration. That can only
5804 // happen if we're out of order; emit a warning.
5805 if (IdealIndex == NumIdealInits && InitIndex) {
5806 WarnIndexes.push_back(InitIndex);
5807
5808 // Move back to the initializer's location in the ideal list.
5809 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5810 if (InitKey == IdealInitKeys[IdealIndex])
5811 break;
5812
5813 assert(IdealIndex < NumIdealInits &&
5814 "initializer not found in initializer list");
5815 }
5816 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5817 }
5818
5819 if (WarnIndexes.empty())
5820 return;
5821
5822 // Sort based on the ideal order, first in the pair.
5823 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5824
5825 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5826 // emit the diagnostic before we can try adding notes.
5827 {
5829 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5830 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5831 : diag::warn_some_initializers_out_of_order);
5832
5833 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5834 if (CorrelatedInitOrder[I].second == I)
5835 continue;
5836 // Ideally we would be using InsertFromRange here, but clang doesn't
5837 // appear to handle InsertFromRange correctly when the source range is
5838 // modified by another fix-it.
5840 Inits[I]->getSourceRange(),
5843 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5844 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5845 }
5846
5847 // If there is only 1 item out of order, the warning expects the name and
5848 // type of each being added to it.
5849 if (WarnIndexes.size() == 1) {
5850 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5851 Inits[WarnIndexes.front()]);
5852 return;
5853 }
5854 }
5855 // More than 1 item to warn, create notes letting the user know which ones
5856 // are bad.
5857 for (unsigned WarnIndex : WarnIndexes) {
5858 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5859 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5860 diag::note_initializer_out_of_order);
5861 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5862 D << PrevInit->getSourceRange();
5863 }
5864}
5865
5866namespace {
5867bool CheckRedundantInit(Sema &S,
5868 CXXCtorInitializer *Init,
5869 CXXCtorInitializer *&PrevInit) {
5870 if (!PrevInit) {
5871 PrevInit = Init;
5872 return false;
5873 }
5874
5875 if (FieldDecl *Field = Init->getAnyMember())
5876 S.Diag(Init->getSourceLocation(),
5877 diag::err_multiple_mem_initialization)
5878 << Field->getDeclName()
5879 << Init->getSourceRange();
5880 else {
5881 const Type *BaseClass = Init->getBaseClass();
5882 assert(BaseClass && "neither field nor base");
5883 S.Diag(Init->getSourceLocation(),
5884 diag::err_multiple_base_initialization)
5885 << QualType(BaseClass, 0)
5886 << Init->getSourceRange();
5887 }
5888 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5889 << 0 << PrevInit->getSourceRange();
5890
5891 return true;
5892}
5893
5894typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5895typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5896
5897bool CheckRedundantUnionInit(Sema &S,
5898 CXXCtorInitializer *Init,
5899 RedundantUnionMap &Unions) {
5900 FieldDecl *Field = Init->getAnyMember();
5901 RecordDecl *Parent = Field->getParent();
5902 NamedDecl *Child = Field;
5903
5904 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5905 if (Parent->isUnion()) {
5906 UnionEntry &En = Unions[Parent];
5907 if (En.first && En.first != Child) {
5908 S.Diag(Init->getSourceLocation(),
5909 diag::err_multiple_mem_union_initialization)
5910 << Field->getDeclName()
5911 << Init->getSourceRange();
5912 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5913 << 0 << En.second->getSourceRange();
5914 return true;
5915 }
5916 if (!En.first) {
5917 En.first = Child;
5918 En.second = Init;
5919 }
5920 if (!Parent->isAnonymousStructOrUnion())
5921 return false;
5922 }
5923
5924 Child = Parent;
5925 Parent = cast<RecordDecl>(Parent->getDeclContext());
5926 }
5927
5928 return false;
5929}
5930} // namespace
5931
5932void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5933 SourceLocation ColonLoc,
5935 bool AnyErrors) {
5936 if (!ConstructorDecl)
5937 return;
5938
5939 AdjustDeclIfTemplate(ConstructorDecl);
5940
5942 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5943
5944 if (!Constructor) {
5945 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5946 return;
5947 }
5948
5949 // Mapping for the duplicate initializers check.
5950 // For member initializers, this is keyed with a FieldDecl*.
5951 // For base initializers, this is keyed with a Type*.
5952 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5953
5954 // Mapping for the inconsistent anonymous-union initializers check.
5955 RedundantUnionMap MemberUnions;
5956
5957 bool HadError = false;
5958 for (unsigned i = 0; i < MemInits.size(); i++) {
5959 CXXCtorInitializer *Init = MemInits[i];
5960
5961 // Set the source order index.
5962 Init->setSourceOrder(i);
5963
5964 if (Init->isAnyMemberInitializer()) {
5965 const void *Key = GetKeyForMember(Context, Init);
5966 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5967 CheckRedundantUnionInit(*this, Init, MemberUnions))
5968 HadError = true;
5969 } else if (Init->isBaseInitializer()) {
5970 const void *Key = GetKeyForMember(Context, Init);
5971 if (CheckRedundantInit(*this, Init, Members[Key]))
5972 HadError = true;
5973 } else {
5974 assert(Init->isDelegatingInitializer());
5975 // This must be the only initializer
5976 if (MemInits.size() != 1) {
5977 Diag(Init->getSourceLocation(),
5978 diag::err_delegating_initializer_alone)
5979 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5980 // We will treat this as being the only initializer.
5981 }
5983 // Return immediately as the initializer is set.
5984 return;
5985 }
5986 }
5987
5988 if (HadError)
5989 return;
5990
5992
5993 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5994
5995 DiagnoseUninitializedFields(*this, Constructor);
5996}
5997
5999 CXXRecordDecl *ClassDecl) {
6000 // Ignore dependent contexts. Also ignore unions, since their members never
6001 // have destructors implicitly called.
6002 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
6003 return;
6004
6005 // FIXME: all the access-control diagnostics are positioned on the
6006 // field/base declaration. That's probably good; that said, the
6007 // user might reasonably want to know why the destructor is being
6008 // emitted, and we currently don't say.
6009
6010 // Non-static data members.
6011 for (auto *Field : ClassDecl->fields()) {
6012 MarkFieldDestructorReferenced(*this, Location, Field);
6013 }
6014
6015 MarkBaseDestructorsReferenced(*this, Location, ClassDecl);
6016}
6017
6019 SourceLocation Location, CXXRecordDecl *ClassDecl,
6020 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
6021 // Virtual bases.
6022 for (const auto &VBase : ClassDecl->vbases()) {
6023 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
6024 if (!BaseClassDecl)
6025 continue;
6026
6027 // Ignore already visited direct virtual bases.
6028 if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))
6029 continue;
6030
6031 auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);
6032 if (!Dtor)
6033 continue;
6034
6035 CanQualType CT = Context.getCanonicalTagType(ClassDecl);
6036 if (CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
6037 PDiag(diag::err_access_dtor_vbase)
6038 << CT << VBase.getType(),
6039 CT) == AR_accessible) {
6041 CT, VBase.getType(), diag::err_access_dtor_vbase, 0,
6042 ClassDecl->getLocation(), SourceRange(), DeclarationName(), nullptr);
6043 }
6044
6045 MarkFunctionReferenced(Location, Dtor);
6046 DiagnoseUseOfDecl(Dtor, Location);
6047 }
6048}
6049
6051 if (!CDtorDecl)
6052 return;
6053
6055 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
6056 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6057 !ClassDecl || ClassDecl->isInvalidDecl()) {
6058 return;
6059 }
6060 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6061 DiagnoseUninitializedFields(*this, Constructor);
6062 }
6063}
6064
6066 if (!getLangOpts().CPlusPlus)
6067 return false;
6068
6069 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6070 if (!RD)
6071 return false;
6072
6073 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6074 // class template specialization here, but doing so breaks a lot of code.
6075
6076 // We can't answer whether something is abstract until it has a
6077 // definition. If it's currently being defined, we'll walk back
6078 // over all the declarations when we have a full definition.
6079 const CXXRecordDecl *Def = RD->getDefinition();
6080 if (!Def || Def->isBeingDefined())
6081 return false;
6082
6083 return RD->isAbstract();
6084}
6085
6087 TypeDiagnoser &Diagnoser) {
6088 if (!isAbstractType(Loc, T))
6089 return false;
6090
6091 T = Context.getBaseElementType(T);
6092 Diagnoser.diagnose(*this, Loc, T);
6093 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6094 return true;
6095}
6096
6098 // Check if we've already emitted the list of pure virtual functions
6099 // for this class.
6101 return;
6102
6103 // If the diagnostic is suppressed, don't emit the notes. We're only
6104 // going to emit them once, so try to attach them to a diagnostic we're
6105 // actually going to show.
6106 if (Diags.isLastDiagnosticIgnored())
6107 return;
6108
6109 CXXFinalOverriderMap FinalOverriders;
6110 RD->getFinalOverriders(FinalOverriders);
6111
6112 // Keep a set of seen pure methods so we won't diagnose the same method
6113 // more than once.
6115
6116 for (const auto &M : FinalOverriders) {
6117 for (const auto &SO : M.second) {
6118 // C++ [class.abstract]p4:
6119 // A class is abstract if it contains or inherits at least one
6120 // pure virtual function for which the final overrider is pure
6121 // virtual.
6122
6123 if (SO.second.size() != 1)
6124 continue;
6125 const CXXMethodDecl *Method = SO.second.front().Method;
6126
6127 if (!Method->isPureVirtual())
6128 continue;
6129
6130 if (!SeenPureMethods.insert(Method).second)
6131 continue;
6132
6133 Diag(Method->getLocation(), diag::note_pure_virtual_function)
6134 << Method->getDeclName() << RD->getDeclName();
6135 }
6136 }
6137
6140 PureVirtualClassDiagSet->insert(RD);
6141}
6142
6143namespace {
6144struct AbstractUsageInfo {
6145 Sema &S;
6147 CanQualType AbstractType;
6148 bool Invalid;
6149
6150 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6151 : S(S), Record(Record),
6152 AbstractType(S.Context.getCanonicalTagType(Record)), Invalid(false) {}
6153
6154 void DiagnoseAbstractType() {
6155 if (Invalid) return;
6157 Invalid = true;
6158 }
6159
6160 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6161};
6162
6163struct CheckAbstractUsage {
6164 AbstractUsageInfo &Info;
6165 const NamedDecl *Ctx;
6166
6167 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6168 : Info(Info), Ctx(Ctx) {}
6169
6170 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6171 switch (TL.getTypeLocClass()) {
6172#define ABSTRACT_TYPELOC(CLASS, PARENT)
6173#define TYPELOC(CLASS, PARENT) \
6174 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6175#include "clang/AST/TypeLocNodes.def"
6176 }
6177 }
6178
6179 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6181 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6182 if (!TL.getParam(I))
6183 continue;
6184
6185 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6186 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6187 }
6188 }
6189
6190 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6192 }
6193
6194 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6195 // Visit the type parameters from a permissive context.
6196 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6197 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6199 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6200 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6201 // TODO: other template argument types?
6202 }
6203 }
6204
6205 // Visit pointee types from a permissive context.
6206#define CheckPolymorphic(Type) \
6207 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6208 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6209 }
6215
6216 /// Handle all the types we haven't given a more specific
6217 /// implementation for above.
6218 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6219 // Every other kind of type that we haven't called out already
6220 // that has an inner type is either (1) sugar or (2) contains that
6221 // inner type in some way as a subobject.
6222 if (TypeLoc Next = TL.getNextTypeLoc())
6223 return Visit(Next, Sel);
6224
6225 // If there's no inner type and we're in a permissive context,
6226 // don't diagnose.
6227 if (Sel == Sema::AbstractNone) return;
6228
6229 // Check whether the type matches the abstract type.
6230 QualType T = TL.getType();
6231 if (T->isArrayType()) {
6233 T = Info.S.Context.getBaseElementType(T);
6234 }
6235 CanQualType CT = T->getCanonicalTypeUnqualified();
6236 if (CT != Info.AbstractType) return;
6237
6238 // It matched; do some magic.
6239 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6240 if (Sel == Sema::AbstractArrayType) {
6241 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6242 << T << TL.getSourceRange();
6243 } else {
6244 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6245 << Sel << T << TL.getSourceRange();
6246 }
6247 Info.DiagnoseAbstractType();
6248 }
6249};
6250
6251void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6253 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6254}
6255
6256}
6257
6258/// Check for invalid uses of an abstract type in a function declaration.
6259static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6260 FunctionDecl *FD) {
6261 // Only definitions are required to refer to complete and
6262 // non-abstract types.
6264 return;
6265
6266 // For safety's sake, just ignore it if we don't have type source
6267 // information. This should never happen for non-implicit methods,
6268 // but...
6269 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6270 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6271}
6272
6273/// Check for invalid uses of an abstract type in a variable0 declaration.
6274static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6275 VarDecl *VD) {
6276 // No need to do the check on definitions, which require that
6277 // the type is complete.
6279 return;
6280
6281 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6283}
6284
6285/// Check for invalid uses of an abstract type within a class definition.
6286static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6287 CXXRecordDecl *RD) {
6288 for (auto *D : RD->decls()) {
6289 if (D->isImplicit()) continue;
6290
6291 // Step through friends to the befriended declaration.
6292 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6293 D = FD->getFriendDecl();
6294 if (!D) continue;
6295 }
6296
6297 // Functions and function templates.
6298 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6299 CheckAbstractClassUsage(Info, FD);
6300 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6301 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6302
6303 // Fields and static variables.
6304 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6305 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6306 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6307 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6308 CheckAbstractClassUsage(Info, VD);
6309 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6310 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6311
6312 // Nested classes and class templates.
6313 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6314 CheckAbstractClassUsage(Info, RD);
6315 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6316 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6317 }
6318 }
6319}
6320
6322 Attr *ClassAttr = getDLLAttr(Class);
6323 if (!ClassAttr)
6324 return;
6325
6326 assert(ClassAttr->getKind() == attr::DLLExport);
6327
6328 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6329
6331 // Don't go any further if this is just an explicit instantiation
6332 // declaration.
6333 return;
6334
6335 // Add a context note to explain how we got to any diagnostics produced below.
6336 struct MarkingClassDllexported {
6337 Sema &S;
6338 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6339 SourceLocation AttrLoc)
6340 : S(S) {
6343 Ctx.PointOfInstantiation = AttrLoc;
6344 Ctx.Entity = Class;
6346 }
6347 ~MarkingClassDllexported() {
6349 }
6350 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6351
6352 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6353 S.MarkVTableUsed(Class->getLocation(), Class, true);
6354
6355 for (Decl *Member : Class->decls()) {
6356 // Skip members that were not marked exported.
6357 if (!Member->hasAttr<DLLExportAttr>())
6358 continue;
6359
6360 // Defined static variables that are members of an exported base
6361 // class must be marked export too.
6362 auto *VD = dyn_cast<VarDecl>(Member);
6363 if (VD && VD->getStorageClass() == SC_Static &&
6365 S.MarkVariableReferenced(VD->getLocation(), VD);
6366
6367 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6368 if (!MD)
6369 continue;
6370
6371 if (MD->isUserProvided()) {
6372 // Instantiate non-default class member functions ...
6373
6374 // .. except for certain kinds of template specializations.
6375 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6376 continue;
6377
6378 // If this is an MS ABI dllexport default constructor, instantiate any
6379 // default arguments.
6381 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6382 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6384 CD->getAttr<DLLExportAttr>()->getLocation(), CD);
6385 }
6386 }
6387
6388 S.MarkFunctionReferenced(Class->getLocation(), MD);
6389
6390 // The function will be passed to the consumer when its definition is
6391 // encountered.
6392 } else if (MD->isExplicitlyDefaulted()) {
6393 // Synthesize and instantiate explicitly defaulted methods.
6394 S.MarkFunctionReferenced(Class->getLocation(), MD);
6395
6397 // Except for explicit instantiation defs, we will not see the
6398 // definition again later, so pass it to the consumer now.
6400 }
6401 } else if (!MD->isTrivial() ||
6402 MD->isCopyAssignmentOperator() ||
6403 MD->isMoveAssignmentOperator()) {
6404 // Synthesize and instantiate non-trivial implicit methods, and the copy
6405 // and move assignment operators. The latter are exported even if they
6406 // are trivial, because the address of an operator can be taken and
6407 // should compare equal across libraries.
6408 S.MarkFunctionReferenced(Class->getLocation(), MD);
6409
6410 // There is no later point when we will see the definition of this
6411 // function, so pass it to the consumer now.
6413 }
6414 }
6415}
6416
6418 CXXRecordDecl *Class) {
6419 // Only the MS ABI has default constructor closures, so we don't need to do
6420 // this semantic checking anywhere else.
6422 return;
6423
6424 if (Class->isInvalidDecl())
6425 return;
6426
6427 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6428 for (Decl *Member : Class->decls()) {
6429 // Nested classes finish delayed default argument parsing with the outermost
6430 // class, so check each nested definition here.
6431 if (auto *NestedClass = dyn_cast<CXXRecordDecl>(Member)) {
6432 if (NestedClass->isThisDeclarationADefinition())
6434 continue;
6435 }
6436
6437 // Look for exported default constructors.
6438 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6439 if (!CD || !CD->isDefaultConstructor())
6440 continue;
6441 auto *Attr = CD->getAttr<DLLExportAttr>();
6442 if (!Attr)
6443 continue;
6444
6445 // If the class is non-dependent, mark the default arguments as ODR-used so
6446 // that we can properly codegen the constructor closure.
6447 if (!Class->isDependentContext()) {
6450 }
6451
6452 if (LastExportedDefaultCtor) {
6453 S.Diag(LastExportedDefaultCtor->getLocation(),
6454 diag::err_attribute_dll_ambiguous_default_ctor)
6455 << Class;
6456 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6457 << CD->getDeclName();
6458 return;
6459 }
6460 LastExportedDefaultCtor = CD;
6461 }
6462}
6463
6465 CXXRecordDecl *Class) {
6466 bool ErrorReported = false;
6467 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6468 ClassTemplateDecl *TD) {
6469 if (ErrorReported)
6470 return;
6471 S.Diag(TD->getLocation(),
6472 diag::err_cuda_device_builtin_surftex_cls_template)
6473 << /*surface*/ 0 << TD;
6474 ErrorReported = true;
6475 };
6476
6477 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6478 if (!TD) {
6479 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6480 if (!SD) {
6481 S.Diag(Class->getLocation(),
6482 diag::err_cuda_device_builtin_surftex_ref_decl)
6483 << /*surface*/ 0 << Class;
6484 S.Diag(Class->getLocation(),
6485 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6486 << Class;
6487 return;
6488 }
6489 TD = SD->getSpecializedTemplate();
6490 }
6491
6493 unsigned N = Params->size();
6494
6495 if (N != 2) {
6496 reportIllegalClassTemplate(S, TD);
6497 S.Diag(TD->getLocation(),
6498 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6499 << TD << 2;
6500 }
6501 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6502 reportIllegalClassTemplate(S, TD);
6503 S.Diag(TD->getLocation(),
6504 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6505 << TD << /*1st*/ 0 << /*type*/ 0;
6506 }
6507 if (N > 1) {
6508 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6509 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6510 reportIllegalClassTemplate(S, TD);
6511 S.Diag(TD->getLocation(),
6512 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6513 << TD << /*2nd*/ 1 << /*integer*/ 1;
6514 }
6515 }
6516}
6517
6519 CXXRecordDecl *Class) {
6520 bool ErrorReported = false;
6521 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6522 ClassTemplateDecl *TD) {
6523 if (ErrorReported)
6524 return;
6525 S.Diag(TD->getLocation(),
6526 diag::err_cuda_device_builtin_surftex_cls_template)
6527 << /*texture*/ 1 << TD;
6528 ErrorReported = true;
6529 };
6530
6531 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6532 if (!TD) {
6533 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6534 if (!SD) {
6535 S.Diag(Class->getLocation(),
6536 diag::err_cuda_device_builtin_surftex_ref_decl)
6537 << /*texture*/ 1 << Class;
6538 S.Diag(Class->getLocation(),
6539 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6540 << Class;
6541 return;
6542 }
6543 TD = SD->getSpecializedTemplate();
6544 }
6545
6547 unsigned N = Params->size();
6548
6549 if (N != 3) {
6550 reportIllegalClassTemplate(S, TD);
6551 S.Diag(TD->getLocation(),
6552 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6553 << TD << 3;
6554 }
6555 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6556 reportIllegalClassTemplate(S, TD);
6557 S.Diag(TD->getLocation(),
6558 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6559 << TD << /*1st*/ 0 << /*type*/ 0;
6560 }
6561 if (N > 1) {
6562 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6563 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6564 reportIllegalClassTemplate(S, TD);
6565 S.Diag(TD->getLocation(),
6566 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6567 << TD << /*2nd*/ 1 << /*integer*/ 1;
6568 }
6569 }
6570 if (N > 2) {
6571 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6572 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6573 reportIllegalClassTemplate(S, TD);
6574 S.Diag(TD->getLocation(),
6575 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6576 << TD << /*3rd*/ 2 << /*integer*/ 1;
6577 }
6578 }
6579}
6580
6582 // Mark any compiler-generated routines with the implicit code_seg attribute.
6583 for (auto *Method : Class->methods()) {
6584 if (Method->isUserProvided())
6585 continue;
6586 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6587 Method->addAttr(A);
6588 }
6589}
6590
6592 Attr *ClassAttr = getDLLAttr(Class);
6593
6594 // MSVC inherits DLL attributes to partial class template specializations.
6595 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6596 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6597 if (Attr *TemplateAttr =
6598 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6599 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6600 A->setInherited(true);
6601 ClassAttr = A;
6602 }
6603 }
6604 }
6605
6606 if (!ClassAttr)
6607 return;
6608
6609 // MSVC allows imported or exported template classes that have UniqueExternal
6610 // linkage. This occurs when the template class has been instantiated with
6611 // a template parameter which itself has internal linkage.
6612 // We drop the attribute to avoid exporting or importing any members.
6613 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6614 Context.getTargetInfo().getTriple().isPS()) &&
6615 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6616 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6617 return;
6618 }
6619
6620 if (!Class->isExternallyVisible()) {
6621 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6622 << Class << ClassAttr;
6623 return;
6624 }
6625
6626 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6627 !ClassAttr->isInherited()) {
6628 // Diagnose dll attributes on members of class with dll attribute.
6629 for (Decl *Member : Class->decls()) {
6631 continue;
6632 InheritableAttr *MemberAttr = getDLLAttr(Member);
6633 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6634 continue;
6635
6636 Diag(MemberAttr->getLocation(),
6637 diag::err_attribute_dll_member_of_dll_class)
6638 << MemberAttr << ClassAttr;
6639 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6640 Member->setInvalidDecl();
6641 }
6642 }
6643
6644 if (Class->getDescribedClassTemplate())
6645 // Don't inherit dll attribute until the template is instantiated.
6646 return;
6647
6648 // The class is either imported or exported.
6649 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6650
6651 // Check if this was a dllimport attribute propagated from a derived class to
6652 // a base class template specialization. We don't apply these attributes to
6653 // static data members.
6654 const bool PropagatedImport =
6655 !ClassExported &&
6656 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6657
6658 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6659
6660 // Ignore explicit dllexport on explicit class template instantiation
6661 // declarations, except in MinGW mode.
6662 if (ClassExported && !ClassAttr->isInherited() &&
6664 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6665 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6666 Class->addAttr(DLLExportOnDeclAttr::Create(Context, DEA->getLoc()));
6667 Class->dropAttr<DLLExportAttr>();
6668 }
6669 return;
6670 }
6671
6672 // Force declaration of implicit members so they can inherit the attribute.
6674
6675 // Inherited constructors are created lazily; force their creation now so the
6676 // loop below can propagate the DLL attribute to them.
6677 if (ClassExported && getLangOpts().DllExportInlines) {
6679 for (Decl *D : Class->decls())
6680 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(D))
6681 Shadows.push_back(S);
6682 for (ConstructorUsingShadowDecl *S : Shadows) {
6683 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(S->getTargetDecl());
6684 if (!BC || BC->isDeleted())
6685 continue;
6686 // Skip constructors whose requires clause is not satisfied.
6687 // Normally overload resolution filters these, but we are bypassing
6688 // it to eagerly create inherited constructors for dllexport.
6689 if (BC->getTrailingRequiresClause()) {
6690 ConstraintSatisfaction Satisfaction;
6691 if (CheckFunctionConstraints(BC, Satisfaction) ||
6692 !Satisfaction.IsSatisfied)
6693 continue;
6694 }
6695 findInheritingConstructor(Class->getLocation(), BC, S);
6696 }
6697 }
6698
6699 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6700 // seem to be true in practice?
6701
6702 for (Decl *Member : Class->decls()) {
6703 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6704 continue;
6705
6706 VarDecl *VD = dyn_cast<VarDecl>(Member);
6707 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6708
6709 // Only methods and static fields inherit the attributes.
6710 if (!VD && !MD)
6711 continue;
6712
6713 if (MD) {
6714 // Don't process deleted methods.
6715 if (MD->isDeleted())
6716 continue;
6717
6718 if (ClassExported && getLangOpts().DllExportInlines) {
6719 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD);
6720 if (CD && CD->getInheritedConstructor()) {
6721 // Inherited constructors already had their base constructor's
6722 // constraints checked before creation via
6723 // findInheritingConstructor, so only ABI-compatibility checks
6724 // are needed here.
6725 //
6726 // Don't export inherited constructors whose parameters prevent
6727 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6728 // CodeGen) returns false, Clang inlines the constructor body
6729 // instead of emitting a forwarding thunk, producing code that
6730 // is not ABI-compatible with MSVC. Suppress the export and warn
6731 // so the user gets a linker error rather than a silent runtime
6732 // mismatch.
6733 if (CD->isVariadic()) {
6734 Diag(CD->getLocation(),
6735 diag::warn_dllexport_inherited_ctor_unsupported)
6736 << /*variadic=*/0;
6737 continue;
6738 }
6739 if (Context.getTargetInfo()
6740 .getCXXABI()
6741 .areArgsDestroyedLeftToRightInCallee()) {
6742 bool HasCalleeCleanupParam = false;
6743 for (const ParmVarDecl *P : CD->parameters())
6744 if (P->needsDestruction(Context)) {
6745 HasCalleeCleanupParam = true;
6746 break;
6747 }
6748 if (HasCalleeCleanupParam) {
6749 Diag(CD->getLocation(),
6750 diag::warn_dllexport_inherited_ctor_unsupported)
6751 << /*callee-cleanup=*/1;
6752 continue;
6753 }
6754 }
6755 } else if (MD->getTrailingRequiresClause()) {
6756 // Don't export methods whose requires clause is not satisfied.
6757 // For class template specializations, member constraints may
6758 // depend on template arguments and an unsatisfied constraint
6759 // means the member should not be available in this
6760 // specialization.
6761 ConstraintSatisfaction Satisfaction;
6762 if (CheckFunctionConstraints(MD, Satisfaction) ||
6763 !Satisfaction.IsSatisfied)
6764 continue;
6765 }
6766 }
6767
6768 if (MD->isInlined()) {
6769 // MinGW does not import or export inline methods. But do it for
6770 // template instantiations and inherited constructors (which are
6771 // marked inline but must be exported to match MSVC behavior).
6772 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6775 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6776 !CD || !CD->getInheritedConstructor())
6777 continue;
6778 }
6779
6780 // MSVC versions before 2015 don't export the move assignment operators
6781 // and move constructor, so don't attempt to import/export them if
6782 // we have a definition.
6783 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6784 if ((MD->isMoveAssignmentOperator() ||
6785 (Ctor && Ctor->isMoveConstructor())) &&
6786 getLangOpts().isCompatibleWithMSVC() &&
6787 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6788 continue;
6789
6790 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6791 // operator is exported anyway.
6792 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6793 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6794 continue;
6795 }
6796 }
6797
6798 // Don't apply dllimport attributes to static data members of class template
6799 // instantiations when the attribute is propagated from a derived class.
6800 if (VD && PropagatedImport)
6801 continue;
6802
6804 continue;
6805
6806 if (!getDLLAttr(Member)) {
6807 InheritableAttr *NewAttr = nullptr;
6808
6809 // Do not export/import inline function when -fno-dllexport-inlines is
6810 // passed. But add attribute for later local static var check.
6811 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6814 if (ClassExported) {
6815 NewAttr = ::new (getASTContext())
6816 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6817 } else {
6818 NewAttr = ::new (getASTContext())
6819 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6820 }
6821 } else {
6822 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6823 }
6824
6825 NewAttr->setInherited(true);
6826 Member->addAttr(NewAttr);
6827
6828 if (MD) {
6829 // Propagate DLLAttr to friend re-declarations of MD that have already
6830 // been constructed.
6831 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6832 FD = FD->getPreviousDecl()) {
6834 continue;
6835 assert(!getDLLAttr(FD) &&
6836 "friend re-decl should not already have a DLLAttr");
6837 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6838 NewAttr->setInherited(true);
6839 FD->addAttr(NewAttr);
6840 }
6841 }
6842 }
6843 }
6844
6845 if (ClassExported)
6846 DelayedDllExportClasses.push_back(Class);
6847}
6848
6850 CXXRecordDecl *Class, Attr *ClassAttr,
6851 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6852 if (getDLLAttr(
6853 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6854 // If the base class template has a DLL attribute, don't try to change it.
6855 return;
6856 }
6857
6858 auto TSK = BaseTemplateSpec->getSpecializationKind();
6859 if (!getDLLAttr(BaseTemplateSpec) &&
6861 TSK == TSK_ImplicitInstantiation)) {
6862 // The template hasn't been instantiated yet (or it has, but only as an
6863 // explicit instantiation declaration or implicit instantiation, which means
6864 // we haven't codegenned any members yet), so propagate the attribute.
6865 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6866 NewAttr->setInherited(true);
6867 BaseTemplateSpec->addAttr(NewAttr);
6868
6869 // If this was an import, mark that we propagated it from a derived class to
6870 // a base class template specialization.
6871 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6872 ImportAttr->setPropagatedToBaseTemplate();
6873
6874 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6875 // needs to be run again to work see the new attribute. Otherwise this will
6876 // get run whenever the template is instantiated.
6877 if (TSK != TSK_Undeclared)
6878 checkClassLevelDLLAttribute(BaseTemplateSpec);
6879
6880 return;
6881 }
6882
6883 if (getDLLAttr(BaseTemplateSpec)) {
6884 // The template has already been specialized or instantiated with an
6885 // attribute, explicitly or through propagation. We should not try to change
6886 // it.
6887 return;
6888 }
6889
6890 // The template was previously instantiated or explicitly specialized without
6891 // a dll attribute, It's too late for us to add an attribute, so warn that
6892 // this is unsupported.
6893 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6894 << BaseTemplateSpec->isExplicitSpecialization();
6895 Diag(ClassAttr->getLocation(), diag::note_attribute);
6896 if (BaseTemplateSpec->isExplicitSpecialization()) {
6897 Diag(BaseTemplateSpec->getLocation(),
6898 diag::note_template_class_explicit_specialization_was_here)
6899 << BaseTemplateSpec;
6900 } else {
6901 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6902 diag::note_template_class_instantiation_was_here)
6903 << BaseTemplateSpec;
6904 }
6905}
6906
6907namespace {
6908/// RAII object to restore the floating-point (FP) features active at the time
6909/// a defaulted function was declared. This ensures that the synthesized body
6910/// of the function respects the FP pragmas (e.g., #pragma STDC FENV_ACCESS)
6911/// that were in effect when the function was explicitly defaulted.
6912struct DefaultedFunctionFPFeaturesRAII {
6913 Sema::FPFeaturesStateRAII SavedFPFeatures;
6914 DefaultedFunctionFPFeaturesRAII(Sema &S, FunctionDecl *FD)
6915 : SavedFPFeatures(S) {
6916 auto *Info = FD->getDefaultedOrDeletedInfo();
6917 FPOptionsOverride FPO = Info ? Info->getFPFeatures() : FPOptionsOverride();
6919 S.FpPragmaStack.CurrentValue = FPO;
6920 }
6921
6922 ~DefaultedFunctionFPFeaturesRAII() = default;
6923};
6924} // namespace
6925
6927 SourceLocation DefaultLoc) {
6929 if (DFK.isComparison())
6930 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6931
6932 switch (DFK.asSpecialMember()) {
6936 break;
6939 break;
6942 break;
6945 break;
6948 break;
6951 break;
6953 llvm_unreachable("Invalid special member.");
6954 }
6955}
6956
6957/// Determine whether a type is permitted to be passed or returned in
6958/// registers, per C++ [class.temporary]p3.
6961 if (D->isDependentType() || D->isInvalidDecl())
6962 return false;
6963
6964 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6965 // The PS4 platform ABI follows the behavior of Clang 3.2.
6967 return !D->hasNonTrivialDestructorForCall() &&
6969
6970 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6971 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6972 bool DtorIsTrivialForCall = false;
6973
6974 // If a class has at least one eligible, trivial copy constructor, it
6975 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6976 //
6977 // Note: This permits classes with non-trivial copy or move ctors to be
6978 // passed in registers, so long as they *also* have a trivial copy ctor,
6979 // which is non-conforming.
6983 CopyCtorIsTrivial = true;
6985 CopyCtorIsTrivialForCall = true;
6986 }
6987 } else {
6988 for (const CXXConstructorDecl *CD : D->ctors()) {
6989 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6990 !CD->isIneligibleOrNotSelected()) {
6991 if (CD->isTrivial())
6992 CopyCtorIsTrivial = true;
6993 if (CD->isTrivialForCall())
6994 CopyCtorIsTrivialForCall = true;
6995 }
6996 }
6997 }
6998
6999 if (D->needsImplicitDestructor()) {
7000 if (!D->defaultedDestructorIsDeleted() &&
7002 DtorIsTrivialForCall = true;
7003 } else if (const auto *DD = D->getDestructor()) {
7004 if (!DD->isDeleted() && DD->isTrivialForCall())
7005 DtorIsTrivialForCall = true;
7006 }
7007
7008 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
7009 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
7010 return true;
7011
7012 // If a class has a destructor, we'd really like to pass it indirectly
7013 // because it allows us to elide copies. Unfortunately, MSVC makes that
7014 // impossible for small types, which it will pass in a single register or
7015 // stack slot. Most objects with dtors are large-ish, so handle that early.
7016 // We can't call out all large objects as being indirect because there are
7017 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7018 // how we pass large POD types.
7019
7020 // Note: This permits small classes with nontrivial destructors to be
7021 // passed in registers, which is non-conforming.
7022 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7023 uint64_t TypeSize = isAArch64 ? 128 : 64;
7024
7025 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7026 S.Context.getCanonicalTagType(D)) <= TypeSize)
7027 return true;
7028 return false;
7029 }
7030
7031 // Per C++ [class.temporary]p3, the relevant condition is:
7032 // each copy constructor, move constructor, and destructor of X is
7033 // either trivial or deleted, and X has at least one non-deleted copy
7034 // or move constructor
7035 bool HasNonDeletedCopyOrMove = false;
7036
7040 return false;
7041 HasNonDeletedCopyOrMove = true;
7042 }
7043
7044 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7047 return false;
7048 HasNonDeletedCopyOrMove = true;
7049 }
7050
7053 return false;
7054
7055 for (const CXXMethodDecl *MD : D->methods()) {
7056 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7057 continue;
7058
7059 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
7060 if (CD && CD->isCopyOrMoveConstructor())
7061 HasNonDeletedCopyOrMove = true;
7062 else if (!isa<CXXDestructorDecl>(MD))
7063 continue;
7064
7065 if (!MD->isTrivialForCall())
7066 return false;
7067 }
7068
7069 return HasNonDeletedCopyOrMove;
7070}
7071
7072/// Report an error regarding overriding, along with any relevant
7073/// overridden methods.
7074///
7075/// \param DiagID the primary error to report.
7076/// \param MD the overriding method.
7077static bool
7078ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7079 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7080 bool IssuedDiagnostic = false;
7081 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7082 if (Report(O)) {
7083 if (!IssuedDiagnostic) {
7084 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7085 IssuedDiagnostic = true;
7086 }
7087 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7088 }
7089 }
7090 return IssuedDiagnostic;
7091}
7092
7094 if (!Record)
7095 return;
7096
7097 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7098 AbstractUsageInfo Info(*this, Record);
7100 }
7101
7102 // If this is not an aggregate type and has no user-declared constructor,
7103 // complain about any non-static data members of reference or const scalar
7104 // type, since they will never get initializers.
7105 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7106 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7107 !Record->isLambda()) {
7108 bool Complained = false;
7109 for (const auto *F : Record->fields()) {
7110 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7111 continue;
7112
7113 if (F->getType()->isReferenceType() ||
7114 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7115 if (!Complained) {
7116 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7117 << Record->getTagKind() << Record;
7118 Complained = true;
7119 }
7120
7121 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7122 << F->getType()->isReferenceType()
7123 << F->getDeclName();
7124 }
7125 }
7126 }
7127
7128 if (Record->getIdentifier()) {
7129 // C++ [class.mem]p13:
7130 // If T is the name of a class, then each of the following shall have a
7131 // name different from T:
7132 // - every member of every anonymous union that is a member of class T.
7133 //
7134 // C++ [class.mem]p14:
7135 // In addition, if class T has a user-declared constructor (12.1), every
7136 // non-static data member of class T shall have a name different from T.
7137 for (const NamedDecl *Element : Record->lookup(Record->getDeclName())) {
7138 const NamedDecl *D = Element->getUnderlyingDecl();
7139 // Invalid IndirectFieldDecls have already been diagnosed with
7140 // err_anonymous_record_member_redecl in
7141 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7143 Record->hasUserDeclaredConstructor()) ||
7144 (isa<IndirectFieldDecl>(D) && !D->isInvalidDecl())) {
7145 Diag(Element->getLocation(), diag::err_member_name_of_class)
7146 << D->getDeclName();
7147 break;
7148 }
7149 }
7150 }
7151
7152 // Warn if the class has virtual methods but non-virtual public destructor.
7153 if (Record->isPolymorphic() && !Record->isDependentType()) {
7154 CXXDestructorDecl *dtor = Record->getDestructor();
7155 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7156 !Record->hasAttr<FinalAttr>())
7157 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7158 diag::warn_non_virtual_dtor)
7159 << Context.getCanonicalTagType(Record);
7160 }
7161
7162 if (Record->isAbstract()) {
7163 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7164 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7165 << FA->isSpelledAsSealed();
7167 }
7168 }
7169
7170 // Warn if the class has a final destructor but is not itself marked final.
7171 if (!Record->hasAttr<FinalAttr>()) {
7172 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7173 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7174 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7175 << FA->isSpelledAsSealed()
7177 getLocForEndOfToken(Record->getLocation()),
7178 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7179 Diag(Record->getLocation(),
7180 diag::note_final_dtor_non_final_class_silence)
7181 << Context.getCanonicalTagType(Record) << FA->isSpelledAsSealed();
7182 }
7183 }
7184 }
7185
7186 // See if trivial_abi has to be dropped.
7187 if (Record->hasAttr<TrivialABIAttr>())
7189
7190 // Set HasTrivialSpecialMemberForCall if the record has attribute
7191 // "trivial_abi".
7192 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7193
7194 if (HasTrivialABI)
7195 Record->setHasTrivialSpecialMemberForCall();
7196
7197 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7198 // We check these last because they can depend on the properties of the
7199 // primary comparison functions (==, <=>).
7200 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7201
7202 // Perform checks that can't be done until we know all the properties of a
7203 // member function (whether it's defaulted, deleted, virtual, overriding,
7204 // ...).
7205 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7206 // A static function cannot override anything.
7207 if (MD->getStorageClass() == SC_Static) {
7208 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7209 [](const CXXMethodDecl *) { return true; }))
7210 return;
7211 }
7212
7213 // A deleted function cannot override a non-deleted function and vice
7214 // versa.
7215 if (ReportOverrides(*this,
7216 MD->isDeleted() ? diag::err_deleted_override
7217 : diag::err_non_deleted_override,
7218 MD, [&](const CXXMethodDecl *V) {
7219 return MD->isDeleted() != V->isDeleted();
7220 })) {
7221 if (MD->isDefaulted() && MD->isDeleted())
7222 // Explain why this defaulted function was deleted.
7224 return;
7225 }
7226
7227 // A consteval function cannot override a non-consteval function and vice
7228 // versa.
7229 if (ReportOverrides(*this,
7230 MD->isConsteval() ? diag::err_consteval_override
7231 : diag::err_non_consteval_override,
7232 MD, [&](const CXXMethodDecl *V) {
7233 return MD->isConsteval() != V->isConsteval();
7234 })) {
7235 if (MD->isDefaulted() && MD->isDeleted())
7236 // Explain why this defaulted function was deleted.
7238 return;
7239 }
7240 };
7241
7242 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7243 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7244 return false;
7245
7249 DefaultedSecondaryComparisons.push_back(FD);
7250 return true;
7251 }
7252
7254 return false;
7255 };
7256
7257 if (!Record->isInvalidDecl() &&
7258 Record->hasAttr<VTablePointerAuthenticationAttr>())
7260
7261 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7262 // Check whether the explicitly-defaulted members are valid.
7263 bool Incomplete = CheckForDefaultedFunction(M);
7264
7265 // Skip the rest of the checks for a member of a dependent class.
7266 if (Record->isDependentType())
7267 return;
7268
7269 // For an explicitly defaulted or deleted special member, we defer
7270 // determining triviality until the class is complete. That time is now!
7271 CXXSpecialMemberKind CSM = M->getSpecialMemberKind();
7272 if (!M->isImplicit() && !M->isUserProvided()) {
7273 if (CSM != CXXSpecialMemberKind::Invalid) {
7274 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7275 // Inform the class that we've finished declaring this member.
7276 Record->finishedDefaultedOrDeletedMember(M);
7277 M->setTrivialForCall(
7278 HasTrivialABI ||
7281 Record->setTrivialForCallFlags(M);
7282 }
7283 }
7284
7285 // Set triviality for the purpose of calls if this is a user-provided
7286 // copy/move constructor or destructor.
7290 M->isUserProvided()) {
7291 M->setTrivialForCall(HasTrivialABI);
7292 Record->setTrivialForCallFlags(M);
7293 }
7294
7295 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7296 M->hasAttr<DLLExportAttr>()) {
7297 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7298 M->isTrivial() &&
7302 M->dropAttr<DLLExportAttr>();
7303
7304 if (M->hasAttr<DLLExportAttr>()) {
7305 // Define after any fields with in-class initializers have been parsed.
7307 }
7308 }
7309
7310 bool EffectivelyConstexprDestructor = true;
7311 // Avoid triggering vtable instantiation due to a dtor that is not
7312 // "effectively constexpr" for better compatibility.
7313 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7314 if (isa<CXXDestructorDecl>(M)) {
7315 llvm::SmallDenseSet<QualType> Visited;
7316 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7317 if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)
7318 return false;
7319 const CXXRecordDecl *RD =
7320 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7321 if (!RD || !RD->isCompleteDefinition())
7322 return true;
7323
7324 if (!RD->hasConstexprDestructor())
7325 return false;
7326
7327 for (const CXXBaseSpecifier &B : RD->bases())
7328 if (!Check(B.getType(), Check))
7329 return false;
7330 for (const FieldDecl *FD : RD->fields())
7331 if (!Check(FD->getType(), Check))
7332 return false;
7333 return true;
7334 };
7335 EffectivelyConstexprDestructor =
7336 Check(Context.getCanonicalTagType(Record), Check);
7337 }
7338
7339 // Define defaulted constexpr virtual functions that override a base class
7340 // function right away.
7341 // FIXME: We can defer doing this until the vtable is marked as used.
7342 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7343 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7344 EffectivelyConstexprDestructor)
7345 DefineDefaultedFunction(*this, M, M->getLocation());
7346
7347 if (!Incomplete)
7348 CheckCompletedMemberFunction(M);
7349 };
7350
7351 // Check the destructor before any other member function. We need to
7352 // determine whether it's trivial in order to determine whether the claas
7353 // type is a literal type, which is a prerequisite for determining whether
7354 // other special member functions are valid and whether they're implicitly
7355 // 'constexpr'.
7356 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7357 CompleteMemberFunction(Dtor);
7358
7359 bool HasMethodWithOverrideControl = false,
7360 HasOverridingMethodWithoutOverrideControl = false;
7361 for (auto *D : Record->decls()) {
7362 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7363 // FIXME: We could do this check for dependent types with non-dependent
7364 // bases.
7365 if (!Record->isDependentType()) {
7366 // See if a method overloads virtual methods in a base
7367 // class without overriding any.
7368 if (!M->isStatic())
7370
7371 if (M->hasAttr<OverrideAttr>()) {
7372 HasMethodWithOverrideControl = true;
7373 } else if (M->size_overridden_methods() > 0) {
7374 HasOverridingMethodWithoutOverrideControl = true;
7375 } else {
7376 // Warn on newly-declared virtual methods in `final` classes
7377 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7378 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7379 << M;
7380 }
7381 }
7382 }
7383
7384 if (!isa<CXXDestructorDecl>(M))
7385 CompleteMemberFunction(M);
7386 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7387 CheckForDefaultedFunction(
7388 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7389 }
7390 }
7391
7392 if (HasOverridingMethodWithoutOverrideControl) {
7393 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7394 for (auto *M : Record->methods())
7395 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7396 }
7397
7398 // Check the defaulted secondary comparisons after any other member functions.
7399 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7401
7402 // If this is a member function, we deferred checking it until now.
7403 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7404 CheckCompletedMemberFunction(MD);
7405 }
7406
7407 // {ms,gcc}_struct is a request to change ABI rules to either follow
7408 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7409 // present, we do not layout classes following foreign ABI rules, but
7410 // instead enter a special "compatibility mode", which only changes
7411 // alignments of fundamental types and layout of bit fields.
7412 // Check whether this class uses any C++ features that are implemented
7413 // completely differently in the requested ABI, and if so, emit a
7414 // diagnostic. That diagnostic defaults to an error, but we allow
7415 // projects to map it down to a warning (or ignore it). It's a fairly
7416 // common practice among users of the ms_struct pragma to
7417 // mass-annotate headers, sweeping up a bunch of types that the
7418 // project doesn't really rely on MSVC-compatible layout for. We must
7419 // therefore support "ms_struct except for C++ stuff" as a secondary
7420 // ABI.
7421 // Don't emit this diagnostic if the feature was enabled as a
7422 // language option (as opposed to via a pragma or attribute), as
7423 // the option -mms-bitfields otherwise essentially makes it impossible
7424 // to build C++ code, unless this diagnostic is turned off.
7425 if (Context.getLangOpts().getLayoutCompatibility() ==
7427 Record->isMsStruct(Context) != Context.defaultsToMsStruct() &&
7428 (Record->isPolymorphic() || Record->getNumBases())) {
7429 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7430 }
7431
7434
7435 bool ClangABICompat4 =
7436 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver4);
7438 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7439 bool CanPass = canPassInRegisters(*this, Record, CCK);
7440
7441 // Do not change ArgPassingRestrictions if it has already been set to
7442 // RecordArgPassingKind::CanNeverPassInRegs.
7443 if (Record->getArgPassingRestrictions() !=
7445 Record->setArgPassingRestrictions(
7448
7449 // If canPassInRegisters returns true despite the record having a non-trivial
7450 // destructor, the record is destructed in the callee. This happens only when
7451 // the record or one of its subobjects has a field annotated with trivial_abi
7452 // or a field qualified with ObjC __strong/__weak.
7453 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7454 Record->setParamDestroyedInCallee(true);
7455 else if (Record->hasNonTrivialDestructor())
7456 Record->setParamDestroyedInCallee(CanPass);
7457
7458 if (getLangOpts().ForceEmitVTables) {
7459 // If we want to emit all the vtables, we need to mark it as used. This
7460 // is especially required for cases like vtable assumption loads.
7461 MarkVTableUsed(Record->getInnerLocStart(), Record);
7462 }
7463
7464 if (getLangOpts().CUDA) {
7465 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7467 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7469 }
7470
7471 llvm::SmallDenseMap<OverloadedOperatorKind,
7473 TypeAwareDecls{{OO_New, {}},
7474 {OO_Array_New, {}},
7475 {OO_Delete, {}},
7476 {OO_Array_New, {}}};
7477 for (auto *D : Record->decls()) {
7478 const FunctionDecl *FnDecl = D->getAsFunction();
7479 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7480 continue;
7481 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7482 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7483 }
7484 auto CheckMismatchedTypeAwareAllocators =
7485 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7486 OverloadedOperatorKind DeleteKind) {
7487 auto &NewDecls = TypeAwareDecls[NewKind];
7488 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7489 if (NewDecls.empty() == DeleteDecls.empty())
7490 return;
7491 DeclarationName FoundOperator =
7492 Context.DeclarationNames.getCXXOperatorName(
7493 NewDecls.empty() ? DeleteKind : NewKind);
7494 DeclarationName MissingOperator =
7495 Context.DeclarationNames.getCXXOperatorName(
7496 NewDecls.empty() ? NewKind : DeleteKind);
7497 Diag(Record->getLocation(),
7498 diag::err_type_aware_allocator_missing_matching_operator)
7499 << FoundOperator << Context.getCanonicalTagType(Record)
7500 << MissingOperator;
7501 for (auto MD : NewDecls)
7502 Diag(MD->getLocation(),
7503 diag::note_unmatched_type_aware_allocator_declared)
7504 << MD;
7505 for (auto MD : DeleteDecls)
7506 Diag(MD->getLocation(),
7507 diag::note_unmatched_type_aware_allocator_declared)
7508 << MD;
7509 };
7510 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7511 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7512}
7513
7514/// Look up the special member function that would be called by a special
7515/// member function for a subobject of class type.
7516///
7517/// \param Class The class type of the subobject.
7518/// \param CSM The kind of special member function.
7519/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7520/// \param ConstRHS True if this is a copy operation with a const object
7521/// on its RHS, that is, if the argument to the outer special member
7522/// function is 'const' and this is not a field marked 'mutable'.
7525 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7526 bool ConstRHS) {
7527 unsigned LHSQuals = 0;
7530 LHSQuals = FieldQuals;
7531
7532 unsigned RHSQuals = FieldQuals;
7535 RHSQuals = 0;
7536 else if (ConstRHS)
7537 RHSQuals |= Qualifiers::Const;
7538
7539 return S.LookupSpecialMember(Class, CSM,
7540 RHSQuals & Qualifiers::Const,
7541 RHSQuals & Qualifiers::Volatile,
7542 false,
7543 LHSQuals & Qualifiers::Const,
7544 LHSQuals & Qualifiers::Volatile);
7545}
7546
7548 Sema &S;
7549 SourceLocation UseLoc;
7550
7551 /// A mapping from the base classes through which the constructor was
7552 /// inherited to the using shadow declaration in that base class (or a null
7553 /// pointer if the constructor was declared in that base class).
7554 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7555 InheritedFromBases;
7556
7557public:
7560 : S(S), UseLoc(UseLoc) {
7561 bool DiagnosedMultipleConstructedBases = false;
7562 CXXRecordDecl *ConstructedBase = nullptr;
7563 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7564
7565 // Find the set of such base class subobjects and check that there's a
7566 // unique constructed subobject.
7567 for (auto *D : Shadow->redecls()) {
7568 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7569 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7570 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7571
7572 InheritedFromBases.insert(
7573 std::make_pair(DNominatedBase->getCanonicalDecl(),
7574 DShadow->getNominatedBaseClassShadowDecl()));
7575 if (DShadow->constructsVirtualBase())
7576 InheritedFromBases.insert(
7577 std::make_pair(DConstructedBase->getCanonicalDecl(),
7578 DShadow->getConstructedBaseClassShadowDecl()));
7579 else
7580 assert(DNominatedBase == DConstructedBase);
7581
7582 // [class.inhctor.init]p2:
7583 // If the constructor was inherited from multiple base class subobjects
7584 // of type B, the program is ill-formed.
7585 if (!ConstructedBase) {
7586 ConstructedBase = DConstructedBase;
7587 ConstructedBaseIntroducer = D->getIntroducer();
7588 } else if (ConstructedBase != DConstructedBase &&
7589 !Shadow->isInvalidDecl()) {
7590 if (!DiagnosedMultipleConstructedBases) {
7591 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7592 << Shadow->getTargetDecl();
7593 S.Diag(ConstructedBaseIntroducer->getLocation(),
7594 diag::note_ambiguous_inherited_constructor_using)
7595 << ConstructedBase;
7596 DiagnosedMultipleConstructedBases = true;
7597 }
7598 S.Diag(D->getIntroducer()->getLocation(),
7599 diag::note_ambiguous_inherited_constructor_using)
7600 << DConstructedBase;
7601 }
7602 }
7603
7604 if (DiagnosedMultipleConstructedBases)
7605 Shadow->setInvalidDecl();
7606 }
7607
7608 /// Find the constructor to use for inherited construction of a base class,
7609 /// and whether that base class constructor inherits the constructor from a
7610 /// virtual base class (in which case it won't actually invoke it).
7611 std::pair<CXXConstructorDecl *, bool>
7613 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7614 if (It == InheritedFromBases.end())
7615 return std::make_pair(nullptr, false);
7616
7617 // This is an intermediary class.
7618 if (It->second)
7619 return std::make_pair(
7620 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7621 It->second->constructsVirtualBase());
7622
7623 // This is the base class from which the constructor was inherited.
7624 return std::make_pair(Ctor, false);
7625 }
7626};
7627
7628/// Is the special member function which would be selected to perform the
7629/// specified operation on the specified class type a constexpr constructor?
7631 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7632 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7633 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7634 // Suppress duplicate constraint checking here, in case a constraint check
7635 // caused us to decide to do this. Any truely recursive checks will get
7636 // caught during these checks anyway.
7638
7639 // If we're inheriting a constructor, see if we need to call it for this base
7640 // class.
7641 if (InheritedCtor) {
7643 auto BaseCtor =
7644 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7645 if (BaseCtor)
7646 return BaseCtor->isConstexpr();
7647 }
7648
7650 return ClassDecl->hasConstexprDefaultConstructor();
7652 return ClassDecl->hasConstexprDestructor();
7653
7655 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7656 if (!SMOR.getMethod())
7657 // A constructor we wouldn't select can't be "involved in initializing"
7658 // anything.
7659 return true;
7660 return SMOR.getMethod()->isConstexpr();
7661}
7662
7663/// Determine whether the specified special member function would be constexpr
7664/// if it were implicitly defined.
7666 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7667 CXXConstructorDecl *InheritedCtor = nullptr,
7668 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7669 if (!S.getLangOpts().CPlusPlus11)
7670 return false;
7671
7672 // C++11 [dcl.constexpr]p4:
7673 // In the definition of a constexpr constructor [...]
7674 bool Ctor = true;
7675 switch (CSM) {
7677 if (Inherited)
7678 break;
7679 // Since default constructor lookup is essentially trivial (and cannot
7680 // involve, for instance, template instantiation), we compute whether a
7681 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7682 //
7683 // This is important for performance; we need to know whether the default
7684 // constructor is constexpr to determine whether the type is a literal type.
7685 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7686
7689 // For copy or move constructors, we need to perform overload resolution.
7690 break;
7691
7694 if (!S.getLangOpts().CPlusPlus14)
7695 return false;
7696 // In C++1y, we need to perform overload resolution.
7697 Ctor = false;
7698 break;
7699
7701 return ClassDecl->defaultedDestructorIsConstexpr();
7702
7704 return false;
7705 }
7706
7707 // -- if the class is a non-empty union, or for each non-empty anonymous
7708 // union member of a non-union class, exactly one non-static data member
7709 // shall be initialized; [DR1359]
7710 //
7711 // If we squint, this is guaranteed, since exactly one non-static data member
7712 // will be initialized (if the constructor isn't deleted), we just don't know
7713 // which one.
7714 if (Ctor && ClassDecl->isUnion())
7716 ? ClassDecl->hasInClassInitializer() ||
7717 !ClassDecl->hasVariantMembers()
7718 : true;
7719
7720 // -- the class shall not have any virtual base classes;
7721 if (!S.getLangOpts().CPlusPlus26 && Ctor && ClassDecl->getNumVBases())
7722 return false;
7723
7724 // C++1y [class.copy]p26:
7725 // -- [the class] is a literal type, and
7726 if (!S.getLangOpts().CPlusPlus23 && !Ctor && !ClassDecl->isLiteral())
7727 return false;
7728
7729 // -- every constructor involved in initializing [...] base class
7730 // sub-objects shall be a constexpr constructor;
7731 // -- the assignment operator selected to copy/move each direct base
7732 // class is a constexpr function, and
7733 if (!S.getLangOpts().CPlusPlus23) {
7734 for (const auto &B : ClassDecl->bases()) {
7735 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7736 if (!BaseClassDecl)
7737 continue;
7738 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7739 InheritedCtor, Inherited))
7740 return false;
7741 }
7742 }
7743
7744 // -- every constructor involved in initializing non-static data members
7745 // [...] shall be a constexpr constructor;
7746 // -- every non-static data member and base class sub-object shall be
7747 // initialized
7748 // -- for each non-static data member of X that is of class type (or array
7749 // thereof), the assignment operator selected to copy/move that member is
7750 // a constexpr function
7751 if (!S.getLangOpts().CPlusPlus23) {
7752 for (const auto *F : ClassDecl->fields()) {
7753 if (F->isInvalidDecl())
7754 continue;
7756 F->hasInClassInitializer())
7757 continue;
7758 QualType BaseType = S.Context.getBaseElementType(F->getType());
7759 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7760 auto *FieldRecDecl =
7761 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
7762 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7763 BaseType.getCVRQualifiers(),
7764 ConstArg && !F->isMutable()))
7765 return false;
7766 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7767 return false;
7768 }
7769 }
7770 }
7771
7772 // All OK, it's constexpr!
7773 return true;
7774}
7775
7776namespace {
7777/// RAII object to register a defaulted function as having its exception
7778/// specification computed.
7779struct ComputingExceptionSpec {
7780 Sema &S;
7781
7782 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7783 : S(S) {
7784 Sema::CodeSynthesisContext Ctx;
7786 Ctx.PointOfInstantiation = Loc;
7787 Ctx.Entity = FD;
7789 }
7790 ~ComputingExceptionSpec() {
7792 }
7793};
7794}
7795
7796static Sema::ImplicitExceptionSpecification
7797ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7798 CXXMethodDecl *MD,
7800 Sema::InheritedConstructorInfo *ICI);
7801
7802static Sema::ImplicitExceptionSpecification
7803ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7804 FunctionDecl *FD,
7806
7807static Sema::ImplicitExceptionSpecification
7809 auto DFK = FD->getDefaultedFunctionKind();
7810 if (DFK.isSpecialMember())
7812 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7813 if (DFK.isComparison())
7815 DFK.asComparison());
7816
7817 auto *CD = cast<CXXConstructorDecl>(FD);
7818 assert(CD->getInheritedConstructor() &&
7819 "only defaulted functions and inherited constructors have implicit "
7820 "exception specs");
7822 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7825}
7826
7828 CXXMethodDecl *MD) {
7830
7831 // Build an exception specification pointing back at this member.
7833 EPI.ExceptionSpec.SourceDecl = MD;
7834
7835 // Set the calling convention to the default for C++ instance methods.
7837 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7838 /*IsCXXMethod=*/true));
7839 return EPI;
7840}
7841
7843 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7845 return;
7846
7847 // Evaluate the exception specification.
7848 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7849 auto ESI = IES.getExceptionSpec();
7850
7851 // Update the type of the special member to use it.
7852 UpdateExceptionSpec(FD, ESI);
7853}
7854
7856 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7857
7859 if (!DefKind) {
7860 assert(FD->getDeclContext()->isDependentContext());
7861 return;
7862 }
7863
7864 if (DefKind.isComparison()) {
7865 auto PT = FD->getParamDecl(0)->getType();
7866 if (const CXXRecordDecl *RD =
7867 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7868 for (FieldDecl *Field : RD->fields()) {
7869 UnusedPrivateFields.remove(Field);
7870 }
7871 }
7872 }
7873
7874 if (DefKind.isSpecialMember()
7876 DefKind.asSpecialMember(),
7877 FD->getDefaultLoc())
7879 FD->setInvalidDecl();
7880}
7881
7884 SourceLocation DefaultLoc) {
7885 CXXRecordDecl *RD = MD->getParent();
7886
7888 "not an explicitly-defaulted special member");
7889
7890 // Defer all checking for special members of a dependent type.
7891 if (RD->isDependentType())
7892 return false;
7893
7894 // Whether this was the first-declared instance of the constructor.
7895 // This affects whether we implicitly add an exception spec and constexpr.
7896 bool First = MD == MD->getCanonicalDecl();
7897
7898 bool HadError = false;
7899
7900 // C++11 [dcl.fct.def.default]p1:
7901 // A function that is explicitly defaulted shall
7902 // -- be a special member function [...] (checked elsewhere),
7903 // -- have the same type (except for ref-qualifiers, and except that a
7904 // copy operation can take a non-const reference) as an implicit
7905 // declaration, and
7906 // -- not have default arguments.
7907 // C++2a changes the second bullet to instead delete the function if it's
7908 // defaulted on its first declaration, unless it's "an assignment operator,
7909 // and its return type differs or its parameter type is not a reference".
7910 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7911 bool ShouldDeleteForTypeMismatch = false;
7912 unsigned ExpectedParams = 1;
7915 ExpectedParams = 0;
7916 if (MD->getNumExplicitParams() != ExpectedParams) {
7917 // This checks for default arguments: a copy or move constructor with a
7918 // default argument is classified as a default constructor, and assignment
7919 // operations and destructors can't have default arguments.
7920 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7921 << CSM << MD->getSourceRange();
7922 HadError = true;
7923 } else if (MD->isVariadic()) {
7924 if (DeleteOnTypeMismatch)
7925 ShouldDeleteForTypeMismatch = true;
7926 else {
7927 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7928 << CSM << MD->getSourceRange();
7929 HadError = true;
7930 }
7931 }
7932
7934
7935 bool CanHaveConstParam = false;
7937 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7939 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7940
7941 QualType ReturnType = Context.VoidTy;
7944 // Check for return type matching.
7945 ReturnType = Type->getReturnType();
7947
7948 QualType DeclType =
7950 /*Qualifier=*/std::nullopt, RD, /*OwnsTag=*/false);
7951 DeclType = Context.getAddrSpaceQualType(
7952 DeclType, ThisType.getQualifiers().getAddressSpace());
7953 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7954
7955 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7956 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7958 << ExpectedReturnType;
7959 HadError = true;
7960 }
7961
7962 // A defaulted special member cannot have cv-qualifiers.
7963 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7964 if (DeleteOnTypeMismatch)
7965 ShouldDeleteForTypeMismatch = true;
7966 else {
7967 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7969 << getLangOpts().CPlusPlus14;
7970 HadError = true;
7971 }
7972 }
7973 // [C++23][dcl.fct.def.default]/p2.2
7974 // if F2 has an implicit object parameter of type “reference to C”,
7975 // F1 may be an explicit object member function whose explicit object
7976 // parameter is of (possibly different) type “reference to C”,
7977 // in which case the type of F1 would differ from the type of F2
7978 // in that the type of F1 has an additional parameter;
7979 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7980 ? MD->getParamDecl(0)->getType()
7981 : QualType();
7982 if (!ExplicitObjectParameter.isNull() &&
7983 (!ExplicitObjectParameter->isReferenceType() ||
7984 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7985 Context.getCanonicalTagType(RD)))) {
7986 if (DeleteOnTypeMismatch)
7987 ShouldDeleteForTypeMismatch = true;
7988 else {
7989 Diag(MD->getLocation(),
7990 diag::err_defaulted_special_member_explicit_object_mismatch)
7991 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7992 << MD->getSourceRange();
7993 HadError = true;
7994 }
7995 }
7996 }
7997
7998 // Check for parameter type matching.
8000 ExpectedParams
8001 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
8002 : QualType();
8003 bool HasConstParam = false;
8004 if (ExpectedParams && ArgType->isReferenceType()) {
8005 // Argument must be reference to possibly-const T.
8006 QualType ReferentType = ArgType->getPointeeType();
8007 HasConstParam = ReferentType.isConstQualified();
8008
8009 if (ReferentType.isVolatileQualified()) {
8010 if (DeleteOnTypeMismatch)
8011 ShouldDeleteForTypeMismatch = true;
8012 else {
8013 Diag(MD->getLocation(),
8014 diag::err_defaulted_special_member_volatile_param)
8015 << CSM;
8016 HadError = true;
8017 }
8018 }
8019
8020 if (HasConstParam && !CanHaveConstParam) {
8021 if (DeleteOnTypeMismatch)
8022 ShouldDeleteForTypeMismatch = true;
8023 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8025 Diag(MD->getLocation(),
8026 diag::err_defaulted_special_member_copy_const_param)
8028 // FIXME: Explain why this special member can't be const.
8029 HadError = true;
8030 } else {
8031 Diag(MD->getLocation(),
8032 diag::err_defaulted_special_member_move_const_param)
8034 HadError = true;
8035 }
8036 }
8037 } else if (ExpectedParams) {
8038 // A copy assignment operator can take its argument by value, but a
8039 // defaulted one cannot.
8041 "unexpected non-ref argument");
8042 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
8043 HadError = true;
8044 }
8045
8046 // C++11 [dcl.fct.def.default]p2:
8047 // An explicitly-defaulted function may be declared constexpr only if it
8048 // would have been implicitly declared as constexpr,
8049 // Do not apply this rule to members of class templates, since core issue 1358
8050 // makes such functions always instantiate to constexpr functions. For
8051 // functions which cannot be constexpr (for non-constructors in C++11 and for
8052 // destructors in C++14 and C++17), this is checked elsewhere.
8053 //
8054 // FIXME: This should not apply if the member is deleted.
8055 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
8056 HasConstParam);
8057
8058 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8059 // If the instantiated template specialization of a constexpr function
8060 // template or member function of a class template would fail to satisfy
8061 // the requirements for a constexpr function or constexpr constructor, that
8062 // specialization is still a constexpr function or constexpr constructor,
8063 // even though a call to such a function cannot appear in a constant
8064 // expression.
8065 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8066 Constexpr = true;
8067
8068 if ((getLangOpts().CPlusPlus20 ||
8070 : isa<CXXConstructorDecl>(MD))) &&
8071 MD->isConstexpr() && !Constexpr &&
8073 if (!MD->isConsteval() && RD->getNumVBases()) {
8074 Diag(MD->getBeginLoc(),
8075 diag::err_incorrect_defaulted_constexpr_with_vb)
8076 << CSM;
8077 for (const auto &I : RD->vbases())
8078 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
8079 } else {
8080 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
8081 << CSM << MD->isConsteval();
8082 }
8083 HadError = true;
8084 // FIXME: Explain why the special member can't be constexpr.
8085 }
8086 if (First) {
8087 // C++2a [dcl.fct.def.default]p3:
8088 // If a function is explicitly defaulted on its first declaration, it is
8089 // implicitly considered to be constexpr if the implicit declaration
8090 // would be.
8095
8096 if (!Type->hasExceptionSpec()) {
8097 // C++2a [except.spec]p3:
8098 // If a declaration of a function does not have a noexcept-specifier
8099 // [and] is defaulted on its first declaration, [...] the exception
8100 // specification is as specified below
8101 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8103 EPI.ExceptionSpec.SourceDecl = MD;
8104 MD->setType(
8105 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
8106 }
8107 }
8108
8109 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8110 if (First) {
8111 SetDeclDeleted(MD, MD->getLocation());
8112 if (!inTemplateInstantiation() && !HadError) {
8113 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
8114 if (ShouldDeleteForTypeMismatch) {
8115 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
8116 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
8117 /*Diagnose*/ true) &&
8118 DefaultLoc.isValid()) {
8119 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
8120 << FixItHint::CreateReplacement(DefaultLoc, "delete");
8121 }
8122 }
8123 if (ShouldDeleteForTypeMismatch && !HadError) {
8124 Diag(MD->getLocation(),
8125 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8126 << CSM;
8127 }
8128 } else {
8129 // C++11 [dcl.fct.def.default]p4:
8130 // [For a] user-provided explicitly-defaulted function [...] if such a
8131 // function is implicitly defined as deleted, the program is ill-formed.
8132 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
8133 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8134 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
8135 HadError = true;
8136 }
8137 }
8138
8139 return HadError;
8140}
8141
8142namespace {
8143/// Helper class for building and checking a defaulted comparison.
8144///
8145/// Defaulted functions are built in two phases:
8146///
8147/// * First, the set of operations that the function will perform are
8148/// identified, and some of them are checked. If any of the checked
8149/// operations is invalid in certain ways, the comparison function is
8150/// defined as deleted and no body is built.
8151/// * Then, if the function is not defined as deleted, the body is built.
8152///
8153/// This is accomplished by performing two visitation steps over the eventual
8154/// body of the function.
8155template<typename Derived, typename ResultList, typename Result,
8156 typename Subobject>
8157class DefaultedComparisonVisitor {
8158public:
8159 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8161 : S(S), RD(RD), FD(FD), DCK(DCK) {
8162 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8163 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8164 // UnresolvedSet to avoid this copy.
8165 Fns.assign(Info->getUnqualifiedLookups().begin(),
8166 Info->getUnqualifiedLookups().end());
8167 }
8168 }
8169
8170 ResultList visit() {
8171 // The type of an lvalue naming a parameter of this function.
8172 QualType ParamLvalType =
8174
8175 ResultList Results;
8176
8177 switch (DCK) {
8179 llvm_unreachable("not a defaulted comparison");
8180
8183 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8184 return Results;
8185
8188 Results.add(getDerived().visitExpandedSubobject(
8189 ParamLvalType, getDerived().getCompleteObject()));
8190 return Results;
8191 }
8192 llvm_unreachable("");
8193 }
8194
8195protected:
8196 Derived &getDerived() { return static_cast<Derived&>(*this); }
8197
8198 /// Visit the expanded list of subobjects of the given type, as specified in
8199 /// C++2a [class.compare.default].
8200 ///
8201 /// \return \c true if the ResultList object said we're done, \c false if not.
8202 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8203 Qualifiers Quals) {
8204 // C++2a [class.compare.default]p4:
8205 // The direct base class subobjects of C
8206 for (CXXBaseSpecifier &Base : Record->bases())
8207 if (Results.add(getDerived().visitSubobject(
8208 S.Context.getQualifiedType(Base.getType(), Quals),
8209 getDerived().getBase(&Base))))
8210 return true;
8211
8212 // followed by the non-static data members of C
8213 for (FieldDecl *Field : Record->fields()) {
8214 // C++23 [class.bit]p2:
8215 // Unnamed bit-fields are not members ...
8216 if (Field->isUnnamedBitField())
8217 continue;
8218 if (Field->isInvalidDecl())
8219 continue;
8220 // Recursively expand anonymous structs.
8221 if (Field->isAnonymousStructOrUnion()) {
8222 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8223 Quals))
8224 return true;
8225 continue;
8226 }
8227
8228 // Figure out the type of an lvalue denoting this field.
8229 Qualifiers FieldQuals = Quals;
8230 if (Field->isMutable())
8231 FieldQuals.removeConst();
8232 QualType FieldType =
8233 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8234
8235 if (Results.add(getDerived().visitSubobject(
8236 FieldType, getDerived().getField(Field))))
8237 return true;
8238 }
8239
8240 // form a list of subobjects.
8241 return false;
8242 }
8243
8244 Result visitSubobject(QualType Type, Subobject Subobj) {
8245 // In that list, any subobject of array type is recursively expanded
8246 const ArrayType *AT = S.Context.getAsArrayType(Type);
8247 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8248 return getDerived().visitSubobjectArray(CAT->getElementType(),
8249 CAT->getSize(), Subobj);
8250 return getDerived().visitExpandedSubobject(Type, Subobj);
8251 }
8252
8253 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8254 Subobject Subobj) {
8255 return getDerived().visitSubobject(Type, Subobj);
8256 }
8257
8258protected:
8259 Sema &S;
8260 CXXRecordDecl *RD;
8261 FunctionDecl *FD;
8263 UnresolvedSet<16> Fns;
8264};
8265
8266/// Information about a defaulted comparison, as determined by
8267/// DefaultedComparisonAnalyzer.
8268struct DefaultedComparisonInfo {
8269 bool Deleted = false;
8270 bool Constexpr = true;
8271 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8272
8273 static DefaultedComparisonInfo deleted() {
8274 DefaultedComparisonInfo Deleted;
8275 Deleted.Deleted = true;
8276 return Deleted;
8277 }
8278
8279 bool add(const DefaultedComparisonInfo &R) {
8280 Deleted |= R.Deleted;
8281 Constexpr &= R.Constexpr;
8282 Category = commonComparisonType(Category, R.Category);
8283 return Deleted;
8284 }
8285};
8286
8287/// An element in the expanded list of subobjects of a defaulted comparison, as
8288/// specified in C++2a [class.compare.default]p4.
8289struct DefaultedComparisonSubobject {
8290 enum { CompleteObject, Member, Base } Kind;
8291 NamedDecl *Decl;
8292 SourceLocation Loc;
8293};
8294
8295/// A visitor over the notional body of a defaulted comparison that determines
8296/// whether that body would be deleted or constexpr.
8297class DefaultedComparisonAnalyzer
8298 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8299 DefaultedComparisonInfo,
8300 DefaultedComparisonInfo,
8301 DefaultedComparisonSubobject> {
8302public:
8303 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8304
8305private:
8306 DiagnosticKind Diagnose;
8307
8308public:
8309 using Base = DefaultedComparisonVisitor;
8310 using Result = DefaultedComparisonInfo;
8311 using Subobject = DefaultedComparisonSubobject;
8312
8313 friend Base;
8314
8315 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8317 DiagnosticKind Diagnose = NoDiagnostics)
8318 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8319
8320 Result visit() {
8321 if ((DCK == DefaultedComparisonKind::Equal ||
8322 DCK == DefaultedComparisonKind::ThreeWay) &&
8323 RD->hasVariantMembers()) {
8324 // C++2a [class.compare.default]p2 [P2002R0]:
8325 // A defaulted comparison operator function for class C is defined as
8326 // deleted if [...] C has variant members.
8327 if (Diagnose == ExplainDeleted) {
8328 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8329 << FD << RD->isUnion() << RD;
8330 }
8331 return Result::deleted();
8332 }
8333
8334 return Base::visit();
8335 }
8336
8337private:
8338 Subobject getCompleteObject() {
8339 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8340 }
8341
8342 Subobject getBase(CXXBaseSpecifier *Base) {
8343 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8344 Base->getBaseTypeLoc()};
8345 }
8346
8347 Subobject getField(FieldDecl *Field) {
8348 return Subobject{Subobject::Member, Field, Field->getLocation()};
8349 }
8350
8351 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8352 // C++2a [class.compare.default]p2 [P2002R0]:
8353 // A defaulted <=> or == operator function for class C is defined as
8354 // deleted if any non-static data member of C is of reference type
8355 if (Type->isReferenceType()) {
8356 if (Diagnose == ExplainDeleted) {
8357 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8358 << FD << RD;
8359 }
8360 return Result::deleted();
8361 }
8362
8363 // [...] Let xi be an lvalue denoting the ith element [...]
8364 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8365 Expr *Args[] = {&Xi, &Xi};
8366
8367 // All operators start by trying to apply that same operator recursively.
8369 assert(OO != OO_None && "not an overloaded operator!");
8370 return visitBinaryOperator(OO, Args, Subobj);
8371 }
8372
8373 Result
8374 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8375 Subobject Subobj,
8376 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8377 // Note that there is no need to consider rewritten candidates here if
8378 // we've already found there is no viable 'operator<=>' candidate (and are
8379 // considering synthesizing a '<=>' from '==' and '<').
8380 OverloadCandidateSet CandidateSet(
8382 OverloadCandidateSet::OperatorRewriteInfo(
8383 OO, FD->getLocation(),
8384 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8385
8386 /// C++2a [class.compare.default]p1 [P2002R0]:
8387 /// [...] the defaulted function itself is never a candidate for overload
8388 /// resolution [...]
8389 CandidateSet.exclude(FD);
8390
8391 if (Args[0]->getType()->isOverloadableType())
8392 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8393 else
8394 // FIXME: We determine whether this is a valid expression by checking to
8395 // see if there's a viable builtin operator candidate for it. That isn't
8396 // really what the rules ask us to do, but should give the right results.
8397 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8398
8399 Result R;
8400
8402 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8403 case OR_Success: {
8404 // C++2a [class.compare.secondary]p2 [P2002R0]:
8405 // The operator function [...] is defined as deleted if [...] the
8406 // candidate selected by overload resolution is not a rewritten
8407 // candidate.
8408 if ((DCK == DefaultedComparisonKind::NotEqual ||
8409 DCK == DefaultedComparisonKind::Relational) &&
8410 !Best->RewriteKind) {
8411 if (Diagnose == ExplainDeleted) {
8412 if (Best->Function) {
8413 S.Diag(Best->Function->getLocation(),
8414 diag::note_defaulted_comparison_not_rewritten_callee)
8415 << FD;
8416 } else {
8417 assert(Best->Conversions.size() == 2 &&
8418 Best->Conversions[0].isUserDefined() &&
8419 "non-user-defined conversion from class to built-in "
8420 "comparison");
8421 S.Diag(Best->Conversions[0]
8422 .UserDefined.FoundConversionFunction.getDecl()
8423 ->getLocation(),
8424 diag::note_defaulted_comparison_not_rewritten_conversion)
8425 << FD;
8426 }
8427 }
8428 return Result::deleted();
8429 }
8430
8431 // Throughout C++2a [class.compare]: if overload resolution does not
8432 // result in a usable function, the candidate function is defined as
8433 // deleted. This requires that we selected an accessible function.
8434 //
8435 // Note that this only considers the access of the function when named
8436 // within the type of the subobject, and not the access path for any
8437 // derived-to-base conversion.
8438 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8439 if (ArgClass && Best->FoundDecl.getDecl() &&
8440 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8441 QualType ObjectType = Subobj.Kind == Subobject::Member
8442 ? Args[0]->getType()
8445 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8446 Diagnose == ExplainDeleted
8447 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8448 << FD << Subobj.Kind << Subobj.Decl
8449 : S.PDiag()))
8450 return Result::deleted();
8451 }
8452
8453 bool NeedsDeducing =
8454 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8455
8456 if (FunctionDecl *BestFD = Best->Function) {
8457 // C++2a [class.compare.default]p3 [P2002R0]:
8458 // A defaulted comparison function is constexpr-compatible if
8459 // [...] no overlod resolution performed [...] results in a
8460 // non-constexpr function.
8461 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8462 // If it's not constexpr, explain why not.
8463 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8464 if (Subobj.Kind != Subobject::CompleteObject)
8465 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8466 << Subobj.Kind << Subobj.Decl;
8467 S.Diag(BestFD->getLocation(),
8468 diag::note_defaulted_comparison_not_constexpr_here);
8469 // Bail out after explaining; we don't want any more notes.
8470 return Result::deleted();
8471 }
8472 R.Constexpr &= BestFD->isConstexpr();
8473
8474 if (NeedsDeducing) {
8475 // If any callee has an undeduced return type, deduce it now.
8476 // FIXME: It's not clear how a failure here should be handled. For
8477 // now, we produce an eager diagnostic, because that is forward
8478 // compatible with most (all?) other reasonable options.
8479 if (BestFD->getReturnType()->isUndeducedType() &&
8480 S.DeduceReturnType(BestFD, FD->getLocation(),
8481 /*Diagnose=*/false)) {
8482 // Don't produce a duplicate error when asked to explain why the
8483 // comparison is deleted: we diagnosed that when initially checking
8484 // the defaulted operator.
8485 if (Diagnose == NoDiagnostics) {
8486 S.Diag(
8487 FD->getLocation(),
8488 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8489 << Subobj.Kind << Subobj.Decl;
8490 S.Diag(
8491 Subobj.Loc,
8492 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8493 << Subobj.Kind << Subobj.Decl;
8494 S.Diag(BestFD->getLocation(),
8495 diag::note_defaulted_comparison_cannot_deduce_callee)
8496 << Subobj.Kind << Subobj.Decl;
8497 }
8498 return Result::deleted();
8499 }
8501 BestFD->getCallResultType());
8502 if (!Info) {
8503 if (Diagnose == ExplainDeleted) {
8504 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8505 << Subobj.Kind << Subobj.Decl
8506 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8507 S.Diag(BestFD->getLocation(),
8508 diag::note_defaulted_comparison_cannot_deduce_callee)
8509 << Subobj.Kind << Subobj.Decl;
8510 }
8511 return Result::deleted();
8512 }
8513 R.Category = Info->Kind;
8514 }
8515 } else {
8516 QualType T = Best->BuiltinParamTypes[0];
8517 assert(T == Best->BuiltinParamTypes[1] &&
8518 "builtin comparison for different types?");
8519 assert(Best->BuiltinParamTypes[2].isNull() &&
8520 "invalid builtin comparison");
8521
8522 // FIXME: If the type we deduced is a vector type, we mark the
8523 // comparison as deleted because we don't yet support this.
8524 if (isa<VectorType>(T)) {
8525 if (Diagnose == ExplainDeleted) {
8526 S.Diag(FD->getLocation(),
8527 diag::note_defaulted_comparison_vector_types)
8528 << FD;
8529 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8530 }
8531 return Result::deleted();
8532 }
8533
8534 if (NeedsDeducing) {
8535 std::optional<ComparisonCategoryType> Cat =
8537 assert(Cat && "no category for builtin comparison?");
8538 R.Category = *Cat;
8539 }
8540 }
8541
8542 // Note that we might be rewriting to a different operator. That call is
8543 // not considered until we come to actually build the comparison function.
8544 break;
8545 }
8546
8547 case OR_Ambiguous:
8548 if (Diagnose == ExplainDeleted) {
8549 unsigned Kind = 0;
8550 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8551 Kind = OO == OO_EqualEqual ? 1 : 2;
8552 CandidateSet.NoteCandidates(
8554 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8555 << FD << Kind << Subobj.Kind << Subobj.Decl),
8556 S, OCD_AmbiguousCandidates, Args);
8557 }
8558 R = Result::deleted();
8559 break;
8560
8561 case OR_Deleted:
8562 if (Diagnose == ExplainDeleted) {
8563 if ((DCK == DefaultedComparisonKind::NotEqual ||
8564 DCK == DefaultedComparisonKind::Relational) &&
8565 !Best->RewriteKind) {
8566 S.Diag(Best->Function->getLocation(),
8567 diag::note_defaulted_comparison_not_rewritten_callee)
8568 << FD;
8569 } else {
8570 S.Diag(Subobj.Loc,
8571 diag::note_defaulted_comparison_calls_deleted)
8572 << FD << Subobj.Kind << Subobj.Decl;
8573 S.NoteDeletedFunction(Best->Function);
8574 }
8575 }
8576 R = Result::deleted();
8577 break;
8578
8580 // If there's no usable candidate, we're done unless we can rewrite a
8581 // '<=>' in terms of '==' and '<'.
8582 if (OO == OO_Spaceship &&
8584 // For any kind of comparison category return type, we need a usable
8585 // '==' and a usable '<'.
8586 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8587 &CandidateSet)))
8588 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8589 break;
8590 }
8591
8592 if (Diagnose == ExplainDeleted) {
8593 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8594 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8595 << Subobj.Kind << Subobj.Decl;
8596
8597 // For a three-way comparison, list both the candidates for the
8598 // original operator and the candidates for the synthesized operator.
8599 if (SpaceshipCandidates) {
8600 SpaceshipCandidates->NoteCandidates(
8601 S, Args,
8602 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8603 Args, FD->getLocation()));
8604 S.Diag(Subobj.Loc,
8605 diag::note_defaulted_comparison_no_viable_function_synthesized)
8606 << (OO == OO_EqualEqual ? 0 : 1);
8607 }
8608
8609 CandidateSet.NoteCandidates(
8610 S, Args,
8611 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8612 FD->getLocation()));
8613 }
8614 R = Result::deleted();
8615 break;
8616 }
8617
8618 return R;
8619 }
8620};
8621
8622/// A list of statements.
8623struct StmtListResult {
8624 bool IsInvalid = false;
8625 llvm::SmallVector<Stmt*, 16> Stmts;
8626
8627 bool add(const StmtResult &S) {
8628 IsInvalid |= S.isInvalid();
8629 if (IsInvalid)
8630 return true;
8631 Stmts.push_back(S.get());
8632 return false;
8633 }
8634};
8635
8636/// A visitor over the notional body of a defaulted comparison that synthesizes
8637/// the actual body.
8638class DefaultedComparisonSynthesizer
8639 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8640 StmtListResult, StmtResult,
8641 std::pair<ExprResult, ExprResult>> {
8642 SourceLocation Loc;
8643 unsigned ArrayDepth = 0;
8644
8645public:
8646 using Base = DefaultedComparisonVisitor;
8647 using ExprPair = std::pair<ExprResult, ExprResult>;
8648
8649 friend Base;
8650
8651 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8653 SourceLocation BodyLoc)
8654 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8655
8656 /// Build a suitable function body for this defaulted comparison operator.
8657 StmtResult build() {
8658 Sema::CompoundScopeRAII CompoundScope(S);
8659
8660 StmtListResult Stmts = visit();
8661 if (Stmts.IsInvalid)
8662 return StmtError();
8663
8664 ExprResult RetVal;
8665 switch (DCK) {
8666 case DefaultedComparisonKind::None:
8667 llvm_unreachable("not a defaulted comparison");
8668
8669 case DefaultedComparisonKind::Equal: {
8670 // C++2a [class.eq]p3:
8671 // [...] compar[e] the corresponding elements [...] until the first
8672 // index i where xi == yi yields [...] false. If no such index exists,
8673 // V is true. Otherwise, V is false.
8674 //
8675 // Join the comparisons with '&&'s and return the result. Use a right
8676 // fold (traversing the conditions right-to-left), because that
8677 // short-circuits more naturally.
8678 auto OldStmts = std::move(Stmts.Stmts);
8679 Stmts.Stmts.clear();
8680 ExprResult CmpSoFar;
8681 // Finish a particular comparison chain.
8682 auto FinishCmp = [&] {
8683 if (Expr *Prior = CmpSoFar.get()) {
8684 // Convert the last expression to 'return ...;'
8685 if (RetVal.isUnset() && Stmts.Stmts.empty())
8686 RetVal = CmpSoFar;
8687 // Convert any prior comparison to 'if (!(...)) return false;'
8688 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8689 return true;
8690 CmpSoFar = ExprResult();
8691 }
8692 return false;
8693 };
8694 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8695 Expr *E = dyn_cast<Expr>(EAsStmt);
8696 if (!E) {
8697 // Found an array comparison.
8698 if (FinishCmp() || Stmts.add(EAsStmt))
8699 return StmtError();
8700 continue;
8701 }
8702
8703 if (CmpSoFar.isUnset()) {
8704 CmpSoFar = E;
8705 continue;
8706 }
8707 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8708 if (CmpSoFar.isInvalid())
8709 return StmtError();
8710 }
8711 if (FinishCmp())
8712 return StmtError();
8713 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8714 // If no such index exists, V is true.
8715 if (RetVal.isUnset())
8716 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8717 break;
8718 }
8719
8720 case DefaultedComparisonKind::ThreeWay: {
8721 // Per C++2a [class.spaceship]p3, as a fallback add:
8722 // return static_cast<R>(std::strong_ordering::equal);
8723 QualType StrongOrdering = S.CheckComparisonCategoryType(
8724 ComparisonCategoryType::StrongOrdering, Loc,
8725 Sema::ComparisonCategoryUsage::DefaultedOperator);
8726 if (StrongOrdering.isNull())
8727 return StmtError();
8728 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8729 .getValueInfo(ComparisonCategoryResult::Equal)
8730 ->VD;
8731 RetVal = getDecl(EqualVD);
8732 if (RetVal.isInvalid())
8733 return StmtError();
8734 RetVal = buildStaticCastToR(RetVal.get());
8735 break;
8736 }
8737
8738 case DefaultedComparisonKind::NotEqual:
8739 case DefaultedComparisonKind::Relational:
8740 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8741 break;
8742 }
8743
8744 // Build the final return statement.
8745 if (RetVal.isInvalid())
8746 return StmtError();
8747 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8748 if (ReturnStmt.isInvalid())
8749 return StmtError();
8750 Stmts.Stmts.push_back(ReturnStmt.get());
8751
8752 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8753 }
8754
8755private:
8756 ExprResult getDecl(ValueDecl *VD) {
8757 return S.BuildDeclarationNameExpr(
8758 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8759 }
8760
8761 ExprResult getParam(unsigned I) {
8762 ParmVarDecl *PD = FD->getParamDecl(I);
8763 return getDecl(PD);
8764 }
8765
8766 ExprPair getCompleteObject() {
8767 unsigned Param = 0;
8768 ExprResult LHS;
8769 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8770 MD && MD->isImplicitObjectMemberFunction()) {
8771 // LHS is '*this'.
8772 LHS = S.ActOnCXXThis(Loc);
8773 if (!LHS.isInvalid())
8774 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8775 } else {
8776 LHS = getParam(Param++);
8777 }
8778 ExprResult RHS = getParam(Param++);
8779 assert(Param == FD->getNumParams());
8780 return {LHS, RHS};
8781 }
8782
8783 ExprPair getBase(CXXBaseSpecifier *Base) {
8784 ExprPair Obj = getCompleteObject();
8785 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8786 return {ExprError(), ExprError()};
8787 CXXCastPath Path = {Base};
8788 const auto CastToBase = [&](Expr *E) {
8789 QualType ToType = S.Context.getQualifiedType(
8790 Base->getType(), E->getType().getQualifiers());
8791 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8792 };
8793 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8794 }
8795
8796 ExprPair getField(FieldDecl *Field) {
8797 ExprPair Obj = getCompleteObject();
8798 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8799 return {ExprError(), ExprError()};
8800
8801 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8802 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8803 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8804 CXXScopeSpec(), Field, Found, NameInfo),
8805 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8806 CXXScopeSpec(), Field, Found, NameInfo)};
8807 }
8808
8809 // FIXME: When expanding a subobject, register a note in the code synthesis
8810 // stack to say which subobject we're comparing.
8811
8812 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8813 if (Cond.isInvalid())
8814 return StmtError();
8815
8816 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8817 if (NotCond.isInvalid())
8818 return StmtError();
8819
8820 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8821 assert(!False.isInvalid() && "should never fail");
8822 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8823 if (ReturnFalse.isInvalid())
8824 return StmtError();
8825
8826 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8827 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8828 Sema::ConditionKind::Boolean),
8829 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8830 }
8831
8832 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8833 ExprPair Subobj) {
8834 QualType SizeType = S.Context.getSizeType();
8835 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8836
8837 // Build 'size_t i$n = 0'.
8838 IdentifierInfo *IterationVarName = nullptr;
8839 {
8840 SmallString<8> Str;
8841 llvm::raw_svector_ostream OS(Str);
8842 OS << "i" << ArrayDepth;
8843 IterationVarName = &S.Context.Idents.get(OS.str());
8844 }
8845 VarDecl *IterationVar = VarDecl::Create(
8846 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8847 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8848 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8849 IterationVar->setInit(
8850 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8851 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8852
8853 auto IterRef = [&] {
8854 ExprResult Ref = S.BuildDeclarationNameExpr(
8855 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8856 IterationVar);
8857 assert(!Ref.isInvalid() && "can't reference our own variable?");
8858 return Ref.get();
8859 };
8860
8861 // Build 'i$n != Size'.
8862 ExprResult Cond = S.CreateBuiltinBinOp(
8863 Loc, BO_NE, IterRef(),
8864 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8865 assert(!Cond.isInvalid() && "should never fail");
8866
8867 // Build '++i$n'.
8868 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8869 assert(!Inc.isInvalid() && "should never fail");
8870
8871 // Build 'a[i$n]' and 'b[i$n]'.
8872 auto Index = [&](ExprResult E) {
8873 if (E.isInvalid())
8874 return ExprError();
8875 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8876 };
8877 Subobj.first = Index(Subobj.first);
8878 Subobj.second = Index(Subobj.second);
8879
8880 // Compare the array elements.
8881 ++ArrayDepth;
8882 StmtResult Substmt = visitSubobject(Type, Subobj);
8883 --ArrayDepth;
8884
8885 if (Substmt.isInvalid())
8886 return StmtError();
8887
8888 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8889 // For outer levels or for an 'operator<=>' we already have a suitable
8890 // statement that returns as necessary.
8891 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8892 assert(DCK == DefaultedComparisonKind::Equal &&
8893 "should have non-expression statement");
8894 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8895 if (Substmt.isInvalid())
8896 return StmtError();
8897 }
8898
8899 // Build 'for (...) ...'
8900 return S.ActOnForStmt(Loc, Loc, Init,
8901 S.ActOnCondition(nullptr, Loc, Cond.get(),
8902 Sema::ConditionKind::Boolean),
8903 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8904 Substmt.get());
8905 }
8906
8907 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8908 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8909 return StmtError();
8910
8913 ExprResult Op;
8914 if (Type->isOverloadableType())
8915 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8916 Obj.second.get(), /*PerformADL=*/true,
8917 /*AllowRewrittenCandidates=*/true, FD);
8918 else
8919 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8920 if (Op.isInvalid())
8921 return StmtError();
8922
8923 switch (DCK) {
8924 case DefaultedComparisonKind::None:
8925 llvm_unreachable("not a defaulted comparison");
8926
8927 case DefaultedComparisonKind::Equal:
8928 // Per C++2a [class.eq]p2, each comparison is individually contextually
8929 // converted to bool.
8930 Op = S.PerformContextuallyConvertToBool(Op.get());
8931 if (Op.isInvalid())
8932 return StmtError();
8933 return Op.get();
8934
8935 case DefaultedComparisonKind::ThreeWay: {
8936 // Per C++2a [class.spaceship]p3, form:
8937 // if (R cmp = static_cast<R>(op); cmp != 0)
8938 // return cmp;
8939 QualType R = FD->getReturnType();
8940 Op = buildStaticCastToR(Op.get());
8941 if (Op.isInvalid())
8942 return StmtError();
8943
8944 // R cmp = ...;
8945 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8946 VarDecl *VD =
8947 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8948 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8949 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8950 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8951
8952 // cmp != 0
8953 ExprResult VDRef = getDecl(VD);
8954 if (VDRef.isInvalid())
8955 return StmtError();
8956 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8957 Expr *Zero =
8958 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8960 if (VDRef.get()->getType()->isOverloadableType())
8961 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8962 true, FD);
8963 else
8964 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8965 if (Comp.isInvalid())
8966 return StmtError();
8967 Sema::ConditionResult Cond = S.ActOnCondition(
8968 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8969 if (Cond.isInvalid())
8970 return StmtError();
8971
8972 // return cmp;
8973 VDRef = getDecl(VD);
8974 if (VDRef.isInvalid())
8975 return StmtError();
8976 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8977 if (ReturnStmt.isInvalid())
8978 return StmtError();
8979
8980 // if (...)
8981 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8982 Loc, ReturnStmt.get(),
8983 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8984 }
8985
8986 case DefaultedComparisonKind::NotEqual:
8987 case DefaultedComparisonKind::Relational:
8988 // C++2a [class.compare.secondary]p2:
8989 // Otherwise, the operator function yields x @ y.
8990 return Op.get();
8991 }
8992 llvm_unreachable("");
8993 }
8994
8995 /// Build "static_cast<R>(E)".
8996 ExprResult buildStaticCastToR(Expr *E) {
8997 QualType R = FD->getReturnType();
8998 assert(!R->isUndeducedType() && "type should have been deduced already");
8999
9000 // Don't bother forming a no-op cast in the common case.
9001 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
9002 return E;
9003 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
9004 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
9005 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
9006 }
9007};
9008}
9009
9010/// Perform the unqualified lookups that might be needed to form a defaulted
9011/// comparison function for the given operator.
9013 UnresolvedSetImpl &Operators,
9015 auto Lookup = [&](OverloadedOperatorKind OO) {
9016 Self.LookupOverloadedOperatorName(OO, S, Operators);
9017 };
9018
9019 // Every defaulted operator looks up itself.
9020 Lookup(Op);
9021 // ... and the rewritten form of itself, if any.
9023 Lookup(ExtraOp);
9024
9025 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9026 // synthesize a three-way comparison from '<' and '=='. In a dependent
9027 // context, we also need to look up '==' in case we implicitly declare a
9028 // defaulted 'operator=='.
9029 if (Op == OO_Spaceship) {
9030 Lookup(OO_ExclaimEqual);
9031 Lookup(OO_Less);
9032 Lookup(OO_EqualEqual);
9033 }
9034}
9035
9038 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9039
9040 // Perform any unqualified lookups we're going to need to default this
9041 // function.
9042 if (S) {
9043 UnresolvedSet<32> Operators;
9044 lookupOperatorsForDefaultedComparison(*this, S, Operators,
9045 FD->getOverloadedOperator());
9048 Context, Operators.pairs(), CurFPFeatureOverrides()));
9049 }
9050
9051 // C++2a [class.compare.default]p1:
9052 // A defaulted comparison operator function for some class C shall be a
9053 // non-template function declared in the member-specification of C that is
9054 // -- a non-static const non-volatile member of C having one parameter of
9055 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9056 // -- a friend of C having two parameters of type const C& or two
9057 // parameters of type C.
9058
9059 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
9060 bool IsMethod = isa<CXXMethodDecl>(FD);
9061 if (IsMethod) {
9062 auto *MD = cast<CXXMethodDecl>(FD);
9063 assert(!MD->isStatic() && "comparison function cannot be a static member");
9064
9065 if (MD->getRefQualifier() == RQ_RValue) {
9066 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
9067
9068 // Remove the ref qualifier to recover.
9069 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9070 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9071 EPI.RefQualifier = RQ_None;
9072 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9073 FPT->getParamTypes(), EPI));
9074 }
9075
9076 // If we're out-of-class, this is the class we're comparing.
9077 if (!RD)
9078 RD = MD->getParent();
9079 QualType T = MD->getFunctionObjectParameterReferenceType();
9080 if (!T.getNonReferenceType().isConstQualified() &&
9081 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9082 SourceLocation Loc, InsertLoc;
9083 if (MD->isExplicitObjectMemberFunction()) {
9084 Loc = MD->getParamDecl(0)->getBeginLoc();
9085 InsertLoc = getLocForEndOfToken(
9086 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
9087 } else {
9088 Loc = MD->getLocation();
9089 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9090 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
9091 }
9092 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9093 // corresponding defaulted 'operator<=>' already.
9094 if (!MD->isImplicit()) {
9095 Diag(Loc, diag::err_defaulted_comparison_non_const)
9096 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
9097 }
9098
9099 // Add the 'const' to the type to recover.
9100 if (MD->isExplicitObjectMemberFunction()) {
9101 assert(T->isLValueReferenceType());
9102 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
9103 T.getNonReferenceType().withConst()));
9104 } else {
9105 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9106 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9107 EPI.TypeQuals.addConst();
9108 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9109 FPT->getParamTypes(), EPI));
9110 }
9111 }
9112
9113 if (MD->isVolatile()) {
9114 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
9115
9116 // Remove the 'volatile' from the type to recover.
9117 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9118 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9120 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9121 FPT->getParamTypes(), EPI));
9122 }
9123 }
9124
9125 if ((FD->getNumParams() -
9126 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9127 (IsMethod ? 1 : 2)) {
9128 // Let's not worry about using a variadic template pack here -- who would do
9129 // such a thing?
9130 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
9131 << int(IsMethod) << int(DCK);
9132 return true;
9133 }
9134
9135 const ParmVarDecl *KnownParm = nullptr;
9136 for (const ParmVarDecl *Param : FD->parameters()) {
9137 QualType ParmTy = Param->getType();
9138 if (!KnownParm) {
9139 auto CTy = ParmTy;
9140 // Is it `T const &`?
9141 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9142 QualType ExpectedTy;
9143 if (RD)
9144 ExpectedTy = Context.getCanonicalTagType(RD);
9145 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9146 CTy = Ref->getPointeeType();
9147 if (RD)
9148 ExpectedTy.addConst();
9149 Ok = true;
9150 }
9151
9152 // Is T a class?
9153 if (RD) {
9154 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
9155 } else {
9156 RD = CTy->getAsCXXRecordDecl();
9157 Ok &= RD != nullptr;
9158 }
9159
9160 if (Ok) {
9161 KnownParm = Param;
9162 } else {
9163 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9164 // corresponding defaulted 'operator<=>' already.
9165 if (!FD->isImplicit()) {
9166 if (RD) {
9167 CanQualType PlainTy = Context.getCanonicalTagType(RD);
9168 QualType RefTy =
9169 Context.getLValueReferenceType(PlainTy.withConst());
9170 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9171 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9172 << Param->getSourceRange();
9173 } else {
9174 assert(!IsMethod && "should know expected type for method");
9175 Diag(FD->getLocation(),
9176 diag::err_defaulted_comparison_param_unknown)
9177 << int(DCK) << ParmTy << Param->getSourceRange();
9178 }
9179 }
9180 return true;
9181 }
9182 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9183 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9184 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9185 << ParmTy << Param->getSourceRange();
9186 return true;
9187 }
9188 }
9189
9190 assert(RD && "must have determined class");
9191 if (IsMethod) {
9192 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9193 // In-class, must be a friend decl.
9194 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9195 } else {
9196 // Out of class, require the defaulted comparison to be a friend (of a
9197 // complete type, per CWG2547).
9198 if (RequireCompleteType(FD->getLocation(), Context.getCanonicalTagType(RD),
9199 diag::err_defaulted_comparison_not_friend, int(DCK),
9200 int(1)))
9201 return true;
9202
9203 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9204 return declaresSameEntity(F->getFriendDecl(), FD);
9205 })) {
9206 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9207 << int(DCK) << int(0) << RD;
9208 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9209 return true;
9210 }
9211 }
9212
9213 // C++2a [class.eq]p1, [class.rel]p1:
9214 // A [defaulted comparison other than <=>] shall have a declared return
9215 // type bool.
9218 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9219 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9220 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9221 << FD->getReturnTypeSourceRange();
9222 return true;
9223 }
9224 // C++2a [class.spaceship]p2 [P2002R0]:
9225 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9226 // R shall not contain a placeholder type.
9227 if (QualType RT = FD->getDeclaredReturnType();
9229 RT->getContainedDeducedType() &&
9230 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
9231 RT->getContainedAutoType()->isConstrained())) {
9232 Diag(FD->getLocation(),
9233 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9234 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9235 << FD->getReturnTypeSourceRange();
9236 return true;
9237 }
9238
9239 // For a defaulted function in a dependent class, defer all remaining checks
9240 // until instantiation.
9241 if (RD->isDependentType())
9242 return false;
9243
9244 // Determine whether the function should be defined as deleted.
9245 DefaultedComparisonInfo Info =
9246 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9247
9248 bool First = FD == FD->getCanonicalDecl();
9249
9250 if (!First) {
9251 if (Info.Deleted) {
9252 // C++11 [dcl.fct.def.default]p4:
9253 // [For a] user-provided explicitly-defaulted function [...] if such a
9254 // function is implicitly defined as deleted, the program is ill-formed.
9255 //
9256 // This is really just a consequence of the general rule that you can
9257 // only delete a function on its first declaration.
9258 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9259 << FD->isImplicit() << (int)DCK;
9260 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9261 DefaultedComparisonAnalyzer::ExplainDeleted)
9262 .visit();
9263 return true;
9264 }
9266 // C++20 [class.compare.default]p1:
9267 // [...] A definition of a comparison operator as defaulted that appears
9268 // in a class shall be the first declaration of that function.
9269 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9270 << (int)DCK;
9272 diag::note_previous_declaration);
9273 return true;
9274 }
9275 }
9276
9277 // If we want to delete the function, then do so; there's nothing else to
9278 // check in that case.
9279 if (Info.Deleted) {
9280 SetDeclDeleted(FD, FD->getLocation());
9281 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9282 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9283 << (int)DCK;
9284 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9285 DefaultedComparisonAnalyzer::ExplainDeleted)
9286 .visit();
9287 if (FD->getDefaultLoc().isValid())
9288 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9289 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9290 }
9291 return false;
9292 }
9293
9294 // C++2a [class.spaceship]p2:
9295 // The return type is deduced as the common comparison type of R0, R1, ...
9299 if (RetLoc.isInvalid())
9300 RetLoc = FD->getBeginLoc();
9301 // FIXME: Should we really care whether we have the complete type and the
9302 // 'enumerator' constants here? A forward declaration seems sufficient.
9304 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9305 if (Cat.isNull())
9306 return true;
9307 Context.adjustDeducedFunctionResultType(
9308 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9309 }
9310
9311 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9312 // An explicitly-defaulted function that is not defined as deleted may be
9313 // declared constexpr or consteval only if it is constexpr-compatible.
9314 // C++2a [class.compare.default]p3 [P2002R0]:
9315 // A defaulted comparison function is constexpr-compatible if it satisfies
9316 // the requirements for a constexpr function [...]
9317 // The only relevant requirements are that the parameter and return types are
9318 // literal types. The remaining conditions are checked by the analyzer.
9319 //
9320 // We support P2448R2 in language modes earlier than C++23 as an extension.
9321 // The concept of constexpr-compatible was removed.
9322 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9323 // A function explicitly defaulted on its first declaration is implicitly
9324 // inline, and is implicitly constexpr if it is constexpr-suitable.
9325 // C++23 [dcl.constexpr]p3
9326 // A function is constexpr-suitable if
9327 // - it is not a coroutine, and
9328 // - if the function is a constructor or destructor, its class does not
9329 // have any virtual base classes.
9330 if (FD->isConstexpr()) {
9331 if (!getLangOpts().CPlusPlus23 &&
9334 !Info.Constexpr) {
9335 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9336 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9337 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9338 DefaultedComparisonAnalyzer::ExplainConstexpr)
9339 .visit();
9340 }
9341 }
9342
9343 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9344 // If a constexpr-compatible function is explicitly defaulted on its first
9345 // declaration, it is implicitly considered to be constexpr.
9346 // FIXME: Only applying this to the first declaration seems problematic, as
9347 // simple reorderings can affect the meaning of the program.
9348 if (First && !FD->isConstexpr() && Info.Constexpr)
9350
9351 // C++2a [except.spec]p3:
9352 // If a declaration of a function does not have a noexcept-specifier
9353 // [and] is defaulted on its first declaration, [...] the exception
9354 // specification is as specified below
9355 if (FD->getExceptionSpecType() == EST_None) {
9356 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9357 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9359 EPI.ExceptionSpec.SourceDecl = FD;
9360 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9361 FPT->getParamTypes(), EPI));
9362 }
9363
9364 return false;
9365}
9366
9368 FunctionDecl *Spaceship) {
9371 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9372 Ctx.Entity = Spaceship;
9374
9375 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9376 EqualEqual->setImplicit();
9377
9379}
9380
9383 assert(FD->isDefaulted() && !FD->isDeleted() &&
9385 if (FD->willHaveBody() || FD->isInvalidDecl())
9386 return;
9387
9389
9390 // Add a context note for diagnostics produced after this point.
9391 Scope.addContextNote(UseLoc);
9392
9393 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, FD);
9394
9395 {
9396 // Build and set up the function body.
9397 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9398 // the type of the class being compared.
9399 auto PT = FD->getParamDecl(0)->getType();
9400 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9401 SourceLocation BodyLoc =
9402 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9403 StmtResult Body =
9404 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9405 if (Body.isInvalid()) {
9406 FD->setInvalidDecl();
9407 return;
9408 }
9409 FD->setBody(Body.get());
9410 FD->markUsed(Context);
9411 }
9412
9413 // The exception specification is needed because we are defining the
9414 // function. Note that this will reuse the body we just built.
9416
9418 L->CompletedImplicitDefinition(FD);
9419}
9420
9423 FunctionDecl *FD,
9425 ComputingExceptionSpec CES(S, FD, Loc);
9427
9428 if (FD->isInvalidDecl())
9429 return ExceptSpec;
9430
9431 // The common case is that we just defined the comparison function. In that
9432 // case, just look at whether the body can throw.
9433 if (Stmt *FunctionBody = FD->getBody()) {
9434 ExceptSpec.CalledStmt(FunctionBody);
9435 } else {
9436 // Otherwise, build a body so we can check it. This should ideally only
9437 // happen when we're not actually marking the function referenced. (This is
9438 // only really important for efficiency: we don't want to build and throw
9439 // away bodies for comparison functions more than we strictly need to.)
9440
9441 // Pretend to synthesize the function body in an unevaluated context.
9442 // Note that we can't actually just go ahead and define the function here:
9443 // we are not permitted to mark its callees as referenced.
9447
9448 CXXRecordDecl *RD =
9450 ? FD->getDeclContext()
9451 : FD->getLexicalDeclContext());
9452 SourceLocation BodyLoc =
9453 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9454 StmtResult Body =
9455 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9456 if (!Body.isInvalid())
9457 ExceptSpec.CalledStmt(Body.get());
9458
9459 // FIXME: Can we hold onto this body and just transform it to potentially
9460 // evaluated when we're asked to define the function rather than rebuilding
9461 // it? Either that, or we should only build the bits of the body that we
9462 // need (the expressions, not the statements).
9463 }
9464
9465 return ExceptSpec;
9466}
9467
9469 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9471
9472 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9474
9475 // Perform any deferred checking of exception specifications for virtual
9476 // destructors.
9477 for (auto &Check : Overriding)
9478 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9479
9480 // Perform any deferred checking of exception specifications for befriended
9481 // special members.
9482 for (auto &Check : Equivalent)
9483 CheckEquivalentExceptionSpec(Check.second, Check.first);
9484}
9485
9486namespace {
9487/// CRTP base class for visiting operations performed by a special member
9488/// function (or inherited constructor).
9489template<typename Derived>
9490struct SpecialMemberVisitor {
9491 Sema &S;
9492 CXXMethodDecl *MD;
9495
9496 // Properties of the special member, computed for convenience.
9497 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9498
9499 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9501 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9502 switch (CSM) {
9506 IsConstructor = true;
9507 break;
9510 IsAssignment = true;
9511 break;
9513 break;
9515 llvm_unreachable("invalid special member kind");
9516 }
9517
9518 if (MD->getNumExplicitParams()) {
9519 if (const ReferenceType *RT =
9520 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9521 ConstArg = RT->getPointeeType().isConstQualified();
9522 }
9523 }
9524
9525 Derived &getDerived() { return static_cast<Derived&>(*this); }
9526
9527 /// Is this a "move" special member?
9528 bool isMove() const {
9529 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9530 CSM == CXXSpecialMemberKind::MoveAssignment;
9531 }
9532
9533 /// Look up the corresponding special member in the given class.
9534 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9535 unsigned Quals, bool IsMutable) {
9536 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9537 ConstArg && !IsMutable);
9538 }
9539
9540 /// Look up the constructor for the specified base class to see if it's
9541 /// overridden due to this being an inherited constructor.
9542 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9543 if (!ICI)
9544 return {};
9545 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9546 auto *BaseCtor =
9547 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9548 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9549 return MD;
9550 return {};
9551 }
9552
9553 /// A base or member subobject.
9554 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9555
9556 /// Get the location to use for a subobject in diagnostics.
9557 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9558 // FIXME: For an indirect virtual base, the direct base leading to
9559 // the indirect virtual base would be a more useful choice.
9560 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
9561 return B->getBaseTypeLoc();
9562 else
9563 return cast<FieldDecl *>(Subobj)->getLocation();
9564 }
9565
9566 enum BasesToVisit {
9567 /// Visit all non-virtual (direct) bases.
9568 VisitNonVirtualBases,
9569 /// Visit all direct bases, virtual or not.
9570 VisitDirectBases,
9571 /// Visit all non-virtual bases, and all virtual bases if the class
9572 /// is not abstract.
9573 VisitPotentiallyConstructedBases,
9574 /// Visit all direct or virtual bases.
9575 VisitAllBases
9576 };
9577
9578 // Visit the bases and members of the class.
9579 bool visit(BasesToVisit Bases) {
9580 CXXRecordDecl *RD = MD->getParent();
9581
9582 if (Bases == VisitPotentiallyConstructedBases)
9583 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9584
9585 for (auto &B : RD->bases())
9586 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9587 getDerived().visitBase(&B))
9588 return true;
9589
9590 if (Bases == VisitAllBases)
9591 for (auto &B : RD->vbases())
9592 if (getDerived().visitBase(&B))
9593 return true;
9594
9595 for (auto *F : RD->fields())
9596 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9597 getDerived().visitField(F))
9598 return true;
9599
9600 return false;
9601 }
9602};
9603}
9604
9605namespace {
9606struct SpecialMemberDeletionInfo
9607 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9608 bool Diagnose;
9609
9610 SourceLocation Loc;
9611
9612 bool AllFieldsAreConst;
9613
9614 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9616 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9617 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9618 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9619
9620 bool inUnion() const { return MD->getParent()->isUnion(); }
9621
9622 CXXSpecialMemberKind getEffectiveCSM() {
9623 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9624 }
9625
9626 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9627
9628 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9629
9630 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9631 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9632
9633 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9634 bool shouldDeleteForField(FieldDecl *FD);
9635 bool shouldDeleteForAllConstMembers();
9636
9637 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9638 unsigned Quals);
9639 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9640 Sema::SpecialMemberOverloadResult SMOR,
9641 bool IsDtorCallInCtor);
9642
9643 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9644};
9645}
9646
9647/// Is the given special member inaccessible when used on the given
9648/// sub-object.
9649bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9650 CXXMethodDecl *target) {
9651 /// If we're operating on a base class, the object type is the
9652 /// type of this special member.
9653 CanQualType objectTy;
9654 AccessSpecifier access = target->getAccess();
9655 if (CXXBaseSpecifier *base = dyn_cast<CXXBaseSpecifier *>(Subobj)) {
9656 objectTy = S.Context.getCanonicalTagType(MD->getParent());
9657 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9658
9659 // If we're operating on a field, the object type is the type of the field.
9660 } else {
9661 objectTy = S.Context.getCanonicalTagType(target->getParent());
9662 }
9663
9665 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9666}
9667
9668/// Check whether we should delete a special member due to the implicit
9669/// definition containing a call to a special member of a subobject.
9670bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9671 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9672 bool IsDtorCallInCtor) {
9673 CXXMethodDecl *Decl = SMOR.getMethod();
9674 FieldDecl *Field = dyn_cast<FieldDecl *>(Subobj);
9675
9676 enum {
9677 NotSet = -1,
9678 NoDecl,
9679 DeletedDecl,
9680 MultipleDecl,
9681 InaccessibleDecl,
9682 NonTrivialDecl
9683 } DiagKind = NotSet;
9684
9686 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9687 Field->getParent()->isUnion()) {
9688 // [class.default.ctor]p2:
9689 // A defaulted default constructor for class X is defined as deleted if
9690 // - X is a union that has a variant member with a non-trivial default
9691 // constructor and no variant member of X has a default member
9692 // initializer
9693 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9694 if (RD->hasInClassInitializer())
9695 return false;
9696 }
9697 DiagKind = !Decl ? NoDecl : DeletedDecl;
9699 DiagKind = MultipleDecl;
9700 else if (!isAccessible(Subobj, Decl))
9701 DiagKind = InaccessibleDecl;
9702 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9703 !Decl->isTrivial()) {
9704 // A member of a union must have a trivial corresponding special member.
9705 // As a weird special case, a destructor call from a union's constructor
9706 // must be accessible and non-deleted, but need not be trivial. Such a
9707 // destructor is never actually called, but is semantically checked as
9708 // if it were.
9709 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9710 // [class.default.ctor]p2:
9711 // A defaulted default constructor for class X is defined as deleted if
9712 // - X is a union that has a variant member with a non-trivial default
9713 // constructor and no variant member of X has a default member
9714 // initializer
9715 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9716 if (!RD->hasInClassInitializer())
9717 DiagKind = NonTrivialDecl;
9718 } else {
9719 DiagKind = NonTrivialDecl;
9720 }
9721 }
9722
9723 if (DiagKind == NotSet)
9724 return false;
9725
9726 if (Diagnose) {
9727 if (Field) {
9728 S.Diag(Field->getLocation(),
9729 diag::note_deleted_special_member_class_subobject)
9730 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9731 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9732 } else {
9733 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9734 S.Diag(Base->getBeginLoc(),
9735 diag::note_deleted_special_member_class_subobject)
9736 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9737 << Base->getType() << DiagKind << IsDtorCallInCtor
9738 << /*IsObjCPtr*/ false;
9739 }
9740
9741 if (DiagKind == DeletedDecl)
9742 S.NoteDeletedFunction(Decl);
9743 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9744 }
9745
9746 return true;
9747}
9748
9749/// Check whether we should delete a special member function due to having a
9750/// direct or virtual base class or non-static data member of class type M.
9751bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9752 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9753 FieldDecl *Field = dyn_cast<FieldDecl *>(Subobj);
9754 bool IsMutable = Field && Field->isMutable();
9755
9756 // C++11 [class.ctor]p5:
9757 // -- any direct or virtual base class, or non-static data member with no
9758 // brace-or-equal-initializer, has class type M (or array thereof) and
9759 // either M has no default constructor or overload resolution as applied
9760 // to M's default constructor results in an ambiguity or in a function
9761 // that is deleted or inaccessible
9762 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9763 // -- a direct or virtual base class B that cannot be copied/moved because
9764 // overload resolution, as applied to B's corresponding special member,
9765 // results in an ambiguity or a function that is deleted or inaccessible
9766 // from the defaulted special member
9767 // C++11 [class.dtor]p5:
9768 // -- any direct or virtual base class [...] has a type with a destructor
9769 // that is deleted or inaccessible
9770 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9771 Field->hasInClassInitializer()) &&
9772 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9773 false))
9774 return true;
9775
9776 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9777 // -- any direct or virtual base class or non-static data member has a
9778 // type with a destructor that is deleted or inaccessible
9779 if (IsConstructor) {
9780 Sema::SpecialMemberOverloadResult SMOR =
9781 S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
9782 false, false, false, false);
9783 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9784 return true;
9785 }
9786
9787 return false;
9788}
9789
9790bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9791 FieldDecl *FD, QualType FieldType) {
9792 // The defaulted special functions are defined as deleted if this is a variant
9793 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9794 // type under ARC.
9795 if (!FieldType.hasNonTrivialObjCLifetime())
9796 return false;
9797
9798 // Don't make the defaulted default constructor defined as deleted if the
9799 // member has an in-class initializer.
9800 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9802 return false;
9803
9804 if (Diagnose) {
9805 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9806 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9807 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9808 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9809 }
9810
9811 return true;
9812}
9813
9814bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9815 const FieldDecl *FD) {
9816 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9817 // Copy/move constructors/assignment operators are deleted if the field has an
9818 // address-discriminated ptrauth qualifier.
9819 PointerAuthQualifier Q = FieldType.getPointerAuth();
9820
9821 if (!Q || !Q.isAddressDiscriminated())
9822 return false;
9823
9824 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9825 CSM == CXXSpecialMemberKind::Destructor)
9826 return false;
9827
9828 if (Diagnose) {
9829 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9830 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9831 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9832 << /*IsDtorCallInCtor*/ false << 2;
9833 }
9834
9835 return true;
9836}
9837
9838/// Check whether we should delete a special member function due to the class
9839/// having a particular direct or virtual base class.
9840bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9841 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9842 // If program is correct, BaseClass cannot be null, but if it is, the error
9843 // must be reported elsewhere.
9844 if (!BaseClass)
9845 return false;
9846 // If we have an inheriting constructor, check whether we're calling an
9847 // inherited constructor instead of a default constructor.
9848 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9849 if (auto *BaseCtor = SMOR.getMethod()) {
9850 // Note that we do not check access along this path; other than that,
9851 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9852 // FIXME: Check that the base has a usable destructor! Sink this into
9853 // shouldDeleteForClassSubobject.
9854 if (BaseCtor->isDeleted() && Diagnose) {
9855 S.Diag(Base->getBeginLoc(),
9856 diag::note_deleted_special_member_class_subobject)
9857 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9858 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9859 << /*IsObjCPtr*/ false;
9860 S.NoteDeletedFunction(BaseCtor);
9861 }
9862 return BaseCtor->isDeleted();
9863 }
9864 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9865}
9866
9867/// Check whether we should delete a special member function due to the class
9868/// having a particular non-static data member.
9869bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9870 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9871 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9872
9873 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9874 return true;
9875
9876 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9877 return true;
9878
9879 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9880 // For a default constructor, all references must be initialized in-class
9881 // and, if a union, it must have a non-const member.
9882 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9883 if (Diagnose)
9884 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9885 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9886 return true;
9887 }
9888 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9889 // data member of const-qualified type (or array thereof) with no
9890 // brace-or-equal-initializer is not const-default-constructible.
9891 if (!inUnion() && FieldType.isConstQualified() &&
9892 !FD->hasInClassInitializer() &&
9893 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9894 if (Diagnose)
9895 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9896 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9897 return true;
9898 }
9899
9900 if (inUnion() && !FieldType.isConstQualified())
9901 AllFieldsAreConst = false;
9902 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9903 // For a copy constructor, data members must not be of rvalue reference
9904 // type.
9905 if (FieldType->isRValueReferenceType()) {
9906 if (Diagnose)
9907 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9908 << MD->getParent() << FD << FieldType;
9909 return true;
9910 }
9911 } else if (IsAssignment) {
9912 // For an assignment operator, data members must not be of reference type.
9913 if (FieldType->isReferenceType()) {
9914 if (Diagnose)
9915 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9916 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9917 return true;
9918 }
9919 if (!FieldRecord && FieldType.isConstQualified()) {
9920 // C++11 [class.copy]p23:
9921 // -- a non-static data member of const non-class type (or array thereof)
9922 if (Diagnose)
9923 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9924 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9925 return true;
9926 }
9927 }
9928
9929 if (FieldRecord) {
9930 // Some additional restrictions exist on the variant members.
9931 if (!inUnion() && FieldRecord->isUnion() &&
9932 FieldRecord->isAnonymousStructOrUnion()) {
9933 bool AllVariantFieldsAreConst = true;
9934
9935 // FIXME: Handle anonymous unions declared within anonymous unions.
9936 for (auto *UI : FieldRecord->fields()) {
9937 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9938
9939 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9940 return true;
9941
9942 if (shouldDeleteForVariantPtrAuthMember(&*UI))
9943 return true;
9944
9945 if (!UnionFieldType.isConstQualified())
9946 AllVariantFieldsAreConst = false;
9947
9948 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9949 if (UnionFieldRecord &&
9950 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9951 UnionFieldType.getCVRQualifiers()))
9952 return true;
9953 }
9954
9955 // At least one member in each anonymous union must be non-const
9956 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9957 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9958 if (Diagnose)
9959 S.Diag(FieldRecord->getLocation(),
9960 diag::note_deleted_default_ctor_all_const)
9961 << !!ICI << MD->getParent() << /*anonymous union*/1;
9962 return true;
9963 }
9964
9965 // Don't check the implicit member of the anonymous union type.
9966 // This is technically non-conformant but supported, and we have a
9967 // diagnostic for this elsewhere.
9968 return false;
9969 }
9970
9971 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9972 FieldType.getCVRQualifiers()))
9973 return true;
9974 }
9975
9976 return false;
9977}
9978
9979/// C++11 [class.ctor] p5:
9980/// A defaulted default constructor for a class X is defined as deleted if
9981/// X is a union and all of its variant members are of const-qualified type.
9982bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9983 // This is a silly definition, because it gives an empty union a deleted
9984 // default constructor. Don't do that.
9985 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9986 AllFieldsAreConst) {
9987 bool AnyFields = false;
9988 for (auto *F : MD->getParent()->fields())
9989 if ((AnyFields = !F->isUnnamedBitField()))
9990 break;
9991 if (!AnyFields)
9992 return false;
9993 if (Diagnose)
9994 S.Diag(MD->getParent()->getLocation(),
9995 diag::note_deleted_default_ctor_all_const)
9996 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9997 return true;
9998 }
9999 return false;
10000}
10001
10002/// Determine whether a defaulted special member function should be defined as
10003/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
10004/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
10008 bool Diagnose) {
10009 if (MD->isInvalidDecl())
10010 return false;
10011 CXXRecordDecl *RD = MD->getParent();
10012 assert(!RD->isDependentType() && "do deletion after instantiation");
10013 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
10014 RD->isInvalidDecl())
10015 return false;
10016
10017 // C++11 [expr.lambda.prim]p19:
10018 // The closure type associated with a lambda-expression has a
10019 // deleted (8.4.3) default constructor and a deleted copy
10020 // assignment operator.
10021 // C++2a adds back these operators if the lambda has no lambda-capture.
10025 if (Diagnose)
10026 Diag(RD->getLocation(), diag::note_lambda_decl);
10027 return true;
10028 }
10029
10030 // C++11 [class.copy]p7, p18:
10031 // If the class definition declares a move constructor or move assignment
10032 // operator, an implicitly declared copy constructor or copy assignment
10033 // operator is defined as deleted.
10036 CXXMethodDecl *UserDeclaredMove = nullptr;
10037
10038 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10039 // deletion of the corresponding copy operation, not both copy operations.
10040 // MSVC 2015 has adopted the standards conforming behavior.
10041 bool DeletesOnlyMatchingCopy =
10042 getLangOpts().MSVCCompat &&
10043 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
10044
10046 (!DeletesOnlyMatchingCopy ||
10048 if (!Diagnose) return true;
10049
10050 // Find any user-declared move constructor.
10051 for (auto *I : RD->ctors()) {
10052 if (I->isMoveConstructor()) {
10053 UserDeclaredMove = I;
10054 break;
10055 }
10056 }
10057 assert(UserDeclaredMove);
10058 } else if (RD->hasUserDeclaredMoveAssignment() &&
10059 (!DeletesOnlyMatchingCopy ||
10061 if (!Diagnose) return true;
10062
10063 // Find any user-declared move assignment operator.
10064 for (auto *I : RD->methods()) {
10065 if (I->isMoveAssignmentOperator()) {
10066 UserDeclaredMove = I;
10067 break;
10068 }
10069 }
10070 assert(UserDeclaredMove);
10071 }
10072
10073 if (UserDeclaredMove) {
10074 Diag(UserDeclaredMove->getLocation(),
10075 diag::note_deleted_copy_user_declared_move)
10076 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10077 << UserDeclaredMove->isMoveAssignmentOperator();
10078 return true;
10079 }
10080 }
10081
10082 // Do access control from the special member function
10083 ContextRAII MethodContext(*this, MD);
10084
10085 // C++11 [class.dtor]p5:
10086 // -- for a virtual destructor, lookup of the non-array deallocation function
10087 // results in an ambiguity or in a function that is deleted or inaccessible
10088 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10089 FunctionDecl *OperatorDelete = nullptr;
10090 CanQualType DeallocType = Context.getCanonicalTagType(RD);
10091 DeclarationName Name =
10092 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
10096 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
10097 OperatorDelete, IDP,
10098 /*Diagnose=*/false)) {
10099 if (Diagnose)
10100 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
10101 return true;
10102 }
10103 }
10104
10105 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10106
10107 // Per DR1611, do not consider virtual bases of constructors of abstract
10108 // classes, since we are not going to construct them.
10109 // Per DR1658, do not consider virtual bases of destructors of abstract
10110 // classes either.
10111 // Per DR2180, for assignment operators we only assign (and thus only
10112 // consider) direct bases.
10113 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
10114 : SMI.VisitPotentiallyConstructedBases))
10115 return true;
10116
10117 if (SMI.shouldDeleteForAllConstMembers())
10118 return true;
10119
10120 if (getLangOpts().CUDA) {
10121 // We should delete the special member in CUDA mode if target inference
10122 // failed.
10123 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10124 // is treated as certain special member, which may not reflect what special
10125 // member MD really is. However inferTargetForImplicitSpecialMember
10126 // expects CSM to match MD, therefore recalculate CSM.
10127 assert(ICI || CSM == MD->getSpecialMemberKind());
10128 auto RealCSM = CSM;
10129 if (ICI)
10130 RealCSM = MD->getSpecialMemberKind();
10131
10132 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
10133 SMI.ConstArg, Diagnose);
10134 }
10135
10136 return false;
10137}
10138
10141 assert(DFK && "not a defaultable function");
10142 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10143
10144 if (DFK.isSpecialMember()) {
10146 nullptr, /*Diagnose=*/true);
10147 } else {
10148 DefaultedComparisonAnalyzer(
10150 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10151 .visit();
10152 }
10153}
10154
10155/// Perform lookup for a special member of the specified kind, and determine
10156/// whether it is trivial. If the triviality can be determined without the
10157/// lookup, skip it. This is intended for use when determining whether a
10158/// special member of a containing object is trivial, and thus does not ever
10159/// perform overload resolution for default constructors.
10160///
10161/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10162/// member that was most likely to be intended to be trivial, if any.
10163///
10164/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10165/// determine whether the special member is trivial.
10167 CXXSpecialMemberKind CSM, unsigned Quals,
10168 bool ConstRHS, TrivialABIHandling TAH,
10169 CXXMethodDecl **Selected) {
10170 if (Selected)
10171 *Selected = nullptr;
10172
10173 switch (CSM) {
10175 llvm_unreachable("not a special member");
10176
10178 // C++11 [class.ctor]p5:
10179 // A default constructor is trivial if:
10180 // - all the [direct subobjects] have trivial default constructors
10181 //
10182 // Note, no overload resolution is performed in this case.
10184 return true;
10185
10186 if (Selected) {
10187 // If there's a default constructor which could have been trivial, dig it
10188 // out. Otherwise, if there's any user-provided default constructor, point
10189 // to that as an example of why there's not a trivial one.
10190 CXXConstructorDecl *DefCtor = nullptr;
10193 for (auto *CI : RD->ctors()) {
10194 if (!CI->isDefaultConstructor())
10195 continue;
10196 DefCtor = CI;
10197 if (!DefCtor->isUserProvided())
10198 break;
10199 }
10200
10201 *Selected = DefCtor;
10202 }
10203
10204 return false;
10205
10207 // C++11 [class.dtor]p5:
10208 // A destructor is trivial if:
10209 // - all the direct [subobjects] have trivial destructors
10210 if (RD->hasTrivialDestructor() ||
10213 return true;
10214
10215 if (Selected) {
10216 if (RD->needsImplicitDestructor())
10218 *Selected = RD->getDestructor();
10219 }
10220
10221 return false;
10222
10224 // C++11 [class.copy]p12:
10225 // A copy constructor is trivial if:
10226 // - the constructor selected to copy each direct [subobject] is trivial
10227 if (RD->hasTrivialCopyConstructor() ||
10230 if (Quals == Qualifiers::Const)
10231 // We must either select the trivial copy constructor or reach an
10232 // ambiguity; no need to actually perform overload resolution.
10233 return true;
10234 } else if (!Selected) {
10235 return false;
10236 }
10237 // In C++98, we are not supposed to perform overload resolution here, but we
10238 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10239 // cases like B as having a non-trivial copy constructor:
10240 // struct A { template<typename T> A(T&); };
10241 // struct B { mutable A a; };
10242 goto NeedOverloadResolution;
10243
10245 // C++11 [class.copy]p25:
10246 // A copy assignment operator is trivial if:
10247 // - the assignment operator selected to copy each direct [subobject] is
10248 // trivial
10249 if (RD->hasTrivialCopyAssignment()) {
10250 if (Quals == Qualifiers::Const)
10251 return true;
10252 } else if (!Selected) {
10253 return false;
10254 }
10255 // In C++98, we are not supposed to perform overload resolution here, but we
10256 // treat that as a language defect.
10257 goto NeedOverloadResolution;
10258
10261 NeedOverloadResolution:
10263 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10264
10265 // The standard doesn't describe how to behave if the lookup is ambiguous.
10266 // We treat it as not making the member non-trivial, just like the standard
10267 // mandates for the default constructor. This should rarely matter, because
10268 // the member will also be deleted.
10270 return true;
10271
10272 if (!SMOR.getMethod()) {
10273 assert(SMOR.getKind() ==
10275 return false;
10276 }
10277
10278 // We deliberately don't check if we found a deleted special member. We're
10279 // not supposed to!
10280 if (Selected)
10281 *Selected = SMOR.getMethod();
10282
10286 return SMOR.getMethod()->isTrivialForCall();
10287 return SMOR.getMethod()->isTrivial();
10288 }
10289
10290 llvm_unreachable("unknown special method kind");
10291}
10292
10294 for (auto *CI : RD->ctors())
10295 if (!CI->isImplicit())
10296 return CI;
10297
10298 // Look for constructor templates.
10300 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10301 if (CXXConstructorDecl *CD =
10302 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10303 return CD;
10304 }
10305
10306 return nullptr;
10307}
10308
10309/// The kind of subobject we are checking for triviality. The values of this
10310/// enumeration are used in diagnostics.
10312 /// The subobject is a base class.
10314 /// The subobject is a non-static data member.
10316 /// The object is actually the complete object.
10318};
10319
10320/// Check whether the special member selected for a given type would be trivial.
10322 QualType SubType, bool ConstRHS,
10325 TrivialABIHandling TAH, bool Diagnose) {
10326 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10327 if (!SubRD)
10328 return true;
10329
10330 CXXMethodDecl *Selected;
10331 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10332 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10333 return true;
10334
10335 if (Diagnose) {
10336 if (ConstRHS)
10337 SubType.addConst();
10338
10339 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10340 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10341 << Kind << SubType.getUnqualifiedType();
10343 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10344 } else if (!Selected)
10345 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10346 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10347 else if (Selected->isUserProvided()) {
10348 if (Kind == TSK_CompleteObject)
10349 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10350 << Kind << SubType.getUnqualifiedType() << CSM;
10351 else {
10352 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10353 << Kind << SubType.getUnqualifiedType() << CSM;
10354 S.Diag(Selected->getLocation(), diag::note_declared_at);
10355 }
10356 } else {
10357 if (Kind != TSK_CompleteObject)
10358 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10359 << Kind << SubType.getUnqualifiedType() << CSM;
10360
10361 // Explain why the defaulted or deleted special member isn't trivial.
10362 S.SpecialMemberIsTrivial(Selected, CSM,
10364 }
10365 }
10366
10367 return false;
10368}
10369
10370/// Check whether the members of a class type allow a special member to be
10371/// trivial.
10373 CXXSpecialMemberKind CSM, bool ConstArg,
10374 TrivialABIHandling TAH, bool Diagnose) {
10375 for (const auto *FI : RD->fields()) {
10376 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10377 continue;
10378
10379 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10380
10381 // Pretend anonymous struct or union members are members of this class.
10382 if (FI->isAnonymousStructOrUnion()) {
10383 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10384 CSM, ConstArg, TAH, Diagnose))
10385 return false;
10386 continue;
10387 }
10388
10389 // C++11 [class.ctor]p5:
10390 // A default constructor is trivial if [...]
10391 // -- no non-static data member of its class has a
10392 // brace-or-equal-initializer
10394 FI->hasInClassInitializer()) {
10395 if (Diagnose)
10396 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10397 << FI;
10398 return false;
10399 }
10400
10401 // Objective C ARC 4.3.5:
10402 // [...] nontrivally ownership-qualified types are [...] not trivially
10403 // default constructible, copy constructible, move constructible, copy
10404 // assignable, move assignable, or destructible [...]
10405 if (FieldType.hasNonTrivialObjCLifetime()) {
10406 if (Diagnose)
10407 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10408 << RD << FieldType.getObjCLifetime();
10409 return false;
10410 }
10411
10412 bool ConstRHS = ConstArg && !FI->isMutable();
10413 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10414 CSM, TSK_Field, TAH, Diagnose))
10415 return false;
10416 }
10417
10418 return true;
10419}
10420
10423 CanQualType Ty = Context.getCanonicalTagType(RD);
10424
10425 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10427 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10430 /*Diagnose*/ true);
10431}
10432
10434 TrivialABIHandling TAH, bool Diagnose) {
10435 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10436 "not special enough");
10437
10438 CXXRecordDecl *RD = MD->getParent();
10439
10440 bool ConstArg = false;
10441
10442 // C++11 [class.copy]p12, p25: [DR1593]
10443 // A [special member] is trivial if [...] its parameter-type-list is
10444 // equivalent to the parameter-type-list of an implicit declaration [...]
10445 switch (CSM) {
10448 // Trivial default constructors and destructors cannot have parameters.
10449 break;
10450
10453 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10454 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10455
10456 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10457 // if they are not user-provided and their parameter-type-list is equivalent
10458 // to the parameter-type-list of an implicit declaration. This maintains the
10459 // behavior before dr2171 was implemented.
10460 //
10461 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10462 // trivial, if they are not user-provided, regardless of the qualifiers on
10463 // the reference type.
10464 const bool ClangABICompat14 =
10465 Context.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver14);
10466 if (!RT ||
10468 ClangABICompat14)) {
10469 if (Diagnose)
10470 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10471 << Param0->getSourceRange() << Param0->getType()
10472 << Context.getLValueReferenceType(
10473 Context.getCanonicalTagType(RD).withConst());
10474 return false;
10475 }
10476
10477 ConstArg = RT->getPointeeType().isConstQualified();
10478 break;
10479 }
10480
10483 // Trivial move operations always have non-cv-qualified parameters.
10484 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10485 const RValueReferenceType *RT =
10486 Param0->getType()->getAs<RValueReferenceType>();
10487 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10488 if (Diagnose)
10489 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10490 << Param0->getSourceRange() << Param0->getType()
10491 << Context.getRValueReferenceType(Context.getCanonicalTagType(RD));
10492 return false;
10493 }
10494 break;
10495 }
10496
10498 llvm_unreachable("not a special member");
10499 }
10500
10501 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10502 if (Diagnose)
10504 diag::note_nontrivial_default_arg)
10506 return false;
10507 }
10508 if (MD->isVariadic()) {
10509 if (Diagnose)
10510 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10511 return false;
10512 }
10513
10514 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10515 // A copy/move [constructor or assignment operator] is trivial if
10516 // -- the [member] selected to copy/move each direct base class subobject
10517 // is trivial
10518 //
10519 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10520 // A [default constructor or destructor] is trivial if
10521 // -- all the direct base classes have trivial [default constructors or
10522 // destructors]
10523 for (const auto &BI : RD->bases())
10524 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10525 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10526 return false;
10527
10528 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10529 // A copy/move [constructor or assignment operator] for a class X is
10530 // trivial if
10531 // -- for each non-static data member of X that is of class type (or array
10532 // thereof), the constructor selected to copy/move that member is
10533 // trivial
10534 //
10535 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10536 // A [default constructor or destructor] is trivial if
10537 // -- for all of the non-static data members of its class that are of class
10538 // type (or array thereof), each such class has a trivial [default
10539 // constructor or destructor]
10540 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10541 return false;
10542
10543 // C++11 [class.dtor]p5:
10544 // A destructor is trivial if [...]
10545 // -- the destructor is not virtual
10546 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10547 if (Diagnose)
10548 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10549 return false;
10550 }
10551
10552 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10553 // A [special member] for class X is trivial if [...]
10554 // -- class X has no virtual functions and no virtual base classes
10556 MD->getParent()->isDynamicClass()) {
10557 if (!Diagnose)
10558 return false;
10559
10560 if (RD->getNumVBases()) {
10561 // Check for virtual bases. We already know that the corresponding
10562 // member in all bases is trivial, so vbases must all be direct.
10563 CXXBaseSpecifier &BS = *RD->vbases_begin();
10564 assert(BS.isVirtual());
10565 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10566 return false;
10567 }
10568
10569 // Must have a virtual method.
10570 for (const auto *MI : RD->methods()) {
10571 if (MI->isVirtual()) {
10572 SourceLocation MLoc = MI->getBeginLoc();
10573 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10574 return false;
10575 }
10576 }
10577
10578 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10579 }
10580
10581 // Looks like it's trivial!
10582 return true;
10583}
10584
10585namespace {
10586struct FindHiddenVirtualMethod {
10587 Sema *S;
10589 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10590 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10591
10592private:
10593 /// Check whether any most overridden method from MD in Methods
10594 static bool CheckMostOverridenMethods(
10595 const CXXMethodDecl *MD,
10596 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10597 if (MD->size_overridden_methods() == 0)
10598 return Methods.count(MD->getCanonicalDecl());
10599 for (const CXXMethodDecl *O : MD->overridden_methods())
10600 if (CheckMostOverridenMethods(O, Methods))
10601 return true;
10602 return false;
10603 }
10604
10605public:
10606 /// Member lookup function that determines whether a given C++
10607 /// method overloads virtual methods in a base class without overriding any,
10608 /// to be used with CXXRecordDecl::lookupInBases().
10609 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10610 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10611 DeclarationName Name = Method->getDeclName();
10612 assert(Name.getNameKind() == DeclarationName::Identifier);
10613
10614 bool foundSameNameMethod = false;
10615 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10616 for (Path.Decls = BaseRecord->lookup(Name).begin();
10617 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10618 NamedDecl *D = *Path.Decls;
10619 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10620 MD = MD->getCanonicalDecl();
10621 foundSameNameMethod = true;
10622 // Interested only in hidden virtual methods.
10623 if (!MD->isVirtual())
10624 continue;
10625 // If the method we are checking overrides a method from its base
10626 // don't warn about the other overloaded methods. Clang deviates from
10627 // GCC by only diagnosing overloads of inherited virtual functions that
10628 // do not override any other virtual functions in the base. GCC's
10629 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10630 // function from a base class. These cases may be better served by a
10631 // warning (not specific to virtual functions) on call sites when the
10632 // call would select a different function from the base class, were it
10633 // visible.
10634 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10635 if (!S->IsOverload(Method, MD, false))
10636 return true;
10637 // Collect the overload only if its hidden.
10638 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10639 overloadedMethods.push_back(MD);
10640 }
10641 }
10642
10643 if (foundSameNameMethod)
10644 OverloadedMethods.append(overloadedMethods.begin(),
10645 overloadedMethods.end());
10646 return foundSameNameMethod;
10647 }
10648};
10649} // end anonymous namespace
10650
10651/// Add the most overridden methods from MD to Methods
10653 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10654 if (MD->size_overridden_methods() == 0)
10655 Methods.insert(MD->getCanonicalDecl());
10656 else
10657 for (const CXXMethodDecl *O : MD->overridden_methods())
10658 AddMostOverridenMethods(O, Methods);
10659}
10660
10662 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10663 if (!MD->getDeclName().isIdentifier())
10664 return;
10665
10666 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10667 /*bool RecordPaths=*/false,
10668 /*bool DetectVirtual=*/false);
10669 FindHiddenVirtualMethod FHVM;
10670 FHVM.Method = MD;
10671 FHVM.S = this;
10672
10673 // Keep the base methods that were overridden or introduced in the subclass
10674 // by 'using' in a set. A base method not in this set is hidden.
10675 CXXRecordDecl *DC = MD->getParent();
10676 for (NamedDecl *ND : DC->lookup(MD->getDeclName())) {
10677 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(ND))
10678 ND = shad->getTargetDecl();
10679 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10680 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10681 }
10682
10683 if (DC->lookupInBases(FHVM, Paths))
10684 OverloadedMethods = FHVM.OverloadedMethods;
10685}
10686
10688 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10689 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10691 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10692 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10693 Diag(overloadedMD->getLocation(), PD);
10694 }
10695}
10696
10698 if (MD->isInvalidDecl())
10699 return;
10700
10701 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10702 return;
10703
10704 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10705 FindHiddenVirtualMethods(MD, OverloadedMethods);
10706 if (!OverloadedMethods.empty()) {
10707 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10708 << MD << (OverloadedMethods.size() > 1);
10709
10710 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10711 }
10712}
10713
10715 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10716 // No diagnostics if this is a template instantiation.
10718 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10719 diag::ext_cannot_use_trivial_abi) << &RD;
10720 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10721 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10722 }
10723 RD.dropAttr<TrivialABIAttr>();
10724 };
10725
10726 // Ill-formed if the struct has virtual functions.
10727 if (RD.isPolymorphic()) {
10728 PrintDiagAndRemoveAttr(1);
10729 return;
10730 }
10731
10732 for (const auto &B : RD.bases()) {
10733 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10734 // virtual base.
10735 if (!B.getType()->isDependentType() &&
10736 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10737 PrintDiagAndRemoveAttr(2);
10738 return;
10739 }
10740
10741 if (B.isVirtual()) {
10742 PrintDiagAndRemoveAttr(3);
10743 return;
10744 }
10745 }
10746
10747 for (const auto *FD : RD.fields()) {
10748 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10749 // non-trivial for the purpose of calls.
10750 QualType FT = FD->getType();
10752 PrintDiagAndRemoveAttr(4);
10753 return;
10754 }
10755
10756 // Ill-formed if the field is an address-discriminated value.
10758 PrintDiagAndRemoveAttr(6);
10759 return;
10760 }
10761
10762 if (const auto *RT =
10763 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10764 if (!RT->isDependentType() &&
10765 !cast<CXXRecordDecl>(RT->getDecl()->getDefinitionOrSelf())
10766 ->canPassInRegisters()) {
10767 PrintDiagAndRemoveAttr(5);
10768 return;
10769 }
10770 }
10771
10773 return;
10774
10775 // Ill-formed if the copy and move constructors are deleted.
10776 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10777 // If the type is dependent, then assume it might have
10778 // implicit copy or move ctor because we won't know yet at this point.
10779 if (RD.isDependentType())
10780 return true;
10783 return true;
10786 return true;
10787 for (const CXXConstructorDecl *CD : RD.ctors())
10788 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10789 return true;
10790 return false;
10791 };
10792
10793 if (!HasNonDeletedCopyOrMoveConstructor()) {
10794 PrintDiagAndRemoveAttr(0);
10795 return;
10796 }
10797}
10798
10800 CXXRecordDecl &RD) {
10801 if (RequireCompleteType(RD.getLocation(), Context.getCanonicalTagType(&RD),
10802 diag::err_incomplete_type_vtable_pointer_auth))
10803 return;
10804
10805 const CXXRecordDecl *PrimaryBase = &RD;
10806 if (PrimaryBase->hasAnyDependentBases())
10807 return;
10808
10809 while (1) {
10810 assert(PrimaryBase);
10811 const CXXRecordDecl *Base = nullptr;
10812 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10813 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10814 continue;
10815 Base = BasePtr.getType()->getAsCXXRecordDecl();
10816 break;
10817 }
10818 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10819 break;
10820 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10821 diag::err_non_top_level_vtable_pointer_auth)
10822 << &RD << Base;
10823 PrimaryBase = Base;
10824 }
10825
10826 if (!RD.isPolymorphic())
10827 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10828 diag::err_non_polymorphic_vtable_pointer_auth)
10829 << &RD;
10830}
10831
10834 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10835 if (!TagDecl)
10836 return;
10837
10839
10840 for (const ParsedAttr &AL : AttrList) {
10841 if (AL.getKind() != ParsedAttr::AT_Visibility)
10842 continue;
10843 AL.setInvalid();
10844 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10845 }
10846
10847 ActOnFields(S, RLoc, TagDecl,
10849 // strict aliasing violation!
10850 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10851 FieldCollector->getCurNumFields()),
10852 LBrac, RBrac, AttrList);
10853
10855}
10856
10857/// Find the equality comparison functions that should be implicitly declared
10858/// in a given class definition, per C++2a [class.compare.default]p3.
10860 ASTContext &Ctx, CXXRecordDecl *RD,
10862 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10863 if (!RD->lookup(EqEq).empty())
10864 // Member operator== explicitly declared: no implicit operator==s.
10865 return;
10866
10867 // Traverse friends looking for an '==' or a '<=>'.
10868 for (FriendDecl *Friend : RD->friends()) {
10869 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10870 if (!FD) continue;
10871
10872 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10873 // Friend operator== explicitly declared: no implicit operator==s.
10874 Spaceships.clear();
10875 return;
10876 }
10877
10878 if (FD->getOverloadedOperator() == OO_Spaceship &&
10880 Spaceships.push_back(FD);
10881 }
10882
10883 // Look for members named 'operator<=>'.
10885 for (NamedDecl *ND : RD->lookup(Cmp)) {
10886 // Note that we could find a non-function here (either a function template
10887 // or a using-declaration). Neither case results in an implicit
10888 // 'operator=='.
10889 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10890 if (FD->isExplicitlyDefaulted())
10891 Spaceships.push_back(FD);
10892 }
10893}
10894
10896 // Don't add implicit special members to templated classes.
10897 // FIXME: This means unqualified lookups for 'operator=' within a class
10898 // template don't work properly.
10899 if (!ClassDecl->isDependentType()) {
10900 if (ClassDecl->needsImplicitDefaultConstructor()) {
10901 ++getASTContext().NumImplicitDefaultConstructors;
10902
10903 if (ClassDecl->hasInheritedConstructor())
10905 }
10906
10907 if (ClassDecl->needsImplicitCopyConstructor()) {
10908 ++getASTContext().NumImplicitCopyConstructors;
10909
10910 // If the properties or semantics of the copy constructor couldn't be
10911 // determined while the class was being declared, force a declaration
10912 // of it now.
10914 ClassDecl->hasInheritedConstructor())
10916 // For the MS ABI we need to know whether the copy ctor is deleted. A
10917 // prerequisite for deleting the implicit copy ctor is that the class has
10918 // a move ctor or move assignment that is either user-declared or whose
10919 // semantics are inherited from a subobject. FIXME: We should provide a
10920 // more direct way for CodeGen to ask whether the constructor was deleted.
10921 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10922 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10924 ClassDecl->hasUserDeclaredMoveAssignment() ||
10927 }
10928
10929 if (getLangOpts().CPlusPlus11 &&
10930 ClassDecl->needsImplicitMoveConstructor()) {
10931 ++getASTContext().NumImplicitMoveConstructors;
10932
10934 ClassDecl->hasInheritedConstructor())
10936 }
10937
10938 if (ClassDecl->needsImplicitCopyAssignment()) {
10939 ++getASTContext().NumImplicitCopyAssignmentOperators;
10940
10941 // If we have a dynamic class, then the copy assignment operator may be
10942 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10943 // it shows up in the right place in the vtable and that we diagnose
10944 // problems with the implicit exception specification.
10945 if (ClassDecl->isDynamicClass() ||
10947 ClassDecl->hasInheritedAssignment())
10949 }
10950
10951 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10952 ++getASTContext().NumImplicitMoveAssignmentOperators;
10953
10954 // Likewise for the move assignment operator.
10955 if (ClassDecl->isDynamicClass() ||
10957 ClassDecl->hasInheritedAssignment())
10959 }
10960
10961 if (ClassDecl->needsImplicitDestructor()) {
10962 ++getASTContext().NumImplicitDestructors;
10963
10964 // If we have a dynamic class, then the destructor may be virtual, so we
10965 // have to declare the destructor immediately. This ensures that, e.g., it
10966 // shows up in the right place in the vtable and that we diagnose problems
10967 // with the implicit exception specification.
10968 if (ClassDecl->isDynamicClass() ||
10970 DeclareImplicitDestructor(ClassDecl);
10971 }
10972 }
10973
10974 // C++2a [class.compare.default]p3:
10975 // If the member-specification does not explicitly declare any member or
10976 // friend named operator==, an == operator function is declared implicitly
10977 // for each defaulted three-way comparison operator function defined in
10978 // the member-specification
10979 // FIXME: Consider doing this lazily.
10980 // We do this during the initial parse for a class template, not during
10981 // instantiation, so that we can handle unqualified lookups for 'operator=='
10982 // when parsing the template.
10984 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10986 DefaultedSpaceships);
10987 for (auto *FD : DefaultedSpaceships)
10988 DeclareImplicitEqualityComparison(ClassDecl, FD);
10989 }
10990}
10991
10992unsigned
10994 llvm::function_ref<Scope *()> EnterScope) {
10995 if (!D)
10996 return 0;
10998
10999 // In order to get name lookup right, reenter template scopes in order from
11000 // outermost to innermost.
11002 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
11003
11004 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
11005 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
11006 ParameterLists.push_back(TPL);
11007
11008 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11009 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
11010 ParameterLists.push_back(FTD->getTemplateParameters());
11011 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11012 LookupDC = VD->getDeclContext();
11013
11015 ParameterLists.push_back(VTD->getTemplateParameters());
11016 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
11017 ParameterLists.push_back(PSD->getTemplateParameters());
11018 }
11019 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
11020 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11021 ParameterLists.push_back(TPL);
11022
11023 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
11025 ParameterLists.push_back(CTD->getTemplateParameters());
11026 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
11027 ParameterLists.push_back(PSD->getTemplateParameters());
11028 }
11029 }
11030 // FIXME: Alias declarations and concepts.
11031
11032 unsigned Count = 0;
11033 Scope *InnermostTemplateScope = nullptr;
11034 for (TemplateParameterList *Params : ParameterLists) {
11035 // Ignore explicit specializations; they don't contribute to the template
11036 // depth.
11037 if (Params->size() == 0)
11038 continue;
11039
11040 InnermostTemplateScope = EnterScope();
11041 for (NamedDecl *Param : *Params) {
11042 if (Param->getDeclName()) {
11043 InnermostTemplateScope->AddDecl(Param);
11044 IdResolver.AddDecl(Param);
11045 }
11046 }
11047 ++Count;
11048 }
11049
11050 // Associate the new template scopes with the corresponding entities.
11051 if (InnermostTemplateScope) {
11052 assert(LookupDC && "no enclosing DeclContext for template lookup");
11053 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
11054 }
11055
11056 return Count;
11057}
11058
11060 if (!RecordD) return;
11061 AdjustDeclIfTemplate(RecordD);
11064}
11065
11067 if (!RecordD) return;
11069}
11070
11072 if (!Param)
11073 return;
11074
11075 S->AddDecl(Param);
11076 if (Param->getDeclName())
11077 IdResolver.AddDecl(Param);
11078}
11079
11082
11083/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11084/// C++ method declaration. We're (re-)introducing the given
11085/// function parameter into scope for use in parsing later parts of
11086/// the method declaration. For example, we could see an
11087/// ActOnParamDefaultArgument event for this parameter.
11089 if (!ParamD)
11090 return;
11091
11092 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
11093
11094 S->AddDecl(Param);
11095 if (Param->getDeclName())
11096 IdResolver.AddDecl(Param);
11097}
11098
11100 if (!MethodD)
11101 return;
11102
11103 AdjustDeclIfTemplate(MethodD);
11104
11106
11107 // Now that we have our default arguments, check the constructor
11108 // again. It could produce additional diagnostics or affect whether
11109 // the class has implicitly-declared destructors, among other
11110 // things.
11111 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
11113
11114 // Check the default arguments, which we may have added.
11115 if (!Method->isInvalidDecl())
11117}
11118
11119// Emit the given diagnostic for each non-address-space qualifier.
11120// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11121static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11123 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11124 bool DiagOccurred = false;
11126 [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11127 SourceLocation SL) {
11128 // This diagnostic should be emitted on any qualifier except an addr
11129 // space qualifier. However, forEachQualifier currently doesn't visit
11130 // addr space qualifiers, so there's no way to write this condition
11131 // right now; we just diagnose on everything.
11132 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
11133 DiagOccurred = true;
11134 });
11135 if (DiagOccurred)
11136 D.setInvalidType();
11137 }
11138}
11139
11141 unsigned Kind) {
11142 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11143 return;
11144
11146 if (Chunk.Kind == DeclaratorChunk::Paren ||
11148 return;
11149
11150 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11151 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
11152 << Kind << Chunk.getSourceRange();
11153 D.setInvalidType();
11154}
11155
11157 StorageClass &SC) {
11158 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11159
11160 // C++ [class.ctor]p3:
11161 // A constructor shall not be virtual (10.3) or static (9.4). A
11162 // constructor can be invoked for a const, volatile or const
11163 // volatile object. A constructor shall not be declared const,
11164 // volatile, or const volatile (9.3.2).
11165 if (isVirtual) {
11166 if (!D.isInvalidType())
11167 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11168 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11170 D.setInvalidType();
11171 }
11172 if (SC == SC_Static) {
11173 if (!D.isInvalidType())
11174 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11175 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11177 D.setInvalidType();
11178 SC = SC_None;
11179 }
11180
11181 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11183 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11187 D.setInvalidType();
11188 }
11189
11190 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11191 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
11192
11193 // C++0x [class.ctor]p4:
11194 // A constructor shall not be declared with a ref-qualifier.
11196 if (FTI.hasRefQualifier()) {
11197 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11200 D.setInvalidType();
11201 }
11202
11203 // Rebuild the function type "R" without any type qualifiers (in
11204 // case any of the errors above fired) and with "void" as the
11205 // return type, since constructors don't have return types.
11206 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11207 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11208 return R;
11209
11211 EPI.TypeQuals = Qualifiers();
11212 EPI.RefQualifier = RQ_None;
11213
11214 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
11215}
11216
11218 CXXRecordDecl *ClassDecl
11219 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11220 if (!ClassDecl)
11221 return Constructor->setInvalidDecl();
11222
11223 // C++ [class.copy]p3:
11224 // A declaration of a constructor for a class X is ill-formed if
11225 // its first parameter is of type (optionally cv-qualified) X and
11226 // either there are no other parameters or else all other
11227 // parameters have default arguments.
11228 if (!Constructor->isInvalidDecl() &&
11229 Constructor->hasOneParamOrDefaultArgs() &&
11230 !Constructor->isFunctionTemplateSpecialization()) {
11231 CanQualType ParamType =
11232 Constructor->getParamDecl(0)->getType()->getCanonicalTypeUnqualified();
11233 CanQualType ClassTy = Context.getCanonicalTagType(ClassDecl);
11234 if (ParamType == ClassTy) {
11235 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11236 const char *ConstRef
11237 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11238 : " const &";
11239 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11240 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11241
11242 // FIXME: Rather that making the constructor invalid, we should endeavor
11243 // to fix the type.
11244 Constructor->setInvalidDecl();
11245 }
11246 }
11247}
11248
11250 CXXRecordDecl *RD = Destructor->getParent();
11251
11252 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11253 SourceLocation Loc;
11254
11255 if (!Destructor->isImplicit())
11256 Loc = Destructor->getLocation();
11257 else
11258 Loc = RD->getLocation();
11259
11260 DeclarationName Name =
11261 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
11262 // If we have a virtual destructor, look up the deallocation function
11264 Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11265 Expr *ThisArg = nullptr;
11266
11267 // If the notional 'delete this' expression requires a non-trivial
11268 // conversion from 'this' to the type of a destroying operator delete's
11269 // first parameter, perform that conversion now.
11270 if (OperatorDelete->isDestroyingOperatorDelete()) {
11271 unsigned AddressParamIndex = 0;
11272 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11273 ++AddressParamIndex;
11274 QualType ParamType =
11275 OperatorDelete->getParamDecl(AddressParamIndex)->getType();
11276 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11277 // C++ [class.dtor]p13:
11278 // ... as if for the expression 'delete this' appearing in a
11279 // non-virtual destructor of the destructor's class.
11280 ContextRAII SwitchContext(*this, Destructor);
11282 OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());
11283 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11284 This = PerformImplicitConversion(This.get(), ParamType,
11286 if (This.isInvalid()) {
11287 // FIXME: Register this as a context note so that it comes out
11288 // in the right order.
11289 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11290 return true;
11291 }
11292 ThisArg = This.get();
11293 }
11294 }
11295
11296 DiagnoseUseOfDecl(OperatorDelete, Loc);
11297 MarkFunctionReferenced(Loc, OperatorDelete);
11298 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11299
11300 if (isa<CXXMethodDecl>(OperatorDelete) &&
11301 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11302 Context.getLangOpts())) {
11303 // In Microsoft ABI whenever a class has a defined operator delete,
11304 // scalar deleting destructors check the 3rd bit of the implicit
11305 // parameter and if it is set, then, global operator delete must be
11306 // called instead of the class-specific one. Find and save the global
11307 // operator delete for that case. Do not diagnose at this point because
11308 // the lack of a global operator delete is not an error if there are no
11309 // delete calls that require it.
11310 FunctionDecl *GlobalOperatorDelete =
11311 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11312 /*LookForGlobal*/ true, Name);
11313 if (GlobalOperatorDelete) {
11314 MarkFunctionReferenced(Loc, GlobalOperatorDelete);
11315 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11316 }
11317 }
11318
11319 if (Context.getTargetInfo().emitVectorDeletingDtors(
11320 Context.getLangOpts())) {
11321 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11322 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11323 DeclarationName VDeleteName =
11324 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
11326 Loc, RD, /*Diagnose*/ false,
11327 /*LookForGlobal*/ false, VDeleteName);
11328 if (ArrOperatorDelete && isa<CXXMethodDecl>(ArrOperatorDelete)) {
11329 FunctionDecl *GlobalArrOperatorDelete =
11330 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11331 /*LookForGlobal*/ true,
11332 VDeleteName);
11333 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11334 if (GlobalArrOperatorDelete &&
11335 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11336 DestructorIsExported))
11337 MarkFunctionReferenced(Loc, GlobalArrOperatorDelete);
11338 } else if (!ArrOperatorDelete) {
11339 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11340 Loc, RD, /*Diagnose*/ false,
11341 /*LookForGlobal*/ true, VDeleteName);
11342 }
11343 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11344 if (ArrOperatorDelete &&
11345 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11346 DestructorIsExported))
11347 MarkFunctionReferenced(Loc, ArrOperatorDelete);
11348 }
11349 }
11350 }
11351
11352 return false;
11353}
11354
11356 StorageClass& SC) {
11357 // C++ [class.dtor]p1:
11358 // [...] A typedef-name that names a class is a class-name
11359 // (7.1.3); however, a typedef-name that names a class shall not
11360 // be used as the identifier in the declarator for a destructor
11361 // declaration.
11362 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11363 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11364 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11365 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11366 else if (const TemplateSpecializationType *TST =
11367 DeclaratorType->getAs<TemplateSpecializationType>())
11368 if (TST->isTypeAlias())
11369 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11370 << DeclaratorType << 1;
11371
11372 // C++ [class.dtor]p2:
11373 // A destructor is used to destroy objects of its class type. A
11374 // destructor takes no parameters, and no return type can be
11375 // specified for it (not even void). The address of a destructor
11376 // shall not be taken. A destructor shall not be static. A
11377 // destructor can be invoked for a const, volatile or const
11378 // volatile object. A destructor shall not be declared const,
11379 // volatile or const volatile (9.3.2).
11380 if (SC == SC_Static) {
11381 if (!D.isInvalidType())
11382 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11383 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11386
11387 SC = SC_None;
11388 }
11389 if (!D.isInvalidType()) {
11390 // Destructors don't have return types, but the parser will
11391 // happily parse something like:
11392 //
11393 // class X {
11394 // float ~X();
11395 // };
11396 //
11397 // The return type will be eliminated later.
11398 if (D.getDeclSpec().hasTypeSpecifier())
11399 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11402 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11403 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11409 D.setInvalidType();
11410 }
11411 }
11412
11413 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11414 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11415
11416 // C++0x [class.dtor]p2:
11417 // A destructor shall not be declared with a ref-qualifier.
11419 if (FTI.hasRefQualifier()) {
11420 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11423 D.setInvalidType();
11424 }
11425
11426 // Make sure we don't have any parameters.
11427 if (FTIHasNonVoidParameters(FTI)) {
11428 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11429
11430 // Delete the parameters.
11431 FTI.freeParams();
11432 D.setInvalidType();
11433 }
11434
11435 // Make sure the destructor isn't variadic.
11436 if (FTI.isVariadic) {
11437 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11438 D.setInvalidType();
11439 }
11440
11441 // Rebuild the function type "R" without any type qualifiers or
11442 // parameters (in case any of the errors above fired) and with
11443 // "void" as the return type, since destructors don't have return
11444 // types.
11445 if (!D.isInvalidType())
11446 return R;
11447
11448 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11450 EPI.Variadic = false;
11451 EPI.TypeQuals = Qualifiers();
11452 EPI.RefQualifier = RQ_None;
11453 return Context.getFunctionType(Context.VoidTy, {}, EPI);
11454}
11455
11456static void extendLeft(SourceRange &R, SourceRange Before) {
11457 if (Before.isInvalid())
11458 return;
11459 R.setBegin(Before.getBegin());
11460 if (R.getEnd().isInvalid())
11461 R.setEnd(Before.getEnd());
11462}
11463
11464static void extendRight(SourceRange &R, SourceRange After) {
11465 if (After.isInvalid())
11466 return;
11467 if (R.getBegin().isInvalid())
11468 R.setBegin(After.getBegin());
11469 R.setEnd(After.getEnd());
11470}
11471
11473 StorageClass& SC) {
11474 // C++ [class.conv.fct]p1:
11475 // Neither parameter types nor return type can be specified. The
11476 // type of a conversion function (8.3.5) is "function taking no
11477 // parameter returning conversion-type-id."
11478 if (SC == SC_Static) {
11479 if (!D.isInvalidType())
11480 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11482 << D.getName().getSourceRange();
11483 D.setInvalidType();
11484 SC = SC_None;
11485 }
11486
11487 TypeSourceInfo *ConvTSI = nullptr;
11488 QualType ConvType =
11490
11491 const DeclSpec &DS = D.getDeclSpec();
11492 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11493 // Conversion functions don't have return types, but the parser will
11494 // happily parse something like:
11495 //
11496 // class X {
11497 // float operator bool();
11498 // };
11499 //
11500 // The return type will be changed later anyway.
11501 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11504 D.setInvalidType();
11505 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11506 // It's also plausible that the user writes type qualifiers in the wrong
11507 // place, such as:
11508 // struct S { const operator int(); };
11509 // FIXME: we could provide a fixit to move the qualifiers onto the
11510 // conversion type.
11511 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11512 << SourceRange(D.getIdentifierLoc()) << 0;
11513 D.setInvalidType();
11514 }
11515 const auto *Proto = R->castAs<FunctionProtoType>();
11516 // Make sure we don't have any parameters.
11518 unsigned NumParam = Proto->getNumParams();
11519
11520 // [C++2b]
11521 // A conversion function shall have no non-object parameters.
11522 if (NumParam == 1) {
11524 if (const auto *First =
11525 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11526 First && First->isExplicitObjectParameter())
11527 NumParam--;
11528 }
11529
11530 if (NumParam != 0) {
11531 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11532 // Delete the parameters.
11533 FTI.freeParams();
11534 D.setInvalidType();
11535 } else if (Proto->isVariadic()) {
11536 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11537 D.setInvalidType();
11538 }
11539
11540 // Diagnose "&operator bool()" and other such nonsense. This
11541 // is actually a gcc extension which we don't support.
11542 if (Proto->getReturnType() != ConvType) {
11543 bool NeedsTypedef = false;
11544 SourceRange Before, After;
11545
11546 // Walk the chunks and extract information on them for our diagnostic.
11547 bool PastFunctionChunk = false;
11548 for (auto &Chunk : D.type_objects()) {
11549 switch (Chunk.Kind) {
11551 if (!PastFunctionChunk) {
11552 if (Chunk.Fun.HasTrailingReturnType) {
11553 TypeSourceInfo *TRT = nullptr;
11554 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11555 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11556 }
11557 PastFunctionChunk = true;
11558 break;
11559 }
11560 [[fallthrough]];
11562 NeedsTypedef = true;
11563 extendRight(After, Chunk.getSourceRange());
11564 break;
11565
11571 extendLeft(Before, Chunk.getSourceRange());
11572 break;
11573
11575 extendLeft(Before, Chunk.Loc);
11576 extendRight(After, Chunk.EndLoc);
11577 break;
11578 }
11579 }
11580
11581 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11582 After.isValid() ? After.getBegin() :
11583 D.getIdentifierLoc();
11584 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11585 DB << Before << After;
11586
11587 if (!NeedsTypedef) {
11588 DB << /*don't need a typedef*/0;
11589
11590 // If we can provide a correct fix-it hint, do so.
11591 if (After.isInvalid() && ConvTSI) {
11592 SourceLocation InsertLoc =
11594 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11596 InsertLoc, CharSourceRange::getTokenRange(Before))
11597 << FixItHint::CreateRemoval(Before);
11598 }
11599 } else if (!Proto->getReturnType()->isDependentType()) {
11600 DB << /*typedef*/1 << Proto->getReturnType();
11601 } else if (getLangOpts().CPlusPlus11) {
11602 DB << /*alias template*/2 << Proto->getReturnType();
11603 } else {
11604 DB << /*might not be fixable*/3;
11605 }
11606
11607 // Recover by incorporating the other type chunks into the result type.
11608 // Note, this does *not* change the name of the function. This is compatible
11609 // with the GCC extension:
11610 // struct S { &operator int(); } s;
11611 // int &r = s.operator int(); // ok in GCC
11612 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11613 ConvType = Proto->getReturnType();
11614 }
11615
11616 // C++ [class.conv.fct]p4:
11617 // The conversion-type-id shall not represent a function type nor
11618 // an array type.
11619 if (ConvType->isArrayType()) {
11620 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11621 ConvType = Context.getPointerType(ConvType);
11622 D.setInvalidType();
11623 } else if (ConvType->isFunctionType()) {
11624 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11625 ConvType = Context.getPointerType(ConvType);
11626 D.setInvalidType();
11627 }
11628
11629 // Rebuild the function type "R" without any parameters (in case any
11630 // of the errors above fired) and with the conversion type as the
11631 // return type.
11632 if (D.isInvalidType())
11633 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11634
11635 // C++0x explicit conversion operators.
11636 if (DS.hasExplicitSpecifier())
11638 diag_compat::explicit_conversion_functions)
11640}
11641
11643 assert(Conversion && "Expected to receive a conversion function declaration");
11644
11645 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11646
11647 // Make sure we aren't redeclaring the conversion function.
11648 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11649 // C++ [class.conv.fct]p1:
11650 // [...] A conversion function is never used to convert a
11651 // (possibly cv-qualified) object to the (possibly cv-qualified)
11652 // same object type (or a reference to it), to a (possibly
11653 // cv-qualified) base class of that type (or a reference to it),
11654 // or to (possibly cv-qualified) void.
11655 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
11656 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11657 ConvType = ConvTypeRef->getPointeeType();
11658 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11660 /* Suppress diagnostics for instantiations. */;
11661 else if (Conversion->size_overridden_methods() != 0)
11662 /* Suppress diagnostics for overriding virtual function in a base class. */;
11663 else if (ConvType->isRecordType()) {
11664 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11665 if (ConvType == ClassType)
11666 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11667 << ClassType;
11668 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11669 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11670 << ClassType << ConvType;
11671 } else if (ConvType->isVoidType()) {
11672 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11673 << ClassType << ConvType;
11674 }
11675
11676 if (FunctionTemplateDecl *ConversionTemplate =
11677 Conversion->getDescribedFunctionTemplate()) {
11678 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11679 ConvType = ConvTypePtr->getPointeeType();
11680 }
11681 if (ConvType->isUndeducedAutoType()) {
11682 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11683 << getReturnTypeLoc(Conversion).getSourceRange()
11684 << ConvType->castAs<AutoType>()->getKeyword()
11685 << /* in declaration of conversion function template= */ 24;
11686 }
11687
11688 return ConversionTemplate;
11689 }
11690
11691 return Conversion;
11692}
11693
11698
11702
11704 DeclarationName Name, QualType R,
11705 bool IsLambda, DeclContext *DC) {
11706 if (!D.isFunctionDeclarator())
11707 return;
11708
11710 if (FTI.NumParams == 0)
11711 return;
11712 ParmVarDecl *ExplicitObjectParam = nullptr;
11713 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11714 const auto &ParamInfo = FTI.Params[Idx];
11715 if (!ParamInfo.Param)
11716 continue;
11717 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11718 if (!Param->isExplicitObjectParameter())
11719 continue;
11720 if (Idx == 0) {
11721 ExplicitObjectParam = Param;
11722 continue;
11723 } else {
11724 Diag(Param->getLocation(),
11725 diag::err_explicit_object_parameter_must_be_first)
11726 << IsLambda << Param->getSourceRange();
11727 }
11728 }
11729 if (!ExplicitObjectParam)
11730 return;
11731
11732 if (ExplicitObjectParam->hasDefaultArg()) {
11733 Diag(ExplicitObjectParam->getLocation(),
11734 diag::err_explicit_object_default_arg)
11735 << ExplicitObjectParam->getSourceRange();
11736 D.setInvalidType();
11737 }
11738
11741 D.isStaticMember())) {
11742 Diag(ExplicitObjectParam->getBeginLoc(),
11743 diag::err_explicit_object_parameter_nonmember)
11744 << D.getSourceRange() << /*static=*/0 << IsLambda;
11745 D.setInvalidType();
11746 }
11747
11748 if (D.getDeclSpec().isVirtualSpecified()) {
11749 Diag(ExplicitObjectParam->getBeginLoc(),
11750 diag::err_explicit_object_parameter_nonmember)
11751 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11752 D.setInvalidType();
11753 }
11754
11755 // Friend declarations require some care. Consider:
11756 //
11757 // namespace N {
11758 // struct A{};
11759 // int f(A);
11760 // }
11761 //
11762 // struct S {
11763 // struct T {
11764 // int f(this T);
11765 // };
11766 //
11767 // friend int T::f(this T); // Allow this.
11768 // friend int f(this S); // But disallow this.
11769 // friend int N::f(this A); // And disallow this.
11770 // };
11771 //
11772 // Here, it seems to suffice to check whether the scope
11773 // specifier designates a class type.
11774 if (D.getDeclSpec().isFriendSpecified() &&
11775 !isa_and_present<CXXRecordDecl>(
11777 Diag(ExplicitObjectParam->getBeginLoc(),
11778 diag::err_explicit_object_parameter_nonmember)
11779 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11780 D.setInvalidType();
11781 }
11782
11783 if (IsLambda && FTI.hasMutableQualifier()) {
11784 Diag(ExplicitObjectParam->getBeginLoc(),
11785 diag::err_explicit_object_parameter_mutable)
11786 << D.getSourceRange();
11787 }
11788
11789 if (IsLambda)
11790 return;
11791
11792 if (!DC || !DC->isRecord()) {
11793 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11794 "should have been diagnosed already");
11795 return;
11796 }
11797
11798 // CWG2674: constructors and destructors cannot have explicit parameters.
11801 Diag(ExplicitObjectParam->getBeginLoc(),
11802 diag::err_explicit_object_parameter_constructor)
11804 << D.getSourceRange();
11805 D.setInvalidType();
11806 }
11807}
11808
11809namespace {
11810/// Utility class to accumulate and print a diagnostic listing the invalid
11811/// specifier(s) on a declaration.
11812struct BadSpecifierDiagnoser {
11813 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11814 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11815 ~BadSpecifierDiagnoser() {
11816 Diagnostic << Specifiers;
11817 }
11818
11819 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11820 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11821 }
11822 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11823 return check(SpecLoc,
11825 }
11826 void check(SourceLocation SpecLoc, const char *Spec) {
11827 if (SpecLoc.isInvalid()) return;
11828 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11829 if (!Specifiers.empty()) Specifiers += " ";
11830 Specifiers += Spec;
11831 }
11832
11833 Sema &S;
11834 Sema::SemaDiagnosticBuilder Diagnostic;
11835 std::string Specifiers;
11836};
11837}
11838
11840 StorageClass &SC) {
11841 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11842 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11843 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11844
11845 // C++ [temp.deduct.guide]p3:
11846 // A deduction-gide shall be declared in the same scope as the
11847 // corresponding class template.
11848 if (!CurContext->getRedeclContext()->Equals(
11849 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11850 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11851 << GuidedTemplateDecl;
11852 NoteTemplateLocation(*GuidedTemplateDecl);
11853 }
11854
11855 auto &DS = D.getMutableDeclSpec();
11856 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11857 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11858 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11859 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11860 BadSpecifierDiagnoser Diagnoser(
11861 *this, D.getIdentifierLoc(),
11862 diag::err_deduction_guide_invalid_specifier);
11863
11864 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11865 DS.ClearStorageClassSpecs();
11866 SC = SC_None;
11867
11868 // 'explicit' is permitted.
11869 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11870 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11871 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11872 DS.ClearConstexprSpec();
11873
11874 Diagnoser.check(DS.getConstSpecLoc(), "const");
11875 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11876 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11877 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11878 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11879 DS.ClearTypeQualifiers();
11880
11881 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11882 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11883 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11884 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11885 DS.ClearTypeSpecType();
11886 }
11887
11888 if (D.isInvalidType())
11889 return true;
11890
11891 // Check the declarator is simple enough.
11892 bool FoundFunction = false;
11893 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11894 if (Chunk.Kind == DeclaratorChunk::Paren)
11895 continue;
11896 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11898 diag::err_deduction_guide_with_complex_decl)
11899 << D.getSourceRange();
11900 break;
11901 }
11902 if (!Chunk.Fun.hasTrailingReturnType())
11903 return Diag(D.getName().getBeginLoc(),
11904 diag::err_deduction_guide_no_trailing_return_type);
11905
11906 // Check that the return type is written as a specialization of
11907 // the template specified as the deduction-guide's name.
11908 // The template name may not be qualified. [temp.deduct.guide]
11909 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11910 TypeSourceInfo *TSI = nullptr;
11911 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11912 assert(TSI && "deduction guide has valid type but invalid return type?");
11913 bool AcceptableReturnType = false;
11914 bool MightInstantiateToSpecialization = false;
11915 if (auto RetTST =
11917 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11918 bool TemplateMatches = Context.hasSameTemplateName(
11919 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11920
11922 SpecifiedName.getAsQualifiedTemplateName();
11923 // A Template template parameter is never wrapped in a
11924 // QualifiedTemplateName, but it's always simply-written.
11925 bool SimplyWritten = !Qualifiers || (!Qualifiers->hasTemplateKeyword() &&
11926 !Qualifiers->getQualifier());
11927 if (SimplyWritten && TemplateMatches)
11928 AcceptableReturnType = true;
11929 else {
11930 // This could still instantiate to the right type, unless we know it
11931 // names the wrong class template.
11932 auto *TD = SpecifiedName.getAsTemplateDecl();
11933 MightInstantiateToSpecialization =
11934 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11935 }
11936 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11937 MightInstantiateToSpecialization = true;
11938 }
11939
11940 if (!AcceptableReturnType)
11941 return Diag(TSI->getTypeLoc().getBeginLoc(),
11942 diag::err_deduction_guide_bad_trailing_return_type)
11943 << GuidedTemplate << TSI->getType()
11944 << MightInstantiateToSpecialization
11945 << TSI->getTypeLoc().getSourceRange();
11946
11947 // Keep going to check that we don't have any inner declarator pieces (we
11948 // could still have a function returning a pointer to a function).
11949 FoundFunction = true;
11950 }
11951
11952 if (D.isFunctionDefinition())
11953 // we can still create a valid deduction guide here.
11954 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11955 return false;
11956}
11957
11958//===----------------------------------------------------------------------===//
11959// Namespace Handling
11960//===----------------------------------------------------------------------===//
11961
11962/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11963/// reopened.
11965 SourceLocation Loc,
11966 IdentifierInfo *II, bool *IsInline,
11967 NamespaceDecl *PrevNS) {
11968 assert(*IsInline != PrevNS->isInline());
11969
11970 // 'inline' must appear on the original definition, but not necessarily
11971 // on all extension definitions, so the note should point to the first
11972 // definition to avoid confusion.
11973 PrevNS = PrevNS->getFirstDecl();
11974
11975 if (PrevNS->isInline())
11976 // The user probably just forgot the 'inline', so suggest that it
11977 // be added back.
11978 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11979 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11980 else
11981 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11982
11983 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11984 *IsInline = PrevNS->isInline();
11985}
11986
11987/// ActOnStartNamespaceDef - This is called at the start of a namespace
11988/// definition.
11990 SourceLocation InlineLoc,
11991 SourceLocation NamespaceLoc,
11992 SourceLocation IdentLoc, IdentifierInfo *II,
11993 SourceLocation LBrace,
11994 const ParsedAttributesView &AttrList,
11995 UsingDirectiveDecl *&UD, bool IsNested) {
11996 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11997 // For anonymous namespace, take the location of the left brace.
11998 SourceLocation Loc = II ? IdentLoc : LBrace;
11999 bool IsInline = InlineLoc.isValid();
12000 bool IsInvalid = false;
12001 bool IsStd = false;
12002 bool AddToKnown = false;
12003 Scope *DeclRegionScope = NamespcScope->getParent();
12004
12005 NamespaceDecl *PrevNS = nullptr;
12006 if (II) {
12007 // C++ [namespace.std]p7:
12008 // A translation unit shall not declare namespace std to be an inline
12009 // namespace (9.8.2).
12010 //
12011 // Precondition: the std namespace is in the file scope and is declared to
12012 // be inline
12013 auto DiagnoseInlineStdNS = [&]() {
12014 assert(IsInline && II->isStr("std") &&
12015 CurContext->getRedeclContext()->isTranslationUnit() &&
12016 "Precondition of DiagnoseInlineStdNS not met");
12017 Diag(InlineLoc, diag::err_inline_namespace_std)
12018 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
12019 IsInline = false;
12020 };
12021 // C++ [namespace.def]p2:
12022 // The identifier in an original-namespace-definition shall not
12023 // have been previously defined in the declarative region in
12024 // which the original-namespace-definition appears. The
12025 // identifier in an original-namespace-definition is the name of
12026 // the namespace. Subsequently in that declarative region, it is
12027 // treated as an original-namespace-name.
12028 //
12029 // Since namespace names are unique in their scope, and we don't
12030 // look through using directives, just look for any ordinary names
12031 // as if by qualified name lookup.
12032 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12034 LookupQualifiedName(R, CurContext->getRedeclContext());
12035 NamedDecl *PrevDecl =
12036 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12037 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
12038
12039 if (PrevNS) {
12040 // This is an extended namespace definition.
12041 if (IsInline && II->isStr("std") &&
12042 CurContext->getRedeclContext()->isTranslationUnit())
12043 DiagnoseInlineStdNS();
12044 else if (IsInline != PrevNS->isInline())
12045 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
12046 &IsInline, PrevNS);
12047 } else if (PrevDecl) {
12048 // This is an invalid name redefinition.
12049 Diag(Loc, diag::err_redefinition_different_kind)
12050 << II;
12051 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12052 IsInvalid = true;
12053 // Continue on to push Namespc as current DeclContext and return it.
12054 } else if (II->isStr("std") &&
12055 CurContext->getRedeclContext()->isTranslationUnit()) {
12056 if (IsInline)
12057 DiagnoseInlineStdNS();
12058 // This is the first "real" definition of the namespace "std", so update
12059 // our cache of the "std" namespace to point at this definition.
12060 PrevNS = getStdNamespace();
12061 IsStd = true;
12062 AddToKnown = !IsInline;
12063 } else {
12064 // We've seen this namespace for the first time.
12065 AddToKnown = !IsInline;
12066 }
12067 } else {
12068 // Anonymous namespaces.
12069
12070 // Determine whether the parent already has an anonymous namespace.
12071 DeclContext *Parent = CurContext->getRedeclContext();
12072 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12073 PrevNS = TU->getAnonymousNamespace();
12074 } else {
12075 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
12076 PrevNS = ND->getAnonymousNamespace();
12077 }
12078
12079 if (PrevNS && IsInline != PrevNS->isInline())
12080 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
12081 &IsInline, PrevNS);
12082 }
12083
12084 // Namespace lookup can find a namespace in an inline namespace. An extension
12085 // of that namespace retains its semantic parent, even when it is written in
12086 // an enclosing namespace.
12087 DeclContext *SemanticContext = CurContext;
12088 if (PrevNS && !CurContext->getRedeclContext()->Equals(
12089 PrevNS->getDeclContext()->getRedeclContext()))
12090 SemanticContext = PrevNS->getDeclContext();
12092 Context, SemanticContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
12094 if (IsInvalid)
12095 Namespc->setInvalidDecl();
12096
12097 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
12098 AddPragmaAttributes(DeclRegionScope, Namespc);
12099 ProcessAPINotes(Namespc);
12100
12101 // FIXME: Should we be merging attributes?
12102 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12104
12105 if (IsStd)
12106 StdNamespace = Namespc;
12107 if (AddToKnown)
12108 KnownNamespaces[Namespc] = false;
12109
12110 if (II) {
12111 PushOnScopeChains(Namespc, DeclRegionScope);
12112 } else {
12113 // Link the anonymous namespace into its parent.
12114 DeclContext *Parent = CurContext->getRedeclContext();
12115 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12116 TU->setAnonymousNamespace(Namespc);
12117 } else {
12118 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
12119 }
12120
12121 CurContext->addDecl(Namespc);
12122
12123 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12124 // behaves as if it were replaced by
12125 // namespace unique { /* empty body */ }
12126 // using namespace unique;
12127 // namespace unique { namespace-body }
12128 // where all occurrences of 'unique' in a translation unit are
12129 // replaced by the same identifier and this identifier differs
12130 // from all other identifiers in the entire program.
12131
12132 // We just create the namespace with an empty name and then add an
12133 // implicit using declaration, just like the standard suggests.
12134 //
12135 // CodeGen enforces the "universally unique" aspect by giving all
12136 // declarations semantically contained within an anonymous
12137 // namespace internal linkage.
12138
12139 if (!PrevNS) {
12141 /* 'using' */ LBrace,
12142 /* 'namespace' */ SourceLocation(),
12143 /* qualifier */ NestedNameSpecifierLoc(),
12144 /* identifier */ SourceLocation(),
12145 Namespc,
12146 /* Ancestor */ Parent);
12147 UD->setImplicit();
12148 Parent->addDecl(UD);
12149 }
12150 }
12151
12152 ActOnDocumentableDecl(Namespc);
12153
12154 // Although we could have an invalid decl (i.e. the namespace name is a
12155 // redefinition), push it as current DeclContext and try to continue parsing.
12156 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12157 // for the namespace has the declarations that showed up in that particular
12158 // namespace definition.
12159 PushDeclContext(NamespcScope, Namespc);
12160 return Namespc;
12161}
12162
12163/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12164/// is a namespace alias, returns the namespace it points to.
12166 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
12167 return AD->getNamespace();
12168 return dyn_cast_or_null<NamespaceDecl>(D);
12169}
12170
12172 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
12173 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12174 Namespc->setRBraceLoc(RBrace);
12176 if (Namespc->hasAttr<VisibilityAttr>())
12177 PopPragmaVisibility(true, RBrace);
12178 // If this namespace contains an export-declaration, export it now.
12179 if (DeferredExportedNamespaces.erase(Namespc))
12181}
12182
12184 return cast_or_null<CXXRecordDecl>(
12185 StdBadAlloc.get(Context.getExternalSource()));
12186}
12187
12189 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
12190}
12191
12193 return cast_or_null<NamespaceDecl>(
12194 StdNamespace.get(Context.getExternalSource()));
12195}
12196
12197namespace {
12198
12199enum UnsupportedSTLSelect {
12200 USS_InvalidMember,
12201 USS_MissingMember,
12202 USS_NonTrivial,
12203 USS_Other
12204};
12205
12206struct InvalidSTLDiagnoser {
12207 Sema &S;
12208 SourceLocation Loc;
12209 QualType TyForDiags;
12210
12211 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12212 const VarDecl *VD = nullptr) {
12213 {
12214 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
12215 << TyForDiags << ((int)Sel);
12216 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12217 assert(!Name.empty());
12218 D << Name;
12219 }
12220 }
12221 if (Sel == USS_InvalidMember) {
12222 S.Diag(VD->getLocation(), diag::note_var_declared_here)
12223 << VD << VD->getSourceRange();
12224 }
12225 return QualType();
12226 }
12227};
12228} // namespace
12229
12231 SourceLocation Loc,
12233 assert(getLangOpts().CPlusPlus &&
12234 "Looking for comparison category type outside of C++.");
12235
12236 // Use an elaborated type for diagnostics which has a name containing the
12237 // prepended 'std' namespace but not any inline namespace names.
12238 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12240 /*Prefix=*/std::nullopt);
12241 return Context.getTagType(ElaboratedTypeKeyword::None, Qualifier,
12242 Info->Record,
12243 /*OwnsTag=*/false);
12244 };
12245
12246 // Check if we've already successfully checked the comparison category type
12247 // before. If so, skip checking it again.
12248 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12249 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12250 // The only thing we need to check is that the type has a reachable
12251 // definition in the current context.
12252 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12253 return QualType();
12254
12255 return Info->getType();
12256 }
12257
12258 // If lookup failed
12259 if (!Info) {
12260 std::string NameForDiags = "std::";
12261 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12262 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12263 << NameForDiags << (int)Usage;
12264 return QualType();
12265 }
12266
12267 assert(Info->Kind == Kind);
12268 assert(Info->Record);
12269
12270 // Update the Record decl in case we encountered a forward declaration on our
12271 // first pass. FIXME: This is a bit of a hack.
12272 if (Info->Record->hasDefinition())
12273 Info->Record = Info->Record->getDefinition();
12274
12275 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12276 return QualType();
12277
12278 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12279
12280 if (!Info->Record->isTriviallyCopyable())
12281 return UnsupportedSTLError(USS_NonTrivial);
12282
12283 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12284 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12285 // Tolerate empty base classes.
12286 if (Base->isEmpty())
12287 continue;
12288 // Reject STL implementations which have at least one non-empty base.
12289 return UnsupportedSTLError();
12290 }
12291
12292 // Check that the STL has implemented the types using a single integer field.
12293 // This expectation allows better codegen for builtin operators. We require:
12294 // (1) The class has exactly one field.
12295 // (2) The field is an integral or enumeration type.
12296 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12297 if (std::distance(FIt, FEnd) != 1 ||
12298 !FIt->getType()->isIntegralOrEnumerationType()) {
12299 return UnsupportedSTLError();
12300 }
12301
12302 // Build each of the require values and store them in Info.
12303 for (ComparisonCategoryResult CCR :
12305 StringRef MemName = ComparisonCategories::getResultString(CCR);
12306 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12307
12308 if (!ValInfo)
12309 return UnsupportedSTLError(USS_MissingMember, MemName);
12310
12311 VarDecl *VD = ValInfo->VD;
12312 assert(VD && "should not be null!");
12313
12314 // Attempt to diagnose reasons why the STL definition of this type
12315 // might be foobar, including it failing to be a constant expression.
12316 // TODO Handle more ways the lookup or result can be invalid.
12317 if (!VD->isStaticDataMember() ||
12319 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12320
12321 // Attempt to evaluate the var decl as a constant expression and extract
12322 // the value of its first field as a ICE. If this fails, the STL
12323 // implementation is not supported.
12324 if (!ValInfo->hasValidIntValue())
12325 return UnsupportedSTLError();
12326
12327 MarkVariableReferenced(Loc, VD);
12328 }
12329
12330 // We've successfully built the required types and expressions. Update
12331 // the cache and return the newly cached value.
12332 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12333 return Info->getType();
12334}
12335
12337 if (!StdNamespace) {
12338 // The "std" namespace has not yet been defined, so build one implicitly.
12340 Context, Context.getTranslationUnitDecl(),
12341 /*Inline=*/false, SourceLocation(), SourceLocation(),
12342 &PP.getIdentifierTable().get("std"),
12343 /*PrevDecl=*/nullptr, /*Nested=*/false);
12344 getStdNamespace()->setImplicit(true);
12345 // We want the created NamespaceDecl to be available for redeclaration
12346 // lookups, but not for regular name lookups.
12347 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12348 getStdNamespace()->clearIdentifierNamespace();
12349 }
12350
12351 return getStdNamespace();
12352}
12353
12354static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12355 const char *ClassName,
12356 ClassTemplateDecl **CachedDecl,
12357 const Decl **MalformedDecl) {
12358 // We're looking for implicit instantiations of
12359 // template <typename U> class std::{ClassName}.
12360
12361 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12362 // it.
12363 return false;
12364
12365 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12366 if (!MalformedDecl)
12367 return;
12368 if (!D)
12369 D = SugaredType->getAsTagDecl();
12370 if (!D || !D->isInStdNamespace())
12371 return;
12372 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12373 if (II && II == &S.PP.getIdentifierTable().get(ClassName))
12374 *MalformedDecl = D;
12375 };
12376
12377 ClassTemplateDecl *Template = nullptr;
12379 if (const TemplateSpecializationType *TST =
12381 Template = dyn_cast_or_null<ClassTemplateDecl>(
12382 TST->getTemplateName().getAsTemplateDecl());
12383 Arguments = TST->template_arguments();
12384 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12385 Template = TT->getTemplateDecl();
12386 Arguments = TT->getTemplateArgs(S.Context);
12387 }
12388
12389 if (!Template) {
12390 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12391 return false;
12392 }
12393
12394 if (!*CachedDecl) {
12395 // Haven't recognized std::{ClassName} yet, maybe this is it.
12396 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12397 // semantics of this are slightly different, most notably the existing
12398 // "lookup" semantics explicitly diagnose an invalid definition as an
12399 // error.
12400 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12401 if (TemplateClass->getIdentifier() !=
12402 &S.PP.getIdentifierTable().get(ClassName) ||
12404 TemplateClass->getNonTransparentDeclContext()))
12405 return false;
12406 // This is a template called std::{ClassName}, but is it the right
12407 // template?
12408 TemplateParameterList *Params = Template->getTemplateParameters();
12409 if (Params->getMinRequiredArguments() != 1 ||
12410 !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||
12411 Params->getParam(0)->isTemplateParameterPack()) {
12412 if (MalformedDecl)
12413 *MalformedDecl = TemplateClass;
12414 return false;
12415 }
12416
12417 // It's the right template.
12418 *CachedDecl = Template;
12419 }
12420
12421 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12422 return false;
12423
12424 // This is an instance of std::{ClassName}. Find the argument type.
12425 if (TypeArg) {
12426 QualType ArgType = Arguments[0].getAsType();
12427 // FIXME: Since TST only has as-written arguments, we have to perform the
12428 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12429 // - If an explicitly-specified template argument type is a lifetime type
12430 // with no lifetime qualifier, the __strong lifetime qualifier is
12431 // inferred.
12432 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12433 !ArgType.getObjCLifetime()) {
12434 Qualifiers Qs;
12436 ArgType = S.Context.getQualifiedType(ArgType, Qs);
12437 }
12438 *TypeArg = ArgType;
12439 }
12440
12441 return true;
12442}
12443
12445 assert(getLangOpts().CPlusPlus &&
12446 "Looking for std::initializer_list outside of C++.");
12447
12448 // We're looking for implicit instantiations of
12449 // template <typename E> class std::initializer_list.
12450
12451 return isStdClassTemplate(*this, Ty, Element, "initializer_list",
12452 &StdInitializerList, /*MalformedDecl=*/nullptr);
12453}
12454
12456 const Decl **MalformedDecl) {
12457 assert(getLangOpts().CPlusPlus &&
12458 "Looking for std::type_identity outside of C++.");
12459
12460 // We're looking for implicit instantiations of
12461 // template <typename T> struct std::type_identity.
12462
12463 return isStdClassTemplate(*this, Ty, Element, "type_identity",
12464 &StdTypeIdentity, MalformedDecl);
12465}
12466
12468 const char *ClassName,
12469 bool *WasMalformed) {
12470 if (!S.StdNamespace)
12471 return nullptr;
12472
12473 LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,
12476 return nullptr;
12477
12479 if (!Template) {
12480 Result.suppressDiagnostics();
12481 // We found something weird. Complain about the first thing we found.
12482 NamedDecl *Found = *Result.begin();
12483 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
12484 << ClassName;
12485 if (WasMalformed)
12486 *WasMalformed = true;
12487 return nullptr;
12488 }
12489
12490 // We found some template with the correct name. Now verify that it's
12491 // correct.
12492 TemplateParameterList *Params = Template->getTemplateParameters();
12493 if (Params->getMinRequiredArguments() != 1 ||
12494 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12495 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
12496 << ClassName;
12497 if (WasMalformed)
12498 *WasMalformed = true;
12499 return nullptr;
12500 }
12501
12502 return Template;
12503}
12504
12506 QualType TypeParam, SourceLocation Loc) {
12507 assert(S.getStdNamespace());
12508 TemplateArgumentListInfo Args(Loc, Loc);
12509 auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);
12510 Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12511
12513 Loc, Args, /*Scope=*/nullptr,
12514 /*ForNestedNameSpecifier=*/false);
12515}
12516
12518 if (!StdInitializerList) {
12519 bool WasMalformed = false;
12521 LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);
12522 if (!StdInitializerList) {
12523 if (!WasMalformed)
12524 Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12525 return QualType();
12526 }
12527 }
12528 return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);
12529}
12530
12532 if (!StdTypeIdentity) {
12533 StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",
12534 /*WasMalformed=*/nullptr);
12535 if (!StdTypeIdentity)
12536 return QualType();
12537 }
12538 return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);
12539}
12540
12542 // C++ [dcl.init.list]p2:
12543 // A constructor is an initializer-list constructor if its first parameter
12544 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12545 // std::initializer_list<E> for some type E, and either there are no other
12546 // parameters or else all other parameters have default arguments.
12547 if (!Ctor->hasOneParamOrDefaultArgs())
12548 return false;
12549
12550 QualType ArgType = Ctor->getParamDecl(0)->getType();
12551 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12552 ArgType = RT->getPointeeType().getUnqualifiedType();
12553
12554 return isStdInitializerList(ArgType, nullptr);
12555}
12556
12557/// Determine whether a using statement is in a context where it will be
12558/// apply in all contexts.
12560 switch (CurContext->getDeclKind()) {
12561 case Decl::TranslationUnit:
12562 return true;
12563 case Decl::LinkageSpec:
12564 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12565 default:
12566 return false;
12567 }
12568}
12569
12570namespace {
12571
12572// Callback to only accept typo corrections that are namespaces.
12573class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12574public:
12575 bool ValidateCandidate(const TypoCorrection &candidate) override {
12576 if (NamedDecl *ND = candidate.getCorrectionDecl())
12578 return false;
12579 }
12580
12581 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12582 return std::make_unique<NamespaceValidatorCCC>(*this);
12583 }
12584};
12585
12586}
12587
12588static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12589 Sema &S) {
12590 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12591 Module *M = ND->getOwningModule();
12592 assert(M && "hidden namespace definition not in a module?");
12593
12594 if (M->isExplicitGlobalModule())
12595 S.Diag(Corrected.getCorrectionRange().getBegin(),
12596 diag::err_module_unimported_use_header)
12598 << /*Header Name*/ false;
12599 else
12600 S.Diag(Corrected.getCorrectionRange().getBegin(),
12601 diag::err_module_unimported_use)
12603 << M->getTopLevelModuleName();
12604}
12605
12607 CXXScopeSpec &SS,
12608 SourceLocation IdentLoc,
12609 IdentifierInfo *Ident) {
12610 R.clear();
12611 NamespaceValidatorCCC CCC{};
12612 if (TypoCorrection Corrected =
12613 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12615 // Generally we find it is confusing more than helpful to diagnose the
12616 // invisible namespace.
12617 // See https://github.com/llvm/llvm-project/issues/73893.
12618 //
12619 // However, we should diagnose when the users are trying to using an
12620 // invisible namespace. So we handle the case specially here.
12621 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12622 Corrected.requiresImport()) {
12623 DiagnoseInvisibleNamespace(Corrected, S);
12624 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12625 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12626 bool DroppedSpecifier =
12627 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12628 S.diagnoseTypo(Corrected,
12629 S.PDiag(diag::err_using_directive_member_suggest)
12630 << Ident << DC << DroppedSpecifier << SS.getRange(),
12631 S.PDiag(diag::note_namespace_defined_here));
12632 } else {
12633 S.diagnoseTypo(Corrected,
12634 S.PDiag(diag::err_using_directive_suggest) << Ident,
12635 S.PDiag(diag::note_namespace_defined_here));
12636 }
12637 R.addDecl(Corrected.getFoundDecl());
12638 return true;
12639 }
12640 return false;
12641}
12642
12644 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12645 SourceLocation IdentLoc,
12646 IdentifierInfo *NamespcName,
12647 const ParsedAttributesView &AttrList) {
12648 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12649 assert(NamespcName && "Invalid NamespcName.");
12650 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12651
12652 // Get the innermost enclosing declaration scope.
12653 S = S->getDeclParent();
12654
12655 UsingDirectiveDecl *UDir = nullptr;
12656 NestedNameSpecifier Qualifier = SS.getScopeRep();
12657
12658 // Lookup namespace name.
12659 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12660 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12661 if (R.isAmbiguous())
12662 return nullptr;
12663
12664 if (R.empty()) {
12665 R.clear();
12666 // Allow "using namespace std;" or "using namespace ::std;" even if
12667 // "std" hasn't been defined yet, for GCC compatibility.
12668 if ((!Qualifier ||
12669 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12670 NamespcName->isStr("std")) {
12671 Diag(IdentLoc, diag::ext_using_undefined_std);
12672 R.addDecl(getOrCreateStdNamespace());
12673 R.resolveKind();
12674 }
12675 // Otherwise, attempt typo correction.
12676 else
12677 TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12678 }
12679
12680 if (!R.empty()) {
12681 NamedDecl *Named = R.getRepresentativeDecl();
12682 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12683 assert(NS && "expected namespace decl");
12684
12685 // The use of a nested name specifier may trigger deprecation warnings.
12686 DiagnoseUseOfDecl(Named, IdentLoc);
12687
12688 // C++ [namespace.udir]p1:
12689 // A using-directive specifies that the names in the nominated
12690 // namespace can be used in the scope in which the
12691 // using-directive appears after the using-directive. During
12692 // unqualified name lookup (3.4.1), the names appear as if they
12693 // were declared in the nearest enclosing namespace which
12694 // contains both the using-directive and the nominated
12695 // namespace. [Note: in this context, "contains" means "contains
12696 // directly or indirectly". ]
12697
12698 // Find enclosing context containing both using-directive and
12699 // nominated namespace.
12700 DeclContext *CommonAncestor = NS;
12701 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12702 CommonAncestor = CommonAncestor->getParent();
12703
12704 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12706 IdentLoc, Named, CommonAncestor);
12707
12709 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12710 Diag(IdentLoc, diag::warn_using_directive_in_header);
12711 }
12712
12713 PushUsingDirective(S, UDir);
12714 } else {
12715 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12716 }
12717
12718 if (UDir) {
12719 ProcessDeclAttributeList(S, UDir, AttrList);
12720 ProcessAPINotes(UDir);
12721 }
12722
12723 return UDir;
12724}
12725
12727 // If the scope has an associated entity and the using directive is at
12728 // namespace or translation unit scope, add the UsingDirectiveDecl into
12729 // its lookup structure so qualified name lookup can find it.
12730 DeclContext *Ctx = S->getEntity();
12731 if (Ctx && !Ctx->isFunctionOrMethod())
12732 Ctx->addDecl(UDir);
12733 else
12734 // Otherwise, it is at block scope. The using-directives will affect lookup
12735 // only to the end of the scope.
12736 S->PushUsingDirective(UDir);
12737}
12738
12740 SourceLocation UsingLoc,
12741 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12742 UnqualifiedId &Name,
12743 SourceLocation EllipsisLoc,
12744 const ParsedAttributesView &AttrList) {
12745 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12746
12747 if (SS.isEmpty()) {
12748 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12749 return nullptr;
12750 }
12751
12752 switch (Name.getKind()) {
12758 break;
12759
12762 // C++11 inheriting constructors.
12763 Diag(Name.getBeginLoc(),
12765 ? diag::warn_cxx98_compat_using_decl_constructor
12766 : diag::err_using_decl_constructor)
12767 << SS.getRange();
12768
12769 if (getLangOpts().CPlusPlus11) break;
12770
12771 return nullptr;
12772
12774 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12775 return nullptr;
12776
12778 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12780 return nullptr;
12781
12783 llvm_unreachable("cannot parse qualified deduction guide name");
12784 }
12785
12786 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12787 DeclarationName TargetName = TargetNameInfo.getName();
12788 if (!TargetName)
12789 return nullptr;
12790
12791 // Warn about access declarations.
12792 if (UsingLoc.isInvalid()) {
12794 ? diag::err_access_decl
12795 : diag::warn_access_decl_deprecated)
12796 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12797 }
12798
12799 if (EllipsisLoc.isInvalid()) {
12802 return nullptr;
12803 } else {
12805 !TargetNameInfo.containsUnexpandedParameterPack()) {
12806 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12807 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12808 EllipsisLoc = SourceLocation();
12809 }
12810 }
12811
12812 NamedDecl *UD =
12813 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12814 SS, TargetNameInfo, EllipsisLoc, AttrList,
12815 /*IsInstantiation*/ false,
12816 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12817 if (UD)
12818 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12819
12820 return UD;
12821}
12822
12824 SourceLocation UsingLoc,
12825 SourceLocation EnumLoc, SourceRange TyLoc,
12826 const IdentifierInfo &II, ParsedType Ty,
12827 const CXXScopeSpec &SS) {
12828 TypeSourceInfo *TSI = nullptr;
12829 SourceLocation IdentLoc = TyLoc.getBegin();
12830 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12831 if (EnumTy.isNull()) {
12832 Diag(IdentLoc, isDependentScopeSpecifier(SS)
12833 ? diag::err_using_enum_is_dependent
12834 : diag::err_unknown_typename)
12835 << II.getName()
12836 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12837 TyLoc.getEnd());
12838 return nullptr;
12839 }
12840
12841 if (EnumTy->isDependentType()) {
12842 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12843 return nullptr;
12844 }
12845
12846 auto *Enum = EnumTy->getAsEnumDecl();
12847 if (!Enum) {
12848 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12849 return nullptr;
12850 }
12851
12852 if (TSI == nullptr)
12853 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12854
12855 auto *UD =
12856 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12857
12858 if (UD)
12859 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12860
12861 return UD;
12862}
12863
12864/// Determine whether a using declaration considers the given
12865/// declarations as "equivalent", e.g., if they are redeclarations of
12866/// the same entity or are both typedefs of the same type.
12867static bool
12869 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12870 return true;
12871
12872 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12873 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12874 return Context.hasSameType(TD1->getUnderlyingType(),
12875 TD2->getUnderlyingType());
12876
12877 // Two using_if_exists using-declarations are equivalent if both are
12878 // unresolved.
12881 return true;
12882
12883 return false;
12884}
12885
12887 const LookupResult &Previous,
12888 UsingShadowDecl *&PrevShadow) {
12889 // Diagnose finding a decl which is not from a base class of the
12890 // current class. We do this now because there are cases where this
12891 // function will silently decide not to build a shadow decl, which
12892 // will pre-empt further diagnostics.
12893 //
12894 // We don't need to do this in C++11 because we do the check once on
12895 // the qualifier.
12896 //
12897 // FIXME: diagnose the following if we care enough:
12898 // struct A { int foo; };
12899 // struct B : A { using A::foo; };
12900 // template <class T> struct C : A {};
12901 // template <class T> struct D : C<T> { using B::foo; } // <---
12902 // This is invalid (during instantiation) in C++03 because B::foo
12903 // resolves to the using decl in B, which is not a base class of D<T>.
12904 // We can't diagnose it immediately because C<T> is an unknown
12905 // specialization. The UsingShadowDecl in D<T> then points directly
12906 // to A::foo, which will look well-formed when we instantiate.
12907 // The right solution is to not collapse the shadow-decl chain.
12908 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12909 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12910 DeclContext *OrigDC = Orig->getDeclContext();
12911
12912 // Handle enums and anonymous structs.
12913 if (isa<EnumDecl>(OrigDC))
12914 OrigDC = OrigDC->getParent();
12915 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12916 while (OrigRec->isAnonymousStructOrUnion())
12917 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12918
12920 if (OrigDC == CurContext) {
12921 Diag(Using->getLocation(),
12922 diag::err_using_decl_nested_name_specifier_is_current_class)
12923 << Using->getQualifierLoc().getSourceRange();
12924 Diag(Orig->getLocation(), diag::note_using_decl_target);
12925 Using->setInvalidDecl();
12926 return true;
12927 }
12928
12929 Diag(Using->getQualifierLoc().getBeginLoc(),
12930 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12931 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12932 << Using->getQualifierLoc().getSourceRange();
12933 Diag(Orig->getLocation(), diag::note_using_decl_target);
12934 Using->setInvalidDecl();
12935 return true;
12936 }
12937 }
12938
12939 if (Previous.empty()) return false;
12940
12941 NamedDecl *Target = Orig;
12943 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12944
12945 // If the target happens to be one of the previous declarations, we
12946 // don't have a conflict.
12947 //
12948 // FIXME: but we might be increasing its access, in which case we
12949 // should redeclare it.
12950 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12951 bool FoundEquivalentDecl = false;
12952 for (NamedDecl *Element : Previous) {
12953 NamedDecl *D = Element->getUnderlyingDecl();
12954 // We can have UsingDecls in our Previous results because we use the same
12955 // LookupResult for checking whether the UsingDecl itself is a valid
12956 // redeclaration.
12958 continue;
12959
12960 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12961 // C++ [class.mem]p19:
12962 // If T is the name of a class, then [every named member other than
12963 // a non-static data member] shall have a name different from T
12964 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12968 CurContext,
12970 return true;
12971 }
12972
12974 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Element))
12975 PrevShadow = Shadow;
12976 FoundEquivalentDecl = true;
12978 // We don't conflict with an existing using shadow decl of an equivalent
12979 // declaration, but we're not a redeclaration of it.
12980 FoundEquivalentDecl = true;
12981 }
12982
12983 if (isVisible(D))
12984 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12985 }
12986
12987 if (FoundEquivalentDecl)
12988 return false;
12989
12990 // Always emit a diagnostic for a mismatch between an unresolved
12991 // using_if_exists and a resolved using declaration in either direction.
12993 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12994 if (!NonTag && !Tag)
12995 return false;
12996 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12997 Diag(Target->getLocation(), diag::note_using_decl_target);
12998 Diag((NonTag ? NonTag : Tag)->getLocation(),
12999 diag::note_using_decl_conflict);
13000 BUD->setInvalidDecl();
13001 return true;
13002 }
13003
13004 if (FunctionDecl *FD = Target->getAsFunction()) {
13005 NamedDecl *OldDecl = nullptr;
13006 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
13007 /*IsForUsingDecl*/ true)) {
13009 return false;
13010
13012 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13013 break;
13014
13015 // We found a decl with the exact signature.
13017 // If we're in a record, we want to hide the target, so we
13018 // return true (without a diagnostic) to tell the caller not to
13019 // build a shadow decl.
13020 if (CurContext->isRecord())
13021 return true;
13022
13023 // If we're not in a record, this is an error.
13024 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13025 break;
13026 }
13027
13028 Diag(Target->getLocation(), diag::note_using_decl_target);
13029 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
13030 BUD->setInvalidDecl();
13031 return true;
13032 }
13033
13034 // Target is not a function.
13035
13036 if (isa<TagDecl>(Target)) {
13037 // No conflict between a tag and a non-tag.
13038 if (!Tag) return false;
13039
13040 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13041 Diag(Target->getLocation(), diag::note_using_decl_target);
13042 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
13043 BUD->setInvalidDecl();
13044 return true;
13045 }
13046
13047 // No conflict between a tag and a non-tag.
13048 if (!NonTag) return false;
13049
13050 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
13051 Diag(Target->getLocation(), diag::note_using_decl_target);
13052 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
13053 BUD->setInvalidDecl();
13054 return true;
13055}
13056
13057/// Determine whether a direct base class is a virtual base class.
13059 if (!Derived->getNumVBases())
13060 return false;
13061 for (auto &B : Derived->bases())
13062 if (B.getType()->getAsCXXRecordDecl() == Base)
13063 return B.isVirtual();
13064 llvm_unreachable("not a direct base class");
13065}
13066
13068 NamedDecl *Orig,
13069 UsingShadowDecl *PrevDecl) {
13070 // If we resolved to another shadow declaration, just coalesce them.
13071 NamedDecl *Target = Orig;
13073 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
13074 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13075 }
13076
13077 NamedDecl *NonTemplateTarget = Target;
13078 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
13079 NonTemplateTarget = TargetTD->getTemplatedDecl();
13080
13081 UsingShadowDecl *Shadow;
13082 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
13083 UsingDecl *Using = cast<UsingDecl>(BUD);
13084 bool IsVirtualBase =
13086 Using->getQualifier().getAsRecordDecl());
13088 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
13089 } else {
13091 Target->getDeclName(), BUD, Target);
13092 }
13093 BUD->addShadowDecl(Shadow);
13094
13095 Shadow->setAccess(BUD->getAccess());
13096 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13097 Shadow->setInvalidDecl();
13098
13099 Shadow->setPreviousDecl(PrevDecl);
13100
13101 if (S)
13102 PushOnScopeChains(Shadow, S);
13103 else
13104 CurContext->addDecl(Shadow);
13105
13106
13107 return Shadow;
13108}
13109
13111 if (Shadow->getDeclName().getNameKind() ==
13113 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
13114
13115 // Remove it from the DeclContext...
13116 Shadow->getDeclContext()->removeDecl(Shadow);
13117
13118 // ...and the scope, if applicable...
13119 if (S) {
13120 S->RemoveDecl(Shadow);
13121 IdResolver.RemoveDecl(Shadow);
13122 }
13123
13124 // ...and the using decl.
13125 Shadow->getIntroducer()->removeShadowDecl(Shadow);
13126
13127 // TODO: complain somehow if Shadow was used. It shouldn't
13128 // be possible for this to happen, because...?
13129}
13130
13131/// Find the base specifier for a base class with the given type.
13133 QualType DesiredBase,
13134 bool &AnyDependentBases) {
13135 // Check whether the named type is a direct base class.
13136 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13137 for (auto &Base : Derived->bases()) {
13138 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13139 if (CanonicalDesiredBase == BaseType)
13140 return &Base;
13141 if (BaseType->isDependentType())
13142 AnyDependentBases = true;
13143 }
13144 return nullptr;
13145}
13146
13147namespace {
13148class UsingValidatorCCC final : public CorrectionCandidateCallback {
13149public:
13150 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13151 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13152 : HasTypenameKeyword(HasTypenameKeyword),
13153 IsInstantiation(IsInstantiation), OldNNS(NNS),
13154 RequireMemberOf(RequireMemberOf) {}
13155
13156 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13157 NamedDecl *ND = Candidate.getCorrectionDecl();
13158
13159 // Keywords are not valid here.
13160 if (!ND || isa<NamespaceDecl>(ND))
13161 return false;
13162
13163 // Completely unqualified names are invalid for a 'using' declaration.
13164 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13165 return false;
13166
13167 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13168 // reject.
13169
13170 if (RequireMemberOf) {
13171 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13172 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13173 // No-one ever wants a using-declaration to name an injected-class-name
13174 // of a base class, unless they're declaring an inheriting constructor.
13175 ASTContext &Ctx = ND->getASTContext();
13176 if (!Ctx.getLangOpts().CPlusPlus11)
13177 return false;
13178 CanQualType FoundType = Ctx.getCanonicalTagType(FoundRecord);
13179
13180 // Check that the injected-class-name is named as a member of its own
13181 // type; we don't want to suggest 'using Derived::Base;', since that
13182 // means something else.
13183 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13184 ? Candidate.getCorrectionSpecifier()
13185 : OldNNS;
13186 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13187 !Ctx.hasSameType(QualType(Specifier.getAsType(), 0), FoundType))
13188 return false;
13189
13190 // Check that this inheriting constructor declaration actually names a
13191 // direct base class of the current class.
13192 bool AnyDependentBases = false;
13193 if (!findDirectBaseWithType(RequireMemberOf,
13194 Ctx.getCanonicalTagType(FoundRecord),
13195 AnyDependentBases) &&
13196 !AnyDependentBases)
13197 return false;
13198 } else {
13199 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
13200 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
13201 return false;
13202
13203 // FIXME: Check that the base class member is accessible?
13204 }
13205 } else {
13206 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13207 if (FoundRecord && FoundRecord->isInjectedClassName())
13208 return false;
13209 }
13210
13211 if (isa<TypeDecl>(ND))
13212 return HasTypenameKeyword || !IsInstantiation;
13213
13214 return !HasTypenameKeyword;
13215 }
13216
13217 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13218 return std::make_unique<UsingValidatorCCC>(*this);
13219 }
13220
13221private:
13222 bool HasTypenameKeyword;
13223 bool IsInstantiation;
13224 NestedNameSpecifier OldNNS;
13225 CXXRecordDecl *RequireMemberOf;
13226};
13227} // end anonymous namespace
13228
13230 // It is really dumb that we have to do this.
13231 LookupResult::Filter F = Previous.makeFilter();
13232 while (F.hasNext()) {
13233 NamedDecl *D = F.next();
13234 if (!isDeclInScope(D, CurContext, S))
13235 F.erase();
13236 // If we found a local extern declaration that's not ordinarily visible,
13237 // and this declaration is being added to a non-block scope, ignore it.
13238 // We're only checking for scope conflicts here, not also for violations
13239 // of the linkage rules.
13240 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13242 F.erase();
13243 }
13244 F.done();
13245}
13246
13248 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13249 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13250 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13251 const ParsedAttributesView &AttrList, bool IsInstantiation,
13252 bool IsUsingIfExists) {
13253 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13254 SourceLocation IdentLoc = NameInfo.getLoc();
13255 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13256
13257 // FIXME: We ignore attributes for now.
13258
13259 // For an inheriting constructor declaration, the name of the using
13260 // declaration is the name of a constructor in this class, not in the
13261 // base class.
13262 DeclarationNameInfo UsingName = NameInfo;
13264 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
13265 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13266 Context.getCanonicalTagType(RD)));
13267
13268 // Do the redeclaration lookup in the current scope.
13269 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13271 Previous.setHideTags(false);
13272 if (S) {
13273 LookupName(Previous, S);
13274
13276 } else {
13277 assert(IsInstantiation && "no scope in non-instantiation");
13278 if (CurContext->isRecord())
13280 else {
13281 // No redeclaration check is needed here; in non-member contexts we
13282 // diagnosed all possible conflicts with other using-declarations when
13283 // building the template:
13284 //
13285 // For a dependent non-type using declaration, the only valid case is
13286 // if we instantiate to a single enumerator. We check for conflicts
13287 // between shadow declarations we introduce, and we check in the template
13288 // definition for conflicts between a non-type using declaration and any
13289 // other declaration, which together covers all cases.
13290 //
13291 // A dependent typename using declaration will never successfully
13292 // instantiate, since it will always name a class member, so we reject
13293 // that in the template definition.
13294 }
13295 }
13296
13297 // Check for invalid redeclarations.
13298 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13299 SS, IdentLoc, Previous))
13300 return nullptr;
13301
13302 // 'using_if_exists' doesn't make sense on an inherited constructor.
13303 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13305 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13306 return nullptr;
13307 }
13308
13309 DeclContext *LookupContext = computeDeclContext(SS);
13311 if (!LookupContext || EllipsisLoc.isValid()) {
13312 NamedDecl *D;
13313 // Dependent scope, or an unexpanded pack
13314 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
13315 SS, NameInfo, IdentLoc))
13316 return nullptr;
13317
13318 if (Previous.isSingleResult() &&
13319 Previous.getFoundDecl()->isTemplateParameter())
13320 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13321
13322 if (HasTypenameKeyword) {
13323 // FIXME: not all declaration name kinds are legal here
13325 UsingLoc, TypenameLoc,
13326 QualifierLoc,
13327 IdentLoc, NameInfo.getName(),
13328 EllipsisLoc);
13329 } else {
13331 QualifierLoc, NameInfo, EllipsisLoc);
13332 }
13333 D->setAccess(AS);
13334 CurContext->addDecl(D);
13335 ProcessDeclAttributeList(S, D, AttrList);
13336 return D;
13337 }
13338
13339 auto Build = [&](bool Invalid) {
13340 UsingDecl *UD =
13341 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13342 UsingName, HasTypenameKeyword);
13343 UD->setAccess(AS);
13344 CurContext->addDecl(UD);
13345 ProcessDeclAttributeList(S, UD, AttrList);
13347 return UD;
13348 };
13349 auto BuildInvalid = [&]{ return Build(true); };
13350 auto BuildValid = [&]{ return Build(false); };
13351
13352 if (RequireCompleteDeclContext(SS, LookupContext))
13353 return BuildInvalid();
13354
13355 // Look up the target name.
13356 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13357
13358 // Unlike most lookups, we don't always want to hide tag
13359 // declarations: tag names are visible through the using declaration
13360 // even if hidden by ordinary names, *except* in a dependent context
13361 // where they may be used by two-phase lookup.
13362 if (!IsInstantiation)
13363 R.setHideTags(false);
13364
13365 // For the purposes of this lookup, we have a base object type
13366 // equal to that of the current context.
13367 if (CurContext->isRecord()) {
13368 R.setBaseObjectType(
13369 Context.getCanonicalTagType(cast<CXXRecordDecl>(CurContext)));
13370 }
13371
13372 LookupQualifiedName(R, LookupContext);
13373
13374 // Validate the context, now we have a lookup
13375 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13376 IdentLoc, &R))
13377 return nullptr;
13378
13379 if (R.empty() && IsUsingIfExists)
13381 UsingName.getName()),
13382 AS_public);
13383
13384 // Try to correct typos if possible. If constructor name lookup finds no
13385 // results, that means the named class has no explicit constructors, and we
13386 // suppressed declaring implicit ones (probably because it's dependent or
13387 // invalid).
13388 if (R.empty() &&
13390 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13391 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13392 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13393 auto *II = NameInfo.getName().getAsIdentifierInfo();
13394 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13395 CurContext->isStdNamespace() &&
13396 isa<TranslationUnitDecl>(LookupContext) &&
13397 PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&
13398 getSourceManager().isInSystemHeader(UsingLoc))
13399 return nullptr;
13400 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13401 dyn_cast<CXXRecordDecl>(CurContext));
13402 if (TypoCorrection Corrected =
13403 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13405 // We reject candidates where DroppedSpecifier == true, hence the
13406 // literal '0' below.
13407 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13408 << NameInfo.getName() << LookupContext << 0
13409 << SS.getRange());
13410
13411 // If we picked a correction with no attached Decl we can't do anything
13412 // useful with it, bail out.
13413 NamedDecl *ND = Corrected.getCorrectionDecl();
13414 if (!ND)
13415 return BuildInvalid();
13416
13417 // If we corrected to an inheriting constructor, handle it as one.
13418 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13419 if (RD && RD->isInjectedClassName()) {
13420 // The parent of the injected class name is the class itself.
13421 RD = cast<CXXRecordDecl>(RD->getParent());
13422
13423 // Fix up the information we'll use to build the using declaration.
13424 if (Corrected.WillReplaceSpecifier()) {
13426 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13427 QualifierLoc.getSourceRange());
13428 QualifierLoc = Builder.getWithLocInContext(Context);
13429 }
13430
13431 // In this case, the name we introduce is the name of a derived class
13432 // constructor.
13433 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13434 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13435 Context.getCanonicalTagType(CurClass)));
13436 UsingName.setNamedTypeInfo(nullptr);
13437 for (auto *Ctor : LookupConstructors(RD))
13438 R.addDecl(Ctor);
13439 R.resolveKind();
13440 } else {
13441 // FIXME: Pick up all the declarations if we found an overloaded
13442 // function.
13443 UsingName.setName(ND->getDeclName());
13444 R.addDecl(ND);
13445 }
13446 } else {
13447 Diag(IdentLoc, diag::err_no_member)
13448 << NameInfo.getName() << LookupContext << SS.getRange();
13449 return BuildInvalid();
13450 }
13451 }
13452
13453 if (R.isAmbiguous())
13454 return BuildInvalid();
13455
13456 if (HasTypenameKeyword) {
13457 // If we asked for a typename and got a non-type decl, error out.
13458 if (!R.getAsSingle<TypeDecl>() &&
13459 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13460 Diag(IdentLoc, diag::err_using_typename_non_type);
13461 for (const NamedDecl *D : R)
13462 Diag(D->getUnderlyingDecl()->getLocation(),
13463 diag::note_using_decl_target);
13464 return BuildInvalid();
13465 }
13466 } else {
13467 // If we asked for a non-typename and we got a type, error out,
13468 // but only if this is an instantiation of an unresolved using
13469 // decl. Otherwise just silently find the type name.
13470 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13471 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13472 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13473 return BuildInvalid();
13474 }
13475 }
13476
13477 // C++14 [namespace.udecl]p6:
13478 // A using-declaration shall not name a namespace.
13479 if (R.getAsSingle<NamespaceDecl>()) {
13480 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13481 << SS.getRange();
13482 // Suggest using 'using namespace ...' instead.
13483 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13484 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13485 return BuildInvalid();
13486 }
13487
13488 UsingDecl *UD = BuildValid();
13489
13490 // Some additional rules apply to inheriting constructors.
13491 if (UsingName.getName().getNameKind() ==
13493 // Suppress access diagnostics; the access check is instead performed at the
13494 // point of use for an inheriting constructor.
13495 R.suppressDiagnostics();
13497 return UD;
13498 }
13499
13500 for (NamedDecl *D : R) {
13501 UsingShadowDecl *PrevDecl = nullptr;
13502 if (!CheckUsingShadowDecl(UD, D, Previous, PrevDecl))
13503 BuildUsingShadowDecl(S, UD, D, PrevDecl);
13504 }
13505
13506 return UD;
13507}
13508
13510 SourceLocation UsingLoc,
13511 SourceLocation EnumLoc,
13512 SourceLocation NameLoc,
13513 TypeSourceInfo *EnumType,
13514 EnumDecl *ED) {
13515 bool Invalid = false;
13516
13517 if (CurContext->getRedeclContext()->isRecord()) {
13518 /// In class scope, check if this is a duplicate, for better a diagnostic.
13519 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13520 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13522
13524
13525 for (NamedDecl *D : Previous)
13526 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13527 if (UED->getEnumDecl() == ED) {
13528 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13529 << SourceRange(EnumLoc, NameLoc);
13530 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13531 Invalid = true;
13532 break;
13533 }
13534 }
13535
13536 if (RequireCompleteEnumDecl(ED, NameLoc))
13537 Invalid = true;
13538
13540 EnumLoc, NameLoc, EnumType);
13541 UD->setAccess(AS);
13542 CurContext->addDecl(UD);
13543
13544 if (Invalid) {
13545 UD->setInvalidDecl();
13546 return UD;
13547 }
13548
13549 // Create the shadow decls for each enumerator
13550 for (EnumConstantDecl *EC : ED->enumerators()) {
13551 UsingShadowDecl *PrevDecl = nullptr;
13552 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13555 LookupName(Previous, S);
13557
13558 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13559 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13560 }
13561
13562 return UD;
13563}
13564
13566 ArrayRef<NamedDecl *> Expansions) {
13567 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13568 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13569 isa<UsingPackDecl>(InstantiatedFrom));
13570
13571 auto *UPD =
13572 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13573 UPD->setAccess(InstantiatedFrom->getAccess());
13574 CurContext->addDecl(UPD);
13575 return UPD;
13576}
13577
13579 assert(!UD->hasTypename() && "expecting a constructor name");
13580
13581 QualType SourceType(UD->getQualifier().getAsType(), 0);
13583
13584 // Check whether the named type is a direct base class.
13585 bool AnyDependentBases = false;
13586 auto *Base =
13587 findDirectBaseWithType(TargetClass, SourceType, AnyDependentBases);
13588 if (!Base && !AnyDependentBases) {
13589 Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base)
13590 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13591 UD->setInvalidDecl();
13592 return true;
13593 }
13594
13595 if (Base)
13596 Base->setInheritConstructors();
13597
13598 return false;
13599}
13600
13602 bool HasTypenameKeyword,
13603 const CXXScopeSpec &SS,
13604 SourceLocation NameLoc,
13605 const LookupResult &Prev) {
13606 NestedNameSpecifier Qual = SS.getScopeRep();
13607
13608 // C++03 [namespace.udecl]p8:
13609 // C++0x [namespace.udecl]p10:
13610 // A using-declaration is a declaration and can therefore be used
13611 // repeatedly where (and only where) multiple declarations are
13612 // allowed.
13613 //
13614 // That's in non-member contexts.
13615 if (!CurContext->getRedeclContext()->isRecord()) {
13616 // A dependent qualifier outside a class can only ever resolve to an
13617 // enumeration type. Therefore it conflicts with any other non-type
13618 // declaration in the same scope.
13619 // FIXME: How should we check for dependent type-type conflicts at block
13620 // scope?
13621 if (Qual.isDependent() && !HasTypenameKeyword) {
13622 for (auto *D : Prev) {
13623 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13624 bool OldCouldBeEnumerator =
13626 Diag(NameLoc,
13627 OldCouldBeEnumerator ? diag::err_redefinition
13628 : diag::err_redefinition_different_kind)
13629 << Prev.getLookupName();
13630 Diag(D->getLocation(), diag::note_previous_definition);
13631 return true;
13632 }
13633 }
13634 }
13635 return false;
13636 }
13637
13638 NestedNameSpecifier CNNS = Qual.getCanonical();
13639 for (const NamedDecl *D : Prev) {
13640 bool DTypename;
13641 NestedNameSpecifier DQual = std::nullopt;
13642 if (const auto *UD = dyn_cast<UsingDecl>(D)) {
13643 DTypename = UD->hasTypename();
13644 DQual = UD->getQualifier();
13645 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13646 DTypename = false;
13647 DQual = UD->getQualifier();
13648 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13649 DTypename = true;
13650 DQual = UD->getQualifier();
13651 } else
13652 continue;
13653
13654 // using decls differ if one says 'typename' and the other doesn't.
13655 // FIXME: non-dependent using decls?
13656 if (HasTypenameKeyword != DTypename) continue;
13657
13658 // using decls differ if they name different scopes (but note that
13659 // template instantiation can cause this check to trigger when it
13660 // didn't before instantiation).
13661 if (CNNS != DQual.getCanonical())
13662 continue;
13663
13664 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13665 Diag(D->getLocation(), diag::note_using_decl) << 1;
13666 return true;
13667 }
13668
13669 return false;
13670}
13671
13672bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13673 const CXXScopeSpec &SS,
13674 const DeclarationNameInfo &NameInfo,
13675 SourceLocation NameLoc,
13676 const LookupResult *R, const UsingDecl *UD) {
13677 DeclContext *NamedContext = computeDeclContext(SS);
13678 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13679 "resolvable context must have exactly one set of decls");
13680
13681 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13682 // relationship.
13683 bool Cxx20Enumerator = false;
13684 if (NamedContext) {
13685 EnumConstantDecl *EC = nullptr;
13686 if (R)
13687 EC = R->getAsSingle<EnumConstantDecl>();
13688 else if (UD && UD->shadow_size() == 1)
13689 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13690 if (EC)
13691 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13692
13693 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13694 // C++14 [namespace.udecl]p7:
13695 // A using-declaration shall not name a scoped enumerator.
13696 // C++20 p1099 permits enumerators.
13697 if (EC && R && ED->isScoped())
13698 DiagCompat(SS.getBeginLoc(), diag_compat::using_decl_scoped_enumerator)
13699 << SS.getRange();
13700
13701 // We want to consider the scope of the enumerator
13702 NamedContext = ED->getDeclContext();
13703 }
13704 }
13705
13706 if (!CurContext->isRecord()) {
13707 // C++03 [namespace.udecl]p3:
13708 // C++0x [namespace.udecl]p8:
13709 // A using-declaration for a class member shall be a member-declaration.
13710 // C++20 [namespace.udecl]p7
13711 // ... other than an enumerator ...
13712
13713 // If we weren't able to compute a valid scope, it might validly be a
13714 // dependent class or enumeration scope. If we have a 'typename' keyword,
13715 // the scope must resolve to a class type.
13716 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13717 : !HasTypename)
13718 return false; // OK
13719
13720 Diag(NameLoc,
13721 Cxx20Enumerator
13722 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13723 : diag::err_using_decl_can_not_refer_to_class_member)
13724 << SS.getRange();
13725
13726 if (Cxx20Enumerator)
13727 return false; // OK
13728
13729 auto *RD = NamedContext
13730 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13731 : nullptr;
13732 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13733 // See if there's a helpful fixit
13734
13735 if (!R) {
13736 // We will have already diagnosed the problem on the template
13737 // definition, Maybe we should do so again?
13738 } else if (R->getAsSingle<TypeDecl>()) {
13739 if (getLangOpts().CPlusPlus11) {
13740 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13741 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13742 << diag::MemClassWorkaround::AliasDecl
13744 NameInfo.getName().getAsString() +
13745 " = ");
13746 } else {
13747 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13748 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13749 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13750 << diag::MemClassWorkaround::TypedefDecl
13751 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13753 InsertLoc, " " + NameInfo.getName().getAsString());
13754 }
13755 } else if (R->getAsSingle<VarDecl>()) {
13756 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13757 // repeating the type of the static data member here.
13758 FixItHint FixIt;
13759 if (getLangOpts().CPlusPlus11) {
13760 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13762 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13763 }
13764
13765 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13766 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13767 } else if (R->getAsSingle<EnumConstantDecl>()) {
13768 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13769 // repeating the type of the enumeration here, and we can't do so if
13770 // the type is anonymous.
13771 FixItHint FixIt;
13772 if (getLangOpts().CPlusPlus11) {
13773 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13775 UsingLoc,
13776 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13777 }
13778
13779 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13780 << (getLangOpts().CPlusPlus11
13781 ? diag::MemClassWorkaround::ConstexprVar
13782 : diag::MemClassWorkaround::ConstVar)
13783 << FixIt;
13784 }
13785 }
13786
13787 return true; // Fail
13788 }
13789
13790 // If the named context is dependent, we can't decide much.
13791 if (!NamedContext) {
13792 // FIXME: in C++0x, we can diagnose if we can prove that the
13793 // nested-name-specifier does not refer to a base class, which is
13794 // still possible in some cases.
13795
13796 // Otherwise we have to conservatively report that things might be
13797 // okay.
13798 return false;
13799 }
13800
13801 // The current scope is a record.
13802 if (!NamedContext->isRecord()) {
13803 // Ideally this would point at the last name in the specifier,
13804 // but we don't have that level of source info.
13805 Diag(SS.getBeginLoc(),
13806 Cxx20Enumerator
13807 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13808 : diag::err_using_decl_nested_name_specifier_is_not_class)
13809 << SS.getScopeRep() << SS.getRange();
13810
13811 if (Cxx20Enumerator)
13812 return false; // OK
13813
13814 return true;
13815 }
13816
13817 if (!NamedContext->isDependentContext() &&
13818 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13819 return true;
13820
13821 // C++26 [namespace.udecl]p3:
13822 // In a using-declaration used as a member-declaration, each
13823 // using-declarator shall either name an enumerator or have a
13824 // nested-name-specifier naming a base class of the current class
13825 // ([expr.prim.this]). ...
13826 // "have a nested-name-specifier naming a base class of the current class"
13827 // was introduced by CWG400.
13828
13831
13832 if (Cxx20Enumerator) {
13833 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13834 << SS.getScopeRep() << SS.getRange();
13835 return false;
13836 }
13837
13838 if (CurContext == NamedContext) {
13839 Diag(SS.getBeginLoc(),
13840 diag::err_using_decl_nested_name_specifier_is_current_class)
13841 << SS.getRange();
13842 return true;
13843 }
13844
13845 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13846 Diag(SS.getBeginLoc(),
13847 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13849 << SS.getRange();
13850 }
13851 return true;
13852 }
13853
13854 return false;
13855}
13856
13858 MultiTemplateParamsArg TemplateParamLists,
13859 SourceLocation UsingLoc, UnqualifiedId &Name,
13860 const ParsedAttributesView &AttrList,
13861 TypeResult Type, Decl *DeclFromDeclSpec) {
13862
13863 if (Type.isInvalid())
13864 return nullptr;
13865
13866 bool Invalid = false;
13868 TypeSourceInfo *TInfo = nullptr;
13869 GetTypeFromParser(Type.get(), &TInfo);
13870
13871 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13872 return nullptr;
13873
13876 Invalid = true;
13877 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13878 TInfo->getTypeLoc().getBeginLoc());
13879 }
13880
13881 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13882 TemplateParamLists.size()
13885 LookupName(Previous, S);
13886
13887 // Warn about shadowing the name of a template parameter.
13888 if (Previous.isSingleResult() &&
13889 Previous.getFoundDecl()->isTemplateParameter()) {
13891 Previous.clear();
13892 }
13893
13894 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13895 "name in alias declaration must be an identifier");
13897 Name.StartLocation,
13898 Name.Identifier, TInfo);
13899
13900 NewTD->setAccess(AS);
13901
13902 if (Invalid)
13903 NewTD->setInvalidDecl();
13904
13905 ProcessDeclAttributeList(S, NewTD, AttrList);
13906 AddPragmaAttributes(S, NewTD);
13907 ProcessAPINotes(NewTD);
13908
13910 Invalid |= NewTD->isInvalidDecl();
13911
13912 // Get the innermost enclosing declaration scope.
13913 S = S->getDeclParent();
13914
13915 bool Redeclaration = false;
13916
13917 NamedDecl *NewND;
13918 if (TemplateParamLists.size()) {
13919 TypeAliasTemplateDecl *OldDecl = nullptr;
13920 TemplateParameterList *OldTemplateParams = nullptr;
13921
13922 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13923 if (TemplateParamLists.size() != 1) {
13924 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13925 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13926 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13927 Invalid = true;
13928
13929 // Recover by picking the last non-empty template parameter list.
13930 auto It = llvm::find_if(
13931 llvm::reverse(TemplateParamLists),
13932 [](TemplateParameterList *TPL) { return !TPL->empty(); });
13933 assert(It != TemplateParamLists.rend() &&
13934 "if all template parameter lists were empty, this should have "
13935 "been rejected as an explicit specialization");
13936 TemplateParams = *It;
13937 }
13938
13939 // Check that we can declare a template here.
13940 if (CheckTemplateDeclScope(S, TemplateParams))
13941 return nullptr;
13942
13943 // Only consider previous declarations in the same scope.
13944 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13945 /*ExplicitInstantiationOrSpecialization*/false);
13946 if (!Previous.empty()) {
13947 Redeclaration = true;
13948
13949 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13950 if (!OldDecl && !Invalid) {
13951 Diag(UsingLoc, diag::err_redefinition_different_kind)
13952 << Name.Identifier;
13953
13954 NamedDecl *OldD = Previous.getRepresentativeDecl();
13955 if (OldD->getLocation().isValid())
13956 Diag(OldD->getLocation(), diag::note_previous_definition);
13957
13958 Invalid = true;
13959 }
13960
13961 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13962 if (TemplateParameterListsAreEqual(TemplateParams,
13963 OldDecl->getTemplateParameters(),
13964 /*Complain=*/true,
13966 OldTemplateParams =
13968 else
13969 Invalid = true;
13970
13971 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13972 if (!Invalid &&
13973 !Context.hasSameType(OldTD->getUnderlyingType(),
13974 NewTD->getUnderlyingType())) {
13975 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13976 // but we can't reasonably accept it.
13977 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13978 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13979 if (OldTD->getLocation().isValid())
13980 Diag(OldTD->getLocation(), diag::note_previous_definition);
13981 Invalid = true;
13982 }
13983 }
13984 }
13985
13986 // Merge any previous default template arguments into our parameters,
13987 // and check the parameter list.
13988 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13989 TPC_Other))
13990 return nullptr;
13991
13992 TypeAliasTemplateDecl *NewDecl =
13994 Name.Identifier, TemplateParams,
13995 NewTD);
13996 NewTD->setDescribedAliasTemplate(NewDecl);
13997
13998 NewDecl->setAccess(AS);
13999
14000 if (Invalid)
14001 NewDecl->setInvalidDecl();
14002 else if (OldDecl) {
14003 NewDecl->setPreviousDecl(OldDecl);
14004 CheckRedeclarationInModule(NewDecl, OldDecl);
14005 }
14006
14007 NewND = NewDecl;
14008 } else {
14009 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
14011 handleTagNumbering(TD, S);
14012 }
14014 NewND = NewTD;
14015 }
14016
14017 PushOnScopeChains(NewND, S);
14018 ActOnDocumentableDecl(NewND);
14019 return NewND;
14020}
14021
14023 SourceLocation AliasLoc,
14024 IdentifierInfo *Alias, CXXScopeSpec &SS,
14025 SourceLocation IdentLoc,
14026 IdentifierInfo *Ident) {
14027
14028 // Lookup the namespace name.
14029 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14030 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
14031
14032 if (R.isAmbiguous())
14033 return nullptr;
14034
14035 if (R.empty()) {
14036 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
14037 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
14038 return nullptr;
14039 }
14040 }
14041 assert(!R.isAmbiguous() && !R.empty());
14042 auto *ND = cast<NamespaceBaseDecl>(R.getRepresentativeDecl());
14043
14044 // Check if we have a previous declaration with the same name.
14045 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14047 LookupName(PrevR, S);
14048
14049 // Check we're not shadowing a template parameter.
14050 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14052 PrevR.clear();
14053 }
14054
14055 // Filter out any other lookup result from an enclosing scope.
14056 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
14057 /*AllowInlineNamespace*/false);
14058
14059 // Find the previous declaration and check that we can redeclare it.
14060 NamespaceAliasDecl *Prev = nullptr;
14061 if (PrevR.isSingleResult()) {
14062 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14063 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
14064 // We already have an alias with the same name that points to the same
14065 // namespace; check that it matches.
14066 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
14067 Prev = AD;
14068 } else if (isVisible(PrevDecl)) {
14069 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
14070 << Alias;
14071 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
14072 << AD->getNamespace();
14073 return nullptr;
14074 }
14075 } else if (isVisible(PrevDecl)) {
14076 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
14077 ? diag::err_redefinition
14078 : diag::err_redefinition_different_kind;
14079 Diag(AliasLoc, DiagID) << Alias;
14080 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14081 return nullptr;
14082 }
14083 }
14084
14085 // The use of a nested name specifier may trigger deprecation warnings.
14086 DiagnoseUseOfDecl(ND, IdentLoc);
14087
14089 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
14090 Alias, SS.getWithLocInContext(Context),
14091 IdentLoc, ND);
14092 if (Prev)
14093 AliasDecl->setPreviousDecl(Prev);
14094
14096 return AliasDecl;
14097}
14098
14099namespace {
14100struct SpecialMemberExceptionSpecInfo
14101 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14102 SourceLocation Loc;
14104
14105 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14108 SourceLocation Loc)
14109 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14110
14111 bool visitBase(CXXBaseSpecifier *Base);
14112 bool visitField(FieldDecl *FD);
14113
14114 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14115 unsigned Quals);
14116
14117 void visitSubobjectCall(Subobject Subobj,
14119};
14120}
14121
14122bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14123 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14124 if (!BaseClass)
14125 return false;
14126
14127 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
14128 if (auto *BaseCtor = SMOR.getMethod()) {
14129 visitSubobjectCall(Base, BaseCtor);
14130 return false;
14131 }
14132
14133 visitClassSubobject(BaseClass, Base, 0);
14134 return false;
14135}
14136
14137bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14138 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14139 FD->hasInClassInitializer()) {
14140 Expr *E = FD->getInClassInitializer();
14141 if (!E)
14142 // FIXME: It's a little wasteful to build and throw away a
14143 // CXXDefaultInitExpr here.
14144 // FIXME: We should have a single context note pointing at Loc, and
14145 // this location should be MD->getLocation() instead, since that's
14146 // the location where we actually use the default init expression.
14147 E = S.BuildCXXCtorDefaultInitExpr(Loc, FD).get();
14148 if (E)
14149 ExceptSpec.CalledExpr(E);
14150 } else if (auto *RD = S.Context.getBaseElementType(FD->getType())
14151 ->getAsCXXRecordDecl()) {
14152 visitClassSubobject(RD, FD, FD->getType().getCVRQualifiers());
14153 }
14154 return false;
14155}
14156
14157void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14158 Subobject Subobj,
14159 unsigned Quals) {
14160 FieldDecl *Field = dyn_cast<FieldDecl *>(Subobj);
14161 bool IsMutable = Field && Field->isMutable();
14162 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
14163}
14164
14165void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14166 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14167 // Note, if lookup fails, it doesn't matter what exception specification we
14168 // choose because the special member will be deleted.
14169 if (CXXMethodDecl *MD = SMOR.getMethod())
14170 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
14171}
14172
14174 llvm::APSInt Result;
14176 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
14177 ExplicitSpec.setExpr(Converted.get());
14178 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14179 ExplicitSpec.setKind(Result.getBoolValue()
14182 return true;
14183 }
14185 return false;
14186}
14187
14190 if (!ExplicitExpr->isTypeDependent() && !ExplicitExpr->containsErrors())
14192 return ES;
14193}
14194
14199 ComputingExceptionSpec CES(S, MD, Loc);
14200
14201 CXXRecordDecl *ClassDecl = MD->getParent();
14202
14203 // C++ [except.spec]p14:
14204 // An implicitly declared special member function (Clause 12) shall have an
14205 // exception-specification. [...]
14206 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14207 if (ClassDecl->isInvalidDecl())
14208 return Info.ExceptSpec;
14209
14210 // FIXME: If this diagnostic fires, we're probably missing a check for
14211 // attempting to resolve an exception specification before it's known
14212 // at a higher level.
14213 if (S.RequireCompleteType(MD->getLocation(),
14214 S.Context.getCanonicalTagType(ClassDecl),
14215 diag::err_exception_spec_incomplete_type))
14216 return Info.ExceptSpec;
14217
14218 // C++1z [except.spec]p7:
14219 // [Look for exceptions thrown by] a constructor selected [...] to
14220 // initialize a potentially constructed subobject,
14221 // C++1z [except.spec]p8:
14222 // The exception specification for an implicitly-declared destructor, or a
14223 // destructor without a noexcept-specifier, is potentially-throwing if and
14224 // only if any of the destructors for any of its potentially constructed
14225 // subojects is potentially throwing.
14226 // FIXME: We respect the first rule but ignore the "potentially constructed"
14227 // in the second rule to resolve a core issue (no number yet) that would have
14228 // us reject:
14229 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14230 // struct B : A {};
14231 // struct C : B { void f(); };
14232 // ... due to giving B::~B() a non-throwing exception specification.
14233 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14234 : Info.VisitAllBases);
14235
14236 return Info.ExceptSpec;
14237}
14238
14239namespace {
14240/// RAII object to register a special member as being currently declared.
14241struct DeclaringSpecialMember {
14242 Sema &S;
14244 Sema::ContextRAII SavedContext;
14245 bool WasAlreadyBeingDeclared;
14246
14247 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14248 : S(S), D(RD, CSM), SavedContext(S, RD) {
14249 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
14250 if (WasAlreadyBeingDeclared)
14251 // This almost never happens, but if it does, ensure that our cache
14252 // doesn't contain a stale result.
14253 S.SpecialMemberCache.clear();
14254 else {
14255 // Register a note to be produced if we encounter an error while
14256 // declaring the special member.
14257 Sema::CodeSynthesisContext Ctx;
14258 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14259 // FIXME: We don't have a location to use here. Using the class's
14260 // location maintains the fiction that we declare all special members
14261 // with the class, but (1) it's not clear that lying about that helps our
14262 // users understand what's going on, and (2) there may be outer contexts
14263 // on the stack (some of which are relevant) and printing them exposes
14264 // our lies.
14265 Ctx.PointOfInstantiation = RD->getLocation();
14266 Ctx.Entity = RD;
14267 Ctx.SpecialMember = CSM;
14268 S.pushCodeSynthesisContext(Ctx);
14269 }
14270 }
14271 ~DeclaringSpecialMember() {
14272 if (!WasAlreadyBeingDeclared) {
14273 S.SpecialMembersBeingDeclared.erase(D);
14275 }
14276 }
14277
14278 /// Are we already trying to declare this special member?
14279 bool isAlreadyBeingDeclared() const {
14280 return WasAlreadyBeingDeclared;
14281 }
14282};
14283}
14284
14286 // Look up any existing declarations, but don't trigger declaration of all
14287 // implicit special members with this name.
14288 DeclarationName Name = FD->getDeclName();
14291 for (auto *D : FD->getParent()->lookup(Name))
14292 if (auto *Acceptable = R.getAcceptableDecl(D))
14293 R.addDecl(Acceptable);
14294 R.resolveKind();
14295 R.suppressDiagnostics();
14296
14297 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14299}
14300
14301void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14302 QualType ResultTy,
14303 ArrayRef<QualType> Args) {
14304 // Build an exception specification pointing back at this constructor.
14306
14307 LangAS AS = getDefaultCXXMethodAddrSpace();
14308 if (AS != LangAS::Default) {
14309 EPI.TypeQuals.addAddressSpace(AS);
14310 }
14311
14312 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14313 SpecialMem->setType(QT);
14314
14315 // During template instantiation of implicit special member functions we need
14316 // a reliable TypeSourceInfo for the function prototype in order to allow
14317 // functions to be substituted.
14318 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14319 TypeSourceInfo *TSI =
14320 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14321 SpecialMem->setTypeSourceInfo(TSI);
14322 }
14323}
14324
14326 CXXRecordDecl *ClassDecl) {
14327 // C++ [class.ctor]p5:
14328 // A default constructor for a class X is a constructor of class X
14329 // that can be called without an argument. If there is no
14330 // user-declared constructor for class X, a default constructor is
14331 // implicitly declared. An implicitly-declared default constructor
14332 // is an inline public member of its class.
14333 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14334 "Should not build implicit default constructor!");
14335
14336 DeclaringSpecialMember DSM(*this, ClassDecl,
14338 if (DSM.isAlreadyBeingDeclared())
14339 return nullptr;
14340
14342 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14343
14344 // Create the actual constructor declaration.
14345 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14346 SourceLocation ClassLoc = ClassDecl->getLocation();
14347 DeclarationName Name
14348 = Context.DeclarationNames.getCXXConstructorName(ClassType);
14349 DeclarationNameInfo NameInfo(Name, ClassLoc);
14351 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14352 /*TInfo=*/nullptr, ExplicitSpecifier(),
14353 getCurFPFeatures().isFPConstrained(),
14354 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14357 DefaultCon->setAccess(AS_public);
14358 DefaultCon->setDefaulted();
14359
14360 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
14361
14362 if (getLangOpts().CUDA)
14363 CUDA().inferTargetForImplicitSpecialMember(
14364 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14365 /* ConstRHS */ false,
14366 /* Diagnose */ false);
14367
14368 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14369 // constructors is easy to compute.
14370 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14371
14372 // Note that we have declared this constructor.
14373 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14374
14375 Scope *S = getScopeForContext(ClassDecl);
14377
14378 if (ShouldDeleteSpecialMember(DefaultCon,
14380 SetDeclDeleted(DefaultCon, ClassLoc);
14381
14382 if (S)
14383 PushOnScopeChains(DefaultCon, S, false);
14384 ClassDecl->addDecl(DefaultCon);
14385
14386 return DefaultCon;
14387}
14388
14391 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Constructor);
14392 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14393 !Constructor->doesThisDeclarationHaveABody() &&
14394 !Constructor->isDeleted()) &&
14395 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14396 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14397 return;
14398
14399 CXXRecordDecl *ClassDecl = Constructor->getParent();
14400 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14401 if (ClassDecl->isInvalidDecl()) {
14402 return;
14403 }
14404
14406
14407 // The exception specification is needed because we are defining the
14408 // function.
14409 ResolveExceptionSpec(CurrentLocation,
14410 Constructor->getType()->castAs<FunctionProtoType>());
14411 MarkVTableUsed(CurrentLocation, ClassDecl);
14412
14413 // Add a context note for diagnostics produced after this point.
14414 Scope.addContextNote(CurrentLocation);
14415
14416 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14417 Constructor->setInvalidDecl();
14418 return;
14419 }
14420
14421 SourceLocation Loc = Constructor->getEndLoc().isValid()
14422 ? Constructor->getEndLoc()
14423 : Constructor->getLocation();
14424 Constructor->setBody(new (Context) CompoundStmt(Loc));
14425 Constructor->markUsed(Context);
14426
14428 L->CompletedImplicitDefinition(Constructor);
14429 }
14430
14431 DiagnoseUninitializedFields(*this, Constructor);
14432
14433 // The synthesized body applies the class's NSDMIs and never reaches the
14434 // normal IssueWarnings path, so run lifetime safety on it here.
14435 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14436}
14437
14439 // Perform any delayed checks on exception specifications.
14441}
14442
14443/// Find or create the fake constructor we synthesize to model constructing an
14444/// object of a derived class via a constructor of a base class.
14447 CXXConstructorDecl *BaseCtor,
14449 CXXRecordDecl *Derived = Shadow->getParent();
14450 SourceLocation UsingLoc = Shadow->getLocation();
14451
14452 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14453 // For now we use the name of the base class constructor as a member of the
14454 // derived class to indicate a (fake) inherited constructor name.
14455 DeclarationName Name = BaseCtor->getDeclName();
14456
14457 // Check to see if we already have a fake constructor for this inherited
14458 // constructor call.
14459 for (NamedDecl *Ctor : Derived->lookup(Name))
14461 ->getInheritedConstructor()
14462 .getConstructor(),
14463 BaseCtor))
14464 return cast<CXXConstructorDecl>(Ctor);
14465
14466 DeclarationNameInfo NameInfo(Name, UsingLoc);
14467 TypeSourceInfo *TInfo =
14468 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14469 FunctionProtoTypeLoc ProtoLoc =
14471
14472 // Check the inherited constructor is valid and find the list of base classes
14473 // from which it was inherited.
14474 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14475
14476 bool Constexpr = BaseCtor->isConstexpr() &&
14479 false, BaseCtor, &ICI);
14480
14482 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14483 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14484 /*isInline=*/true,
14485 /*isImplicitlyDeclared=*/true,
14487 InheritedConstructor(Shadow, BaseCtor),
14488 BaseCtor->getTrailingRequiresClause());
14489 if (Shadow->isInvalidDecl())
14490 DerivedCtor->setInvalidDecl();
14491
14492 // Build an unevaluated exception specification for this fake constructor.
14493 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14496 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14497 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14498 FPT->getParamTypes(), EPI));
14499
14500 // Build the parameter declarations.
14502 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14503 TypeSourceInfo *TInfo =
14504 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14506 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14507 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14508 PD->setScopeInfo(0, I);
14509 PD->setImplicit();
14510 // Ensure attributes are propagated onto parameters (this matters for
14511 // format, pass_object_size, ...).
14512 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14513 ParamDecls.push_back(PD);
14514 ProtoLoc.setParam(I, PD);
14515 }
14516
14517 // Set up the new constructor.
14518 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14519 DerivedCtor->setAccess(BaseCtor->getAccess());
14520 DerivedCtor->setParams(ParamDecls);
14521 Derived->addDecl(DerivedCtor);
14522
14523 if (ShouldDeleteSpecialMember(DerivedCtor,
14525 SetDeclDeleted(DerivedCtor, UsingLoc);
14526
14527 return DerivedCtor;
14528}
14529
14537
14540 CXXRecordDecl *ClassDecl = Constructor->getParent();
14541 assert(Constructor->getInheritedConstructor() &&
14542 !Constructor->doesThisDeclarationHaveABody() &&
14543 !Constructor->isDeleted());
14544 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14545 return;
14546
14547 // Initializations are performed "as if by a defaulted default constructor",
14548 // so enter the appropriate scope.
14550
14551 // The exception specification is needed because we are defining the
14552 // function.
14553 ResolveExceptionSpec(CurrentLocation,
14554 Constructor->getType()->castAs<FunctionProtoType>());
14555 MarkVTableUsed(CurrentLocation, ClassDecl);
14556
14557 // Add a context note for diagnostics produced after this point.
14558 Scope.addContextNote(CurrentLocation);
14559
14561 Constructor->getInheritedConstructor().getShadowDecl();
14562 CXXConstructorDecl *InheritedCtor =
14563 Constructor->getInheritedConstructor().getConstructor();
14564
14565 // [class.inhctor.init]p1:
14566 // initialization proceeds as if a defaulted default constructor is used to
14567 // initialize the D object and each base class subobject from which the
14568 // constructor was inherited
14569
14570 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14571 CXXRecordDecl *RD = Shadow->getParent();
14572 SourceLocation InitLoc = Shadow->getLocation();
14573
14574 // Build explicit initializers for all base classes from which the
14575 // constructor was inherited.
14577 for (bool VBase : {false, true}) {
14578 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14579 if (B.isVirtual() != VBase)
14580 continue;
14581
14582 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14583 if (!BaseRD)
14584 continue;
14585
14586 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14587 if (!BaseCtor.first)
14588 continue;
14589
14590 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14592 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14593
14594 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14595 Inits.push_back(new (Context) CXXCtorInitializer(
14596 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14597 SourceLocation()));
14598 }
14599 }
14600
14601 // We now proceed as if for a defaulted default constructor, with the relevant
14602 // initializers replaced.
14603
14604 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14605 Constructor->setInvalidDecl();
14606 return;
14607 }
14608
14609 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14610 Constructor->markUsed(Context);
14611
14613 L->CompletedImplicitDefinition(Constructor);
14614 }
14615
14616 DiagnoseUninitializedFields(*this, Constructor);
14617
14618 // The synthesized body applies the class's NSDMIs and never reaches the
14619 // normal IssueWarnings path, so run lifetime safety on it here.
14620 AnalysisWarnings.IssueWarningsForImplicitFunction(Constructor);
14621}
14622
14624 // C++ [class.dtor]p2:
14625 // If a class has no user-declared destructor, a destructor is
14626 // declared implicitly. An implicitly-declared destructor is an
14627 // inline public member of its class.
14628 assert(ClassDecl->needsImplicitDestructor());
14629
14630 DeclaringSpecialMember DSM(*this, ClassDecl,
14632 if (DSM.isAlreadyBeingDeclared())
14633 return nullptr;
14634
14636 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14637
14638 // Create the actual destructor declaration.
14639 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14640 SourceLocation ClassLoc = ClassDecl->getLocation();
14641 DeclarationName Name
14642 = Context.DeclarationNames.getCXXDestructorName(ClassType);
14643 DeclarationNameInfo NameInfo(Name, ClassLoc);
14645 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14646 getCurFPFeatures().isFPConstrained(),
14647 /*isInline=*/true,
14648 /*isImplicitlyDeclared=*/true,
14651 Destructor->setAccess(AS_public);
14652 Destructor->setDefaulted();
14653
14654 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14655
14656 if (getLangOpts().CUDA)
14657 CUDA().inferTargetForImplicitSpecialMember(
14659 /* ConstRHS */ false,
14660 /* Diagnose */ false);
14661
14662 // We don't need to use SpecialMemberIsTrivial here; triviality for
14663 // destructors is easy to compute.
14664 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14665 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14666 ClassDecl->hasTrivialDestructorForCall());
14667
14668 // Note that we have declared this destructor.
14669 ++getASTContext().NumImplicitDestructorsDeclared;
14670
14671 Scope *S = getScopeForContext(ClassDecl);
14673
14674 // We can't check whether an implicit destructor is deleted before we complete
14675 // the definition of the class, because its validity depends on the alignment
14676 // of the class. We'll check this from ActOnFields once the class is complete.
14677 if (ClassDecl->isCompleteDefinition() &&
14679 SetDeclDeleted(Destructor, ClassLoc);
14680
14681 // Introduce this destructor into its scope.
14682 if (S)
14683 PushOnScopeChains(Destructor, S, false);
14684 ClassDecl->addDecl(Destructor);
14685
14686 return Destructor;
14687}
14688
14691 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Destructor);
14692 assert((Destructor->isDefaulted() &&
14693 !Destructor->doesThisDeclarationHaveABody() &&
14694 !Destructor->isDeleted()) &&
14695 "DefineImplicitDestructor - call it for implicit default dtor");
14696 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14697 return;
14698
14699 CXXRecordDecl *ClassDecl = Destructor->getParent();
14700 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14701
14703
14704 // The exception specification is needed because we are defining the
14705 // function.
14706 ResolveExceptionSpec(CurrentLocation,
14707 Destructor->getType()->castAs<FunctionProtoType>());
14708 MarkVTableUsed(CurrentLocation, ClassDecl);
14709
14710 // Add a context note for diagnostics produced after this point.
14711 Scope.addContextNote(CurrentLocation);
14712
14714 Destructor->getParent());
14715
14717 Destructor->setInvalidDecl();
14718 return;
14719 }
14720
14721 SourceLocation Loc = Destructor->getEndLoc().isValid()
14722 ? Destructor->getEndLoc()
14723 : Destructor->getLocation();
14724 Destructor->setBody(new (Context) CompoundStmt(Loc));
14725 Destructor->markUsed(Context);
14726
14728 L->CompletedImplicitDefinition(Destructor);
14729 }
14730}
14731
14734 if (Destructor->isInvalidDecl())
14735 return;
14736
14737 CXXRecordDecl *ClassDecl = Destructor->getParent();
14738 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14739 "implicit complete dtors unneeded outside MS ABI");
14740 assert(ClassDecl->getNumVBases() > 0 &&
14741 "complete dtor only exists for classes with vbases");
14742
14744
14745 // Add a context note for diagnostics produced after this point.
14746 Scope.addContextNote(CurrentLocation);
14747
14748 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14749}
14750
14752 // If the context is an invalid C++ class, just suppress these checks.
14753 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14754 if (Record->isInvalidDecl()) {
14757 return;
14758 }
14760 }
14761}
14762
14765
14766 if (!DelayedDllExportMemberFunctions.empty()) {
14768 std::swap(DelayedDllExportMemberFunctions, WorkList);
14769 for (CXXMethodDecl *M : WorkList) {
14770 DefineDefaultedFunction(*this, M, M->getLocation());
14771
14772 // Pass the method to the consumer to get emitted. This is not necessary
14773 // for explicit instantiation definitions, as they will get emitted
14774 // anyway.
14775 if (M->getParent()->getTemplateSpecializationKind() !=
14778 }
14779 }
14780}
14781
14783 if (!DelayedDllExportClasses.empty()) {
14784 // Calling ReferenceDllExportedMembers might cause the current function to
14785 // be called again, so use a local copy of DelayedDllExportClasses.
14787 std::swap(DelayedDllExportClasses, WorkList);
14788 for (CXXRecordDecl *Class : WorkList)
14790 }
14791}
14792
14794 assert(getLangOpts().CPlusPlus11 &&
14795 "adjusting dtor exception specs was introduced in c++11");
14796
14797 if (Destructor->isDependentContext())
14798 return;
14799
14800 // C++11 [class.dtor]p3:
14801 // A declaration of a destructor that does not have an exception-
14802 // specification is implicitly considered to have the same exception-
14803 // specification as an implicit declaration.
14804 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14805 if (DtorType->hasExceptionSpec())
14806 return;
14807
14808 // Replace the destructor's type, building off the existing one. Fortunately,
14809 // the only thing of interest in the destructor type is its extended info.
14810 // The return and arguments are fixed.
14811 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14814 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14815
14816 // FIXME: If the destructor has a body that could throw, and the newly created
14817 // spec doesn't allow exceptions, we should emit a warning, because this
14818 // change in behavior can break conforming C++03 programs at runtime.
14819 // However, we don't have a body or an exception specification yet, so it
14820 // needs to be done somewhere else.
14821}
14822
14823namespace {
14824/// An abstract base class for all helper classes used in building the
14825// copy/move operators. These classes serve as factory functions and help us
14826// avoid using the same Expr* in the AST twice.
14827class ExprBuilder {
14828 ExprBuilder(const ExprBuilder&) = delete;
14829 ExprBuilder &operator=(const ExprBuilder&) = delete;
14830
14831protected:
14832 static Expr *assertNotNull(Expr *E) {
14833 assert(E && "Expression construction must not fail.");
14834 return E;
14835 }
14836
14837public:
14838 ExprBuilder() {}
14839 virtual ~ExprBuilder() {}
14840
14841 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14842};
14843
14844class RefBuilder: public ExprBuilder {
14845 VarDecl *Var;
14846 QualType VarType;
14847
14848public:
14849 Expr *build(Sema &S, SourceLocation Loc) const override {
14850 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14851 }
14852
14853 RefBuilder(VarDecl *Var, QualType VarType)
14854 : Var(Var), VarType(VarType) {}
14855};
14856
14857class ThisBuilder: public ExprBuilder {
14858public:
14859 Expr *build(Sema &S, SourceLocation Loc) const override {
14860 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14861 }
14862};
14863
14864class CastBuilder: public ExprBuilder {
14865 const ExprBuilder &Builder;
14866 QualType Type;
14868 const CXXCastPath &Path;
14869
14870public:
14871 Expr *build(Sema &S, SourceLocation Loc) const override {
14872 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14873 CK_UncheckedDerivedToBase, Kind,
14874 &Path).get());
14875 }
14876
14877 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14878 const CXXCastPath &Path)
14879 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14880};
14881
14882class DerefBuilder: public ExprBuilder {
14883 const ExprBuilder &Builder;
14884
14885public:
14886 Expr *build(Sema &S, SourceLocation Loc) const override {
14887 return assertNotNull(
14888 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14889 }
14890
14891 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14892};
14893
14894class MemberBuilder: public ExprBuilder {
14895 const ExprBuilder &Builder;
14896 QualType Type;
14897 CXXScopeSpec SS;
14898 bool IsArrow;
14899 LookupResult &MemberLookup;
14900
14901public:
14902 Expr *build(Sema &S, SourceLocation Loc) const override {
14903 return assertNotNull(S.BuildMemberReferenceExpr(
14904 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14905 nullptr, MemberLookup, nullptr, nullptr).get());
14906 }
14907
14908 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14909 LookupResult &MemberLookup)
14910 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14911 MemberLookup(MemberLookup) {}
14912};
14913
14914class MoveCastBuilder: public ExprBuilder {
14915 const ExprBuilder &Builder;
14916
14917public:
14918 Expr *build(Sema &S, SourceLocation Loc) const override {
14919 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14920 }
14921
14922 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14923};
14924
14925class LvalueConvBuilder: public ExprBuilder {
14926 const ExprBuilder &Builder;
14927
14928public:
14929 Expr *build(Sema &S, SourceLocation Loc) const override {
14930 return assertNotNull(
14931 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14932 }
14933
14934 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14935};
14936
14937class SubscriptBuilder: public ExprBuilder {
14938 const ExprBuilder &Base;
14939 const ExprBuilder &Index;
14940
14941public:
14942 Expr *build(Sema &S, SourceLocation Loc) const override {
14943 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14944 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14945 }
14946
14947 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14948 : Base(Base), Index(Index) {}
14949};
14950
14951} // end anonymous namespace
14952
14953/// When generating a defaulted copy or move assignment operator, if a field
14954/// should be copied with __builtin_memcpy rather than via explicit assignments,
14955/// do so. This optimization only applies for arrays of scalars, and for arrays
14956/// of class type where the selected copy/move-assignment operator is trivial.
14957static StmtResult
14959 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14960 // Compute the size of the memory buffer to be copied.
14961 QualType SizeType = S.Context.getSizeType();
14962 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14964
14965 // Take the address of the field references for "from" and "to". We
14966 // directly construct UnaryOperators here because semantic analysis
14967 // does not permit us to take the address of an xvalue.
14968 Expr *From = FromB.build(S, Loc);
14969 From = UnaryOperator::Create(
14970 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14971 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14972 Expr *To = ToB.build(S, Loc);
14974 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14975 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14976
14977 bool NeedsCollectableMemCpy = false;
14978 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14979 NeedsCollectableMemCpy = RD->hasObjectMember();
14980
14981 // Create a reference to the __builtin_objc_memmove_collectable function
14982 StringRef MemCpyName = NeedsCollectableMemCpy ?
14983 "__builtin_objc_memmove_collectable" :
14984 "__builtin_memcpy";
14985 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14987 S.LookupName(R, S.TUScope, true);
14988
14989 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14990 if (!MemCpy)
14991 // Something went horribly wrong earlier, and we will have complained
14992 // about it.
14993 return StmtError();
14994
14995 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14996 VK_PRValue, Loc, nullptr);
14997 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14998
14999 Expr *CallArgs[] = {
15000 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
15001 };
15002 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
15003 Loc, CallArgs, Loc);
15004
15005 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
15006 return Call.getAs<Stmt>();
15007}
15008
15009/// Builds a statement that copies/moves the given entity from \p From to
15010/// \c To.
15011///
15012/// This routine is used to copy/move the members of a class with an
15013/// implicitly-declared copy/move assignment operator. When the entities being
15014/// copied are arrays, this routine builds for loops to copy them.
15015///
15016/// \param S The Sema object used for type-checking.
15017///
15018/// \param Loc The location where the implicit copy/move is being generated.
15019///
15020/// \param T The type of the expressions being copied/moved. Both expressions
15021/// must have this type.
15022///
15023/// \param To The expression we are copying/moving to.
15024///
15025/// \param From The expression we are copying/moving from.
15026///
15027/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15028/// Otherwise, it's a non-static member subobject.
15029///
15030/// \param Copying Whether we're copying or moving.
15031///
15032/// \param Depth Internal parameter recording the depth of the recursion.
15033///
15034/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15035/// if a memcpy should be used instead.
15036static StmtResult
15038 const ExprBuilder &To, const ExprBuilder &From,
15039 bool CopyingBaseSubobject, bool Copying,
15040 unsigned Depth = 0) {
15041 // C++11 [class.copy]p28:
15042 // Each subobject is assigned in the manner appropriate to its type:
15043 //
15044 // - if the subobject is of class type, as if by a call to operator= with
15045 // the subobject as the object expression and the corresponding
15046 // subobject of x as a single function argument (as if by explicit
15047 // qualification; that is, ignoring any possible virtual overriding
15048 // functions in more derived classes);
15049 //
15050 // C++03 [class.copy]p13:
15051 // - if the subobject is of class type, the copy assignment operator for
15052 // the class is used (as if by explicit qualification; that is,
15053 // ignoring any possible virtual overriding functions in more derived
15054 // classes);
15055 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15056 // Look for operator=.
15057 DeclarationName Name
15059 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15060 S.LookupQualifiedName(OpLookup, ClassDecl, false);
15061
15062 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15063 // operator.
15064 if (!S.getLangOpts().CPlusPlus11) {
15065 LookupResult::Filter F = OpLookup.makeFilter();
15066 while (F.hasNext()) {
15067 NamedDecl *D = F.next();
15068 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
15069 if (Method->isCopyAssignmentOperator() ||
15070 (!Copying && Method->isMoveAssignmentOperator()))
15071 continue;
15072
15073 F.erase();
15074 }
15075 F.done();
15076 }
15077
15078 // Suppress the protected check (C++ [class.protected]) for each of the
15079 // assignment operators we found. This strange dance is required when
15080 // we're assigning via a base classes's copy-assignment operator. To
15081 // ensure that we're getting the right base class subobject (without
15082 // ambiguities), we need to cast "this" to that subobject type; to
15083 // ensure that we don't go through the virtual call mechanism, we need
15084 // to qualify the operator= name with the base class (see below). However,
15085 // this means that if the base class has a protected copy assignment
15086 // operator, the protected member access check will fail. So, we
15087 // rewrite "protected" access to "public" access in this case, since we
15088 // know by construction that we're calling from a derived class.
15089 if (CopyingBaseSubobject) {
15090 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15091 L != LEnd; ++L) {
15092 if (L.getAccess() == AS_protected)
15093 L.setAccess(AS_public);
15094 }
15095 }
15096
15097 // Create the nested-name-specifier that will be used to qualify the
15098 // reference to operator=; this is required to suppress the virtual
15099 // call mechanism.
15100 CXXScopeSpec SS;
15101 // FIXME: Don't canonicalize this.
15102 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
15103 SS.MakeTrivial(S.Context, NestedNameSpecifier(CanonicalT), Loc);
15104
15105 // Create the reference to operator=.
15106 ExprResult OpEqualRef
15107 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
15108 SS, /*TemplateKWLoc=*/SourceLocation(),
15109 /*FirstQualifierInScope=*/nullptr,
15110 OpLookup,
15111 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15112 /*SuppressQualifierCheck=*/true);
15113 if (OpEqualRef.isInvalid())
15114 return StmtError();
15115
15116 // Build the call to the assignment operator.
15117
15118 Expr *FromInst = From.build(S, Loc);
15119 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
15120 OpEqualRef.getAs<Expr>(),
15121 Loc, FromInst, Loc);
15122 if (Call.isInvalid())
15123 return StmtError();
15124
15125 // If we built a call to a trivial 'operator=' while copying an array,
15126 // bail out. We'll replace the whole shebang with a memcpy.
15127 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
15128 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15129 return StmtResult((Stmt*)nullptr);
15130
15131 // Convert to an expression-statement, and clean up any produced
15132 // temporaries.
15133 return S.ActOnExprStmt(Call);
15134 }
15135
15136 // - if the subobject is of scalar type, the built-in assignment
15137 // operator is used.
15139 if (!ArrayTy) {
15141 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
15142 if (Assignment.isInvalid())
15143 return StmtError();
15144 return S.ActOnExprStmt(Assignment);
15145 }
15146
15147 // - if the subobject is an array, each element is assigned, in the
15148 // manner appropriate to the element type;
15149
15150 // Construct a loop over the array bounds, e.g.,
15151 //
15152 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15153 //
15154 // that will copy each of the array elements.
15155 QualType SizeType = S.Context.getSizeType();
15156
15157 // Create the iteration variable.
15158 IdentifierInfo *IterationVarName = nullptr;
15159 {
15160 SmallString<8> Str;
15161 llvm::raw_svector_ostream OS(Str);
15162 OS << "__i" << Depth;
15163 IterationVarName = &S.Context.Idents.get(OS.str());
15164 }
15165 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
15166 IterationVarName, SizeType,
15167 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
15168 SC_None);
15169
15170 // Initialize the iteration variable to zero.
15171 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
15172 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
15173
15174 // Creates a reference to the iteration variable.
15175 RefBuilder IterationVarRef(IterationVar, SizeType);
15176 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15177
15178 // Create the DeclStmt that holds the iteration variable.
15179 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15180
15181 // Subscript the "from" and "to" expressions with the iteration variable.
15182 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15183 MoveCastBuilder FromIndexMove(FromIndexCopy);
15184 const ExprBuilder *FromIndex;
15185 if (Copying)
15186 FromIndex = &FromIndexCopy;
15187 else
15188 FromIndex = &FromIndexMove;
15189
15190 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15191
15192 // Build the copy/move for an individual element of the array.
15193 StmtResult Copy =
15195 ToIndex, *FromIndex, CopyingBaseSubobject,
15196 Copying, Depth + 1);
15197 // Bail out if copying fails or if we determined that we should use memcpy.
15198 if (Copy.isInvalid() || !Copy.get())
15199 return Copy;
15200
15201 // Create the comparison against the array bound.
15202 llvm::APInt Upper
15203 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
15205 S.Context, IterationVarRefRVal.build(S, Loc),
15206 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
15209
15210 // Create the pre-increment of the iteration variable. We can determine
15211 // whether the increment will overflow based on the value of the array
15212 // bound.
15213 Expr *Increment = UnaryOperator::Create(
15214 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
15215 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
15216
15217 // Construct the loop that copies all elements of this array.
15218 return S.ActOnForStmt(
15219 Loc, Loc, InitStmt,
15221 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
15222}
15223
15224static StmtResult
15226 const ExprBuilder &To, const ExprBuilder &From,
15227 bool CopyingBaseSubobject, bool Copying) {
15228 // Maybe we should use a memcpy?
15229 if (T->isArrayType() && !T.hasQualifiers() &&
15230 T.isTriviallyCopyableType(S.Context))
15231 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15232
15233 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15234 CopyingBaseSubobject,
15235 Copying, 0));
15236
15237 // If we ended up picking a trivial assignment operator for an array of a
15238 // non-trivially-copyable class type, just emit a memcpy.
15239 if (!Result.isInvalid() && !Result.get())
15240 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15241
15242 return Result;
15243}
15244
15246 // Note: The following rules are largely analoguous to the copy
15247 // constructor rules. Note that virtual bases are not taken into account
15248 // for determining the argument type of the operator. Note also that
15249 // operators taking an object instead of a reference are allowed.
15250 assert(ClassDecl->needsImplicitCopyAssignment());
15251
15252 DeclaringSpecialMember DSM(*this, ClassDecl,
15254 if (DSM.isAlreadyBeingDeclared())
15255 return nullptr;
15256
15258 /*Qualifier=*/std::nullopt, ClassDecl,
15259 /*OwnsTag=*/false);
15261 if (AS != LangAS::Default)
15262 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15263 QualType RetType = Context.getLValueReferenceType(ArgType);
15264 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15265 if (Const)
15266 ArgType = ArgType.withConst();
15267
15268 ArgType = Context.getLValueReferenceType(ArgType);
15269
15271 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
15272
15273 // An implicitly-declared copy assignment operator is an inline public
15274 // member of its class.
15275 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15276 SourceLocation ClassLoc = ClassDecl->getLocation();
15277 DeclarationNameInfo NameInfo(Name, ClassLoc);
15279 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15280 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15281 getCurFPFeatures().isFPConstrained(),
15282 /*isInline=*/true,
15284 SourceLocation());
15285 CopyAssignment->setAccess(AS_public);
15286 CopyAssignment->setDefaulted();
15287 CopyAssignment->setImplicit();
15288
15289 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15290
15291 if (getLangOpts().CUDA)
15292 CUDA().inferTargetForImplicitSpecialMember(
15294 /* ConstRHS */ Const,
15295 /* Diagnose */ false);
15296
15297 // Add the parameter to the operator.
15299 ClassLoc, ClassLoc,
15300 /*Id=*/nullptr, ArgType,
15301 /*TInfo=*/nullptr, SC_None,
15302 nullptr);
15303 CopyAssignment->setParams(FromParam);
15304
15305 CopyAssignment->setTrivial(
15309 : ClassDecl->hasTrivialCopyAssignment());
15310
15311 // Note that we have added this copy-assignment operator.
15312 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15313
15314 Scope *S = getScopeForContext(ClassDecl);
15316
15320 SetDeclDeleted(CopyAssignment, ClassLoc);
15321 }
15322
15323 if (S)
15325 ClassDecl->addDecl(CopyAssignment);
15326
15327 return CopyAssignment;
15328}
15329
15330/// Diagnose an implicit copy operation for a class which is odr-used, but
15331/// which is deprecated because the class has a user-declared copy constructor,
15332/// copy assignment operator, or destructor.
15334 assert(CopyOp->isImplicit());
15335
15336 CXXRecordDecl *RD = CopyOp->getParent();
15337 CXXMethodDecl *UserDeclaredOperation = nullptr;
15338
15339 if (RD->hasUserDeclaredDestructor()) {
15340 UserDeclaredOperation = RD->getDestructor();
15341 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15343 // Find any user-declared copy constructor.
15344 for (auto *I : RD->ctors()) {
15345 if (I->isCopyConstructor()) {
15346 UserDeclaredOperation = I;
15347 break;
15348 }
15349 }
15350 assert(UserDeclaredOperation);
15351 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15353 // Find any user-declared move assignment operator.
15354 for (auto *I : RD->methods()) {
15355 if (I->isCopyAssignmentOperator()) {
15356 UserDeclaredOperation = I;
15357 break;
15358 }
15359 }
15360 assert(UserDeclaredOperation);
15361 }
15362
15363 if (UserDeclaredOperation) {
15364 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15365 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15366 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15367 unsigned DiagID =
15368 (UDOIsUserProvided && UDOIsDestructor)
15369 ? diag::warn_deprecated_copy_with_user_provided_dtor
15370 : (UDOIsUserProvided && !UDOIsDestructor)
15371 ? diag::warn_deprecated_copy_with_user_provided_copy
15372 : (!UDOIsUserProvided && UDOIsDestructor)
15373 ? diag::warn_deprecated_copy_with_dtor
15374 : diag::warn_deprecated_copy;
15375 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15376 << RD << IsCopyAssignment;
15377 }
15378}
15379
15381 CXXMethodDecl *CopyAssignOperator) {
15382 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyAssignOperator);
15383 assert((CopyAssignOperator->isDefaulted() &&
15384 CopyAssignOperator->isOverloadedOperator() &&
15385 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15386 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15387 !CopyAssignOperator->isDeleted()) &&
15388 "DefineImplicitCopyAssignment called for wrong function");
15389 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15390 return;
15391
15392 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15393 if (ClassDecl->isInvalidDecl()) {
15394 CopyAssignOperator->setInvalidDecl();
15395 return;
15396 }
15397
15398 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15399
15400 // The exception specification is needed because we are defining the
15401 // function.
15402 ResolveExceptionSpec(CurrentLocation,
15403 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15404
15405 // Add a context note for diagnostics produced after this point.
15406 Scope.addContextNote(CurrentLocation);
15407
15408 // C++11 [class.copy]p18:
15409 // The [definition of an implicitly declared copy assignment operator] is
15410 // deprecated if the class has a user-declared copy constructor or a
15411 // user-declared destructor.
15412 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15413 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15414
15415 // C++0x [class.copy]p30:
15416 // The implicitly-defined or explicitly-defaulted copy assignment operator
15417 // for a non-union class X performs memberwise copy assignment of its
15418 // subobjects. The direct base classes of X are assigned first, in the
15419 // order of their declaration in the base-specifier-list, and then the
15420 // immediate non-static data members of X are assigned, in the order in
15421 // which they were declared in the class definition.
15422
15423 // The statements that form the synthesized function body.
15424 SmallVector<Stmt*, 8> Statements;
15425
15426 // The parameter for the "other" object, which we are copying from.
15427 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15428 Qualifiers OtherQuals = Other->getType().getQualifiers();
15429 QualType OtherRefType = Other->getType();
15430 if (OtherRefType->isLValueReferenceType()) {
15431 OtherRefType = OtherRefType->getPointeeType();
15432 OtherQuals = OtherRefType.getQualifiers();
15433 }
15434
15435 // Our location for everything implicitly-generated.
15436 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15437 ? CopyAssignOperator->getEndLoc()
15438 : CopyAssignOperator->getLocation();
15439
15440 // Builds a DeclRefExpr for the "other" object.
15441 RefBuilder OtherRef(Other, OtherRefType);
15442
15443 // Builds the function object parameter.
15444 std::optional<ThisBuilder> This;
15445 std::optional<DerefBuilder> DerefThis;
15446 std::optional<RefBuilder> ExplicitObject;
15447 bool IsArrow = false;
15448 QualType ObjectType;
15449 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15450 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15451 if (ObjectType->isReferenceType())
15452 ObjectType = ObjectType->getPointeeType();
15453 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15454 } else {
15455 ObjectType = getCurrentThisType();
15456 This.emplace();
15457 DerefThis.emplace(*This);
15458 IsArrow = !LangOpts.HLSL;
15459 }
15460 ExprBuilder &ObjectParameter =
15461 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15462 : static_cast<ExprBuilder &>(*This);
15463
15464 // Assign base classes.
15465 bool Invalid = false;
15466 for (auto &Base : ClassDecl->bases()) {
15467 // Form the assignment:
15468 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15469 QualType BaseType = Base.getType().getUnqualifiedType();
15470 if (!BaseType->isRecordType()) {
15471 Invalid = true;
15472 continue;
15473 }
15474
15475 CXXCastPath BasePath;
15476 BasePath.push_back(&Base);
15477
15478 // Construct the "from" expression, which is an implicit cast to the
15479 // appropriately-qualified base type.
15480 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15481 VK_LValue, BasePath);
15482
15483 // Dereference "this".
15484 CastBuilder To(
15485 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15486 : static_cast<ExprBuilder &>(*DerefThis),
15487 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15488 VK_LValue, BasePath);
15489
15490 // Build the copy.
15491 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15492 To, From,
15493 /*CopyingBaseSubobject=*/true,
15494 /*Copying=*/true);
15495 if (Copy.isInvalid()) {
15496 CopyAssignOperator->setInvalidDecl();
15497 return;
15498 }
15499
15500 // Success! Record the copy.
15501 Statements.push_back(Copy.getAs<Expr>());
15502 }
15503
15504 // A defaulted copy assignment operator for a union copies the object
15505 // representation as if by a memcpy, the same way the defaulted union copy
15506 // constructor does. The memberwise loop below skips union members.
15507 if (ClassDecl->isUnion()) {
15508 ExprBuilder &To = ExplicitObject
15509 ? static_cast<ExprBuilder &>(*ExplicitObject)
15510 : static_cast<ExprBuilder &>(*DerefThis);
15511 // Copying the object representation is correct even for a union that is
15512 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15513 // here. Ignoring warnings rather than casting the arguments to void*
15514 // keeps them typed, which preserves their address space.
15515 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15517 *this, Loc, Context.getCanonicalTagType(ClassDecl), To, OtherRef);
15518 if (Copy.isInvalid()) {
15519 CopyAssignOperator->setInvalidDecl();
15520 return;
15521 }
15522 Statements.push_back(Copy.getAs<Stmt>());
15523 }
15524
15525 // Assign non-static members.
15526 for (auto *Field : ClassDecl->fields()) {
15527 // Union members are copied by the whole-object memcpy emitted above.
15528 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15529 continue;
15530
15531 if (Field->isInvalidDecl()) {
15532 Invalid = true;
15533 continue;
15534 }
15535
15536 // Check for members of reference type; we can't copy those.
15537 if (Field->getType()->isReferenceType()) {
15538 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15539 << Context.getCanonicalTagType(ClassDecl) << 0
15540 << Field->getDeclName();
15541 Diag(Field->getLocation(), diag::note_declared_at);
15542 Invalid = true;
15543 continue;
15544 }
15545
15546 // Check for members of const-qualified, non-class type.
15547 QualType BaseType = Context.getBaseElementType(Field->getType());
15548 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15549 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15550 << Context.getCanonicalTagType(ClassDecl) << 1
15551 << Field->getDeclName();
15552 Diag(Field->getLocation(), diag::note_declared_at);
15553 Invalid = true;
15554 continue;
15555 }
15556
15557 // Suppress assigning zero-width bitfields.
15558 if (Field->isZeroLengthBitField())
15559 continue;
15560
15561 QualType FieldType = Field->getType().getNonReferenceType();
15562 if (FieldType->isIncompleteArrayType()) {
15563 assert(ClassDecl->hasFlexibleArrayMember() &&
15564 "Incomplete array type is not valid");
15565 continue;
15566 }
15567
15568 // Build references to the field in the object we're copying from and to.
15569 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15571 MemberLookup.addDecl(Field);
15572 MemberLookup.resolveKind();
15573
15574 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15575 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15576 // Build the copy of this field.
15577 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15578 To, From,
15579 /*CopyingBaseSubobject=*/false,
15580 /*Copying=*/true);
15581 if (Copy.isInvalid()) {
15582 CopyAssignOperator->setInvalidDecl();
15583 return;
15584 }
15585
15586 // Success! Record the copy.
15587 Statements.push_back(Copy.getAs<Stmt>());
15588 }
15589
15590 if (!Invalid) {
15591 // Add a "return *this;"
15592 Expr *ThisExpr =
15593 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15594 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15595 : static_cast<ExprBuilder &>(*DerefThis))
15596 .build(*this, Loc);
15597 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15598 if (Return.isInvalid())
15599 Invalid = true;
15600 else
15601 Statements.push_back(Return.getAs<Stmt>());
15602 }
15603
15604 if (Invalid) {
15605 CopyAssignOperator->setInvalidDecl();
15606 return;
15607 }
15608
15609 StmtResult Body;
15610 {
15611 CompoundScopeRAII CompoundScope(*this);
15612 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15613 /*isStmtExpr=*/false);
15614 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15615 }
15616 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15617 CopyAssignOperator->markUsed(Context);
15618
15620 L->CompletedImplicitDefinition(CopyAssignOperator);
15621 }
15622}
15623
15625 assert(ClassDecl->needsImplicitMoveAssignment());
15626
15627 DeclaringSpecialMember DSM(*this, ClassDecl,
15629 if (DSM.isAlreadyBeingDeclared())
15630 return nullptr;
15631
15632 // Note: The following rules are largely analoguous to the move
15633 // constructor rules.
15634
15636 /*Qualifier=*/std::nullopt, ClassDecl,
15637 /*OwnsTag=*/false);
15639 if (AS != LangAS::Default)
15640 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15641 QualType RetType = Context.getLValueReferenceType(ArgType);
15642 ArgType = Context.getRValueReferenceType(ArgType);
15643
15645 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15646
15647 // An implicitly-declared move assignment operator is an inline public
15648 // member of its class.
15649 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15650 SourceLocation ClassLoc = ClassDecl->getLocation();
15651 DeclarationNameInfo NameInfo(Name, ClassLoc);
15653 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15654 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15655 getCurFPFeatures().isFPConstrained(),
15656 /*isInline=*/true,
15658 SourceLocation());
15659 MoveAssignment->setAccess(AS_public);
15660 MoveAssignment->setDefaulted();
15661 MoveAssignment->setImplicit();
15662
15663 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15664
15665 if (getLangOpts().CUDA)
15666 CUDA().inferTargetForImplicitSpecialMember(
15668 /* ConstRHS */ false,
15669 /* Diagnose */ false);
15670
15671 // Add the parameter to the operator.
15673 ClassLoc, ClassLoc,
15674 /*Id=*/nullptr, ArgType,
15675 /*TInfo=*/nullptr, SC_None,
15676 nullptr);
15677 MoveAssignment->setParams(FromParam);
15678
15679 MoveAssignment->setTrivial(
15683 : ClassDecl->hasTrivialMoveAssignment());
15684
15685 // Note that we have added this copy-assignment operator.
15686 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15687
15688 Scope *S = getScopeForContext(ClassDecl);
15690
15694 SetDeclDeleted(MoveAssignment, ClassLoc);
15695 }
15696
15697 if (S)
15699 ClassDecl->addDecl(MoveAssignment);
15700
15701 return MoveAssignment;
15702}
15703
15704/// Check if we're implicitly defining a move assignment operator for a class
15705/// with virtual bases. Such a move assignment might move-assign the virtual
15706/// base multiple times.
15708 SourceLocation CurrentLocation) {
15709 assert(!Class->isDependentContext() && "should not define dependent move");
15710
15711 // Only a virtual base could get implicitly move-assigned multiple times.
15712 // Only a non-trivial move assignment can observe this. We only want to
15713 // diagnose if we implicitly define an assignment operator that assigns
15714 // two base classes, both of which move-assign the same virtual base.
15715 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15716 Class->getNumBases() < 2)
15717 return;
15718
15720 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15721 VBaseMap VBases;
15722
15723 for (auto &BI : Class->bases()) {
15724 Worklist.push_back(&BI);
15725 while (!Worklist.empty()) {
15726 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15727 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15728
15729 // If the base has no non-trivial move assignment operators,
15730 // we don't care about moves from it.
15731 if (!Base->hasNonTrivialMoveAssignment())
15732 continue;
15733
15734 // If there's nothing virtual here, skip it.
15735 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15736 continue;
15737
15738 // If we're not actually going to call a move assignment for this base,
15739 // or the selected move assignment is trivial, skip it.
15742 /*ConstArg*/ false, /*VolatileArg*/ false,
15743 /*RValueThis*/ true, /*ConstThis*/ false,
15744 /*VolatileThis*/ false);
15745 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15747 continue;
15748
15749 if (BaseSpec->isVirtual()) {
15750 // We're going to move-assign this virtual base, and its move
15751 // assignment operator is not trivial. If this can happen for
15752 // multiple distinct direct bases of Class, diagnose it. (If it
15753 // only happens in one base, we'll diagnose it when synthesizing
15754 // that base class's move assignment operator.)
15755 CXXBaseSpecifier *&Existing =
15756 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15757 .first->second;
15758 if (Existing && Existing != &BI) {
15759 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15760 << Class << Base;
15761 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15762 << (Base->getCanonicalDecl() ==
15764 << Base << Existing->getType() << Existing->getSourceRange();
15765 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15766 << (Base->getCanonicalDecl() ==
15767 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15768 << Base << BI.getType() << BaseSpec->getSourceRange();
15769
15770 // Only diagnose each vbase once.
15771 Existing = nullptr;
15772 }
15773 } else {
15774 // Only walk over bases that have defaulted move assignment operators.
15775 // We assume that any user-provided move assignment operator handles
15776 // the multiple-moves-of-vbase case itself somehow.
15777 if (!SMOR.getMethod()->isDefaulted())
15778 continue;
15779
15780 // We're going to move the base classes of Base. Add them to the list.
15781 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15782 }
15783 }
15784 }
15785}
15786
15788 CXXMethodDecl *MoveAssignOperator) {
15789 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveAssignOperator);
15790 assert((MoveAssignOperator->isDefaulted() &&
15791 MoveAssignOperator->isOverloadedOperator() &&
15792 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15793 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15794 !MoveAssignOperator->isDeleted()) &&
15795 "DefineImplicitMoveAssignment called for wrong function");
15796 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15797 return;
15798
15799 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15800 if (ClassDecl->isInvalidDecl()) {
15801 MoveAssignOperator->setInvalidDecl();
15802 return;
15803 }
15804
15805 // C++0x [class.copy]p28:
15806 // The implicitly-defined or move assignment operator for a non-union class
15807 // X performs memberwise move assignment of its subobjects. The direct base
15808 // classes of X are assigned first, in the order of their declaration in the
15809 // base-specifier-list, and then the immediate non-static data members of X
15810 // are assigned, in the order in which they were declared in the class
15811 // definition.
15812
15813 // Issue a warning if our implicit move assignment operator will move
15814 // from a virtual base more than once.
15815 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15816
15817 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15818
15819 // The exception specification is needed because we are defining the
15820 // function.
15821 ResolveExceptionSpec(CurrentLocation,
15822 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15823
15824 // Add a context note for diagnostics produced after this point.
15825 Scope.addContextNote(CurrentLocation);
15826
15827 // The statements that form the synthesized function body.
15828 SmallVector<Stmt*, 8> Statements;
15829
15830 // The parameter for the "other" object, which we are move from.
15831 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15832 QualType OtherRefType =
15833 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15834
15835 // Our location for everything implicitly-generated.
15836 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15837 ? MoveAssignOperator->getEndLoc()
15838 : MoveAssignOperator->getLocation();
15839
15840 // Builds a reference to the "other" object.
15841 RefBuilder OtherRef(Other, OtherRefType);
15842 // Cast to rvalue.
15843 MoveCastBuilder MoveOther(OtherRef);
15844
15845 // Builds the function object parameter.
15846 std::optional<ThisBuilder> This;
15847 std::optional<DerefBuilder> DerefThis;
15848 std::optional<RefBuilder> ExplicitObject;
15849 QualType ObjectType;
15850 bool IsArrow = false;
15851 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15852 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15853 if (ObjectType->isReferenceType())
15854 ObjectType = ObjectType->getPointeeType();
15855 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15856 } else {
15857 ObjectType = getCurrentThisType();
15858 This.emplace();
15859 DerefThis.emplace(*This);
15860 IsArrow = !getLangOpts().HLSL;
15861 }
15862 ExprBuilder &ObjectParameter =
15863 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15864
15865 // Assign base classes.
15866 bool Invalid = false;
15867 for (auto &Base : ClassDecl->bases()) {
15868 // C++11 [class.copy]p28:
15869 // It is unspecified whether subobjects representing virtual base classes
15870 // are assigned more than once by the implicitly-defined copy assignment
15871 // operator.
15872 // FIXME: Do not assign to a vbase that will be assigned by some other base
15873 // class. For a move-assignment, this can result in the vbase being moved
15874 // multiple times.
15875
15876 // Form the assignment:
15877 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15878 QualType BaseType = Base.getType().getUnqualifiedType();
15879 if (!BaseType->isRecordType()) {
15880 Invalid = true;
15881 continue;
15882 }
15883
15884 CXXCastPath BasePath;
15885 BasePath.push_back(&Base);
15886
15887 // Construct the "from" expression, which is an implicit cast to the
15888 // appropriately-qualified base type.
15889 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15890
15891 // Implicitly cast "this" to the appropriately-qualified base type.
15892 // Dereference "this".
15893 CastBuilder To(
15894 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15895 : static_cast<ExprBuilder &>(*DerefThis),
15896 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15897 VK_LValue, BasePath);
15898
15899 // Build the move.
15900 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15901 To, From,
15902 /*CopyingBaseSubobject=*/true,
15903 /*Copying=*/false);
15904 if (Move.isInvalid()) {
15905 MoveAssignOperator->setInvalidDecl();
15906 return;
15907 }
15908
15909 // Success! Record the move.
15910 Statements.push_back(Move.getAs<Expr>());
15911 }
15912
15913 // A defaulted move assignment operator for a union copies the object
15914 // representation as if by a memcpy, the same way the defaulted union copy
15915 // constructor does. The memberwise loop below skips union members.
15916 if (ClassDecl->isUnion()) {
15917 ExprBuilder &To = ExplicitObject
15918 ? static_cast<ExprBuilder &>(*ExplicitObject)
15919 : static_cast<ExprBuilder &>(*DerefThis);
15920 // Copying the object representation is correct even for a union that is
15921 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15922 // here. Ignoring warnings rather than casting the arguments to void*
15923 // keeps them typed, which preserves their address space.
15924 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15926 *this, Loc, Context.getCanonicalTagType(ClassDecl), To, OtherRef);
15927 if (Copy.isInvalid()) {
15928 MoveAssignOperator->setInvalidDecl();
15929 return;
15930 }
15931 Statements.push_back(Copy.getAs<Stmt>());
15932 }
15933
15934 // Assign non-static members.
15935 for (auto *Field : ClassDecl->fields()) {
15936 // Union members are copied by the whole-object memcpy emitted above.
15937 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15938 continue;
15939
15940 if (Field->isInvalidDecl()) {
15941 Invalid = true;
15942 continue;
15943 }
15944
15945 // Check for members of reference type; we can't move those.
15946 if (Field->getType()->isReferenceType()) {
15947 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15948 << Context.getCanonicalTagType(ClassDecl) << 0
15949 << Field->getDeclName();
15950 Diag(Field->getLocation(), diag::note_declared_at);
15951 Invalid = true;
15952 continue;
15953 }
15954
15955 // Check for members of const-qualified, non-class type.
15956 QualType BaseType = Context.getBaseElementType(Field->getType());
15957 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15958 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15959 << Context.getCanonicalTagType(ClassDecl) << 1
15960 << Field->getDeclName();
15961 Diag(Field->getLocation(), diag::note_declared_at);
15962 Invalid = true;
15963 continue;
15964 }
15965
15966 // Suppress assigning zero-width bitfields.
15967 if (Field->isZeroLengthBitField())
15968 continue;
15969
15970 QualType FieldType = Field->getType().getNonReferenceType();
15971 if (FieldType->isIncompleteArrayType()) {
15972 assert(ClassDecl->hasFlexibleArrayMember() &&
15973 "Incomplete array type is not valid");
15974 continue;
15975 }
15976
15977 // Build references to the field in the object we're copying from and to.
15978 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15980 MemberLookup.addDecl(Field);
15981 MemberLookup.resolveKind();
15982 MemberBuilder From(MoveOther, OtherRefType,
15983 /*IsArrow=*/false, MemberLookup);
15984 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15985
15986 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15987 "Member reference with rvalue base must be rvalue except for reference "
15988 "members, which aren't allowed for move assignment.");
15989
15990 // Build the move of this field.
15991 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15992 To, From,
15993 /*CopyingBaseSubobject=*/false,
15994 /*Copying=*/false);
15995 if (Move.isInvalid()) {
15996 MoveAssignOperator->setInvalidDecl();
15997 return;
15998 }
15999
16000 // Success! Record the copy.
16001 Statements.push_back(Move.getAs<Stmt>());
16002 }
16003
16004 if (!Invalid) {
16005 // Add a "return *this;"
16006 Expr *ThisExpr =
16007 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16008 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
16009 : static_cast<ExprBuilder &>(*DerefThis))
16010 .build(*this, Loc);
16011
16012 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
16013 if (Return.isInvalid())
16014 Invalid = true;
16015 else
16016 Statements.push_back(Return.getAs<Stmt>());
16017 }
16018
16019 if (Invalid) {
16020 MoveAssignOperator->setInvalidDecl();
16021 return;
16022 }
16023
16024 StmtResult Body;
16025 {
16026 CompoundScopeRAII CompoundScope(*this);
16027 Body = ActOnCompoundStmt(Loc, Loc, Statements,
16028 /*isStmtExpr=*/false);
16029 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
16030 }
16031 MoveAssignOperator->setBody(Body.getAs<Stmt>());
16032 MoveAssignOperator->markUsed(Context);
16033
16035 L->CompletedImplicitDefinition(MoveAssignOperator);
16036 }
16037}
16038
16040 CXXRecordDecl *ClassDecl) {
16041 // C++ [class.copy]p4:
16042 // If the class definition does not explicitly declare a copy
16043 // constructor, one is declared implicitly.
16044 assert(ClassDecl->needsImplicitCopyConstructor());
16045
16046 DeclaringSpecialMember DSM(*this, ClassDecl,
16048 if (DSM.isAlreadyBeingDeclared())
16049 return nullptr;
16050
16051 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16052 /*Qualifier=*/std::nullopt, ClassDecl,
16053 /*OwnsTag=*/false);
16054 QualType ArgType = ClassType;
16055 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
16056 if (Const)
16057 ArgType = ArgType.withConst();
16058
16060 if (AS != LangAS::Default)
16061 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
16062
16063 ArgType = Context.getLValueReferenceType(ArgType);
16064
16066 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
16067
16068 DeclarationName Name
16069 = Context.DeclarationNames.getCXXConstructorName(
16070 Context.getCanonicalType(ClassType));
16071 SourceLocation ClassLoc = ClassDecl->getLocation();
16072 DeclarationNameInfo NameInfo(Name, ClassLoc);
16073
16074 // An implicitly-declared copy constructor is an inline public
16075 // member of its class.
16077 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16078 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16079 /*isInline=*/true,
16080 /*isImplicitlyDeclared=*/true,
16083 CopyConstructor->setAccess(AS_public);
16084 CopyConstructor->setDefaulted();
16085
16086 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
16087
16088 if (getLangOpts().CUDA)
16089 CUDA().inferTargetForImplicitSpecialMember(
16091 /* ConstRHS */ Const,
16092 /* Diagnose */ false);
16093
16094 // During template instantiation of special member functions we need a
16095 // reliable TypeSourceInfo for the parameter types in order to allow functions
16096 // to be substituted.
16097 TypeSourceInfo *TSI = nullptr;
16098 if (inTemplateInstantiation() && ClassDecl->isLambda())
16099 TSI = Context.getTrivialTypeSourceInfo(ArgType);
16100
16101 // Add the parameter to the constructor.
16102 ParmVarDecl *FromParam =
16103 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
16104 /*IdentifierInfo=*/nullptr, ArgType,
16105 /*TInfo=*/TSI, SC_None, nullptr);
16106 CopyConstructor->setParams(FromParam);
16107
16108 CopyConstructor->setTrivial(
16112 : ClassDecl->hasTrivialCopyConstructor());
16113
16114 CopyConstructor->setTrivialForCall(
16115 ClassDecl->hasAttr<TrivialABIAttr>() ||
16120 : ClassDecl->hasTrivialCopyConstructorForCall()));
16121
16122 // Note that we have declared this constructor.
16123 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16124
16125 Scope *S = getScopeForContext(ClassDecl);
16127
16132 }
16133
16134 if (S)
16136 ClassDecl->addDecl(CopyConstructor);
16137
16138 return CopyConstructor;
16139}
16140
16143 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyConstructor);
16144 assert((CopyConstructor->isDefaulted() &&
16145 CopyConstructor->isCopyConstructor() &&
16146 !CopyConstructor->doesThisDeclarationHaveABody() &&
16147 !CopyConstructor->isDeleted()) &&
16148 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16149 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16150 return;
16151
16152 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16153 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16154
16156
16157 // The exception specification is needed because we are defining the
16158 // function.
16159 ResolveExceptionSpec(CurrentLocation,
16160 CopyConstructor->getType()->castAs<FunctionProtoType>());
16161 MarkVTableUsed(CurrentLocation, ClassDecl);
16162
16163 // Add a context note for diagnostics produced after this point.
16164 Scope.addContextNote(CurrentLocation);
16165
16166 // C++11 [class.copy]p7:
16167 // The [definition of an implicitly declared copy constructor] is
16168 // deprecated if the class has a user-declared copy assignment operator
16169 // or a user-declared destructor.
16170 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16172
16173 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
16174 CopyConstructor->setInvalidDecl();
16175 } else {
16176 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16177 ? CopyConstructor->getEndLoc()
16178 : CopyConstructor->getLocation();
16179 Sema::CompoundScopeRAII CompoundScope(*this);
16180 CopyConstructor->setBody(
16181 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16182 CopyConstructor->markUsed(Context);
16183 }
16184
16186 L->CompletedImplicitDefinition(CopyConstructor);
16187 }
16188}
16189
16191 CXXRecordDecl *ClassDecl) {
16192 assert(ClassDecl->needsImplicitMoveConstructor());
16193
16194 DeclaringSpecialMember DSM(*this, ClassDecl,
16196 if (DSM.isAlreadyBeingDeclared())
16197 return nullptr;
16198
16199 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16200 /*Qualifier=*/std::nullopt, ClassDecl,
16201 /*OwnsTag=*/false);
16202
16203 QualType ArgType = ClassType;
16205 if (AS != LangAS::Default)
16206 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
16207 ArgType = Context.getRValueReferenceType(ArgType);
16208
16210 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
16211
16212 DeclarationName Name
16213 = Context.DeclarationNames.getCXXConstructorName(
16214 Context.getCanonicalType(ClassType));
16215 SourceLocation ClassLoc = ClassDecl->getLocation();
16216 DeclarationNameInfo NameInfo(Name, ClassLoc);
16217
16218 // C++11 [class.copy]p11:
16219 // An implicitly-declared copy/move constructor is an inline public
16220 // member of its class.
16222 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16223 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16224 /*isInline=*/true,
16225 /*isImplicitlyDeclared=*/true,
16228 MoveConstructor->setAccess(AS_public);
16229 MoveConstructor->setDefaulted();
16230
16231 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
16232
16233 if (getLangOpts().CUDA)
16234 CUDA().inferTargetForImplicitSpecialMember(
16236 /* ConstRHS */ false,
16237 /* Diagnose */ false);
16238
16239 // Add the parameter to the constructor.
16241 ClassLoc, ClassLoc,
16242 /*IdentifierInfo=*/nullptr,
16243 ArgType, /*TInfo=*/nullptr,
16244 SC_None, nullptr);
16245 MoveConstructor->setParams(FromParam);
16246
16247 MoveConstructor->setTrivial(
16251 : ClassDecl->hasTrivialMoveConstructor());
16252
16253 MoveConstructor->setTrivialForCall(
16254 ClassDecl->hasAttr<TrivialABIAttr>() ||
16259 : ClassDecl->hasTrivialMoveConstructorForCall()));
16260
16261 // Note that we have declared this constructor.
16262 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16263
16264 Scope *S = getScopeForContext(ClassDecl);
16266
16271 }
16272
16273 if (S)
16275 ClassDecl->addDecl(MoveConstructor);
16276
16277 return MoveConstructor;
16278}
16279
16282 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveConstructor);
16283 assert((MoveConstructor->isDefaulted() &&
16284 MoveConstructor->isMoveConstructor() &&
16285 !MoveConstructor->doesThisDeclarationHaveABody() &&
16286 !MoveConstructor->isDeleted()) &&
16287 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16288 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16289 return;
16290
16291 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16292 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16293
16295
16296 // The exception specification is needed because we are defining the
16297 // function.
16298 ResolveExceptionSpec(CurrentLocation,
16299 MoveConstructor->getType()->castAs<FunctionProtoType>());
16300 MarkVTableUsed(CurrentLocation, ClassDecl);
16301
16302 // Add a context note for diagnostics produced after this point.
16303 Scope.addContextNote(CurrentLocation);
16304
16305 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
16306 MoveConstructor->setInvalidDecl();
16307 } else {
16308 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16309 ? MoveConstructor->getEndLoc()
16310 : MoveConstructor->getLocation();
16311 Sema::CompoundScopeRAII CompoundScope(*this);
16312 MoveConstructor->setBody(
16313 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16314 MoveConstructor->markUsed(Context);
16315 }
16316
16318 L->CompletedImplicitDefinition(MoveConstructor);
16319 }
16320}
16321
16323 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16324}
16325
16327 SourceLocation CurrentLocation,
16328 CXXConversionDecl *Conv) {
16329 SynthesizedFunctionScope Scope(*this, Conv);
16330 assert(!Conv->getReturnType()->isUndeducedType());
16331
16332 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16333 CallingConv CC =
16334 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16335
16336 CXXRecordDecl *Lambda = Conv->getParent();
16337 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16338 FunctionDecl *Invoker =
16339 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16340 ? CallOp
16341 : Lambda->getLambdaStaticInvoker(CC);
16342
16343 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16345 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16346 if (!CallOp)
16347 return;
16348
16349 if (CallOp != Invoker) {
16351 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16352 CurrentLocation);
16353 if (!Invoker)
16354 return;
16355 }
16356 }
16357
16358 if (CallOp->isInvalidDecl())
16359 return;
16360
16361 // Mark the call operator referenced (and add to pending instantiations
16362 // if necessary).
16363 // For both the conversion and static-invoker template specializations
16364 // we construct their body's in this function, so no need to add them
16365 // to the PendingInstantiations.
16366 MarkFunctionReferenced(CurrentLocation, CallOp);
16367
16368 if (Invoker != CallOp) {
16369 // Fill in the __invoke function with a dummy implementation. IR generation
16370 // will fill in the actual details. Update its type in case it contained
16371 // an 'auto'.
16372 Invoker->markUsed(Context);
16373 Invoker->setReferenced();
16374 Invoker->setType(Conv->getReturnType()->getPointeeType());
16375 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16376 }
16377
16378 // Construct the body of the conversion function { return __invoke; }.
16379 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16380 Conv->getLocation());
16381 assert(FunctionRef && "Can't refer to __invoke function?");
16382 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16384 Conv->getLocation(), Conv->getLocation()));
16385 Conv->markUsed(Context);
16386 Conv->setReferenced();
16387
16389 L->CompletedImplicitDefinition(Conv);
16390 if (Invoker != CallOp)
16391 L->CompletedImplicitDefinition(Invoker);
16392 }
16393}
16394
16396 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16397 assert(!Conv->getParent()->isGenericLambda());
16398
16399 SynthesizedFunctionScope Scope(*this, Conv);
16400
16401 // Copy-initialize the lambda object as needed to capture it.
16402 Expr *This = ActOnCXXThis(CurrentLocation).get();
16403 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16404
16405 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16406 Conv->getLocation(),
16407 Conv, DerefThis);
16408
16409 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16410 // behavior. Note that only the general conversion function does this
16411 // (since it's unusable otherwise); in the case where we inline the
16412 // block literal, it has block literal lifetime semantics.
16413 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16414 BuildBlock = ImplicitCastExpr::Create(
16415 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16416 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16417
16418 if (BuildBlock.isInvalid()) {
16419 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16420 Conv->setInvalidDecl();
16421 return;
16422 }
16423
16424 // Create the return statement that returns the block from the conversion
16425 // function.
16426 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16427 if (Return.isInvalid()) {
16428 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16429 Conv->setInvalidDecl();
16430 return;
16431 }
16432
16433 // Set the body of the conversion function.
16434 Stmt *ReturnS = Return.get();
16436 Conv->getLocation(), Conv->getLocation()));
16437 Conv->markUsed(Context);
16438
16439 // We're done; notify the mutation listener, if any.
16441 L->CompletedImplicitDefinition(Conv);
16442 }
16443}
16444
16445/// Determine whether the given list arguments contains exactly one
16446/// "real" (non-default) argument.
16448 switch (Args.size()) {
16449 case 0:
16450 return false;
16451
16452 default:
16453 if (!Args[1]->isDefaultArgument())
16454 return false;
16455
16456 [[fallthrough]];
16457 case 1:
16458 return !Args[0]->isDefaultArgument();
16459 }
16460
16461 return false;
16462}
16463
16465 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16467 bool HadMultipleCandidates, bool IsListInitialization,
16468 bool IsStdInitListInitialization, bool RequiresZeroInit,
16469 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16470 bool Elidable = false;
16471
16472 // C++0x [class.copy]p34:
16473 // When certain criteria are met, an implementation is allowed to
16474 // omit the copy/move construction of a class object, even if the
16475 // copy/move constructor and/or destructor for the object have
16476 // side effects. [...]
16477 // - when a temporary class object that has not been bound to a
16478 // reference (12.2) would be copied/moved to a class object
16479 // with the same cv-unqualified type, the copy/move operation
16480 // can be omitted by constructing the temporary object
16481 // directly into the target of the omitted copy/move
16482 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16483 // FIXME: Converting constructors should also be accepted.
16484 // But to fix this, the logic that digs down into a CXXConstructExpr
16485 // to find the source object needs to handle it.
16486 // Right now it assumes the source object is passed directly as the
16487 // first argument.
16488 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16489 Expr *SubExpr = ExprArgs[0];
16490 // FIXME: Per above, this is also incorrect if we want to accept
16491 // converting constructors, as isTemporaryObject will
16492 // reject temporaries with different type from the
16493 // CXXRecord itself.
16494 Elidable = SubExpr->isTemporaryObject(
16496 }
16497
16498 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16499 FoundDecl, Constructor,
16500 Elidable, ExprArgs, HadMultipleCandidates,
16501 IsListInitialization,
16502 IsStdInitListInitialization, RequiresZeroInit,
16503 ConstructKind, ParenRange);
16504}
16505
16507 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16508 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16509 bool HadMultipleCandidates, bool IsListInitialization,
16510 bool IsStdInitListInitialization, bool RequiresZeroInit,
16511 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16512 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16513 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16514 // The only way to get here is if we did overload resolution to find the
16515 // shadow decl, so we don't need to worry about re-checking the trailing
16516 // requires clause.
16517 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16518 return ExprError();
16519 }
16520
16521 return BuildCXXConstructExpr(
16522 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16523 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16524 RequiresZeroInit, ConstructKind, ParenRange);
16525}
16526
16527/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16528/// including handling of its default argument expressions.
16530 SourceLocation ConstructLoc, QualType DeclInitType,
16531 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16532 bool HadMultipleCandidates, bool IsListInitialization,
16533 bool IsStdInitListInitialization, bool RequiresZeroInit,
16534 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16535 assert(declaresSameEntity(
16536 Constructor->getParent(),
16537 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16538 "given constructor for wrong type");
16539 MarkFunctionReferenced(ConstructLoc, Constructor);
16540 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16541 return ExprError();
16542
16545 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16546 HadMultipleCandidates, IsListInitialization,
16547 IsStdInitListInitialization, RequiresZeroInit,
16548 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16549 Constructor);
16550}
16551
16553 if (VD->isInvalidDecl()) return;
16554 // If initializing the variable failed, don't also diagnose problems with
16555 // the destructor, they're likely related.
16556 if (VD->getInit() && VD->getInit()->containsErrors())
16557 return;
16558
16559 ClassDecl = ClassDecl->getDefinitionOrSelf();
16560 if (ClassDecl->isInvalidDecl()) return;
16561 if (ClassDecl->hasIrrelevantDestructor()) return;
16562 if (ClassDecl->isDependentContext()) return;
16563
16564 if (VD->isNoDestroy(getASTContext()))
16565 return;
16566
16568 // The result of `LookupDestructor` might be nullptr if the destructor is
16569 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16570 // will not be selected by `CXXRecordDecl::getDestructor()`.
16571 if (!Destructor)
16572 return;
16573 // If this is an array, we'll require the destructor during initialization, so
16574 // we can skip over this. We still want to emit exit-time destructor warnings
16575 // though.
16576 if (!VD->getType()->isArrayType()) {
16579 PDiag(diag::err_access_dtor_var)
16580 << VD->getDeclName() << VD->getType());
16582 }
16583
16584 if (Destructor->isTrivial()) return;
16585
16586 // If the destructor is constexpr, check whether the variable has constant
16587 // destruction now.
16588 if (Destructor->isConstexpr()) {
16589 bool HasConstantInit = false;
16590 if (VD->getInit() && !VD->getInit()->isValueDependent())
16591 HasConstantInit = VD->evaluateValue();
16593 sema::EvalProxy SProxy(*this);
16594 if (!VD->evaluateConstantDestruction(Notes, SProxy) && VD->isConstexpr() &&
16595 HasConstantInit) {
16596 Diag(VD->getLocation(),
16597 diag::err_constexpr_var_requires_const_destruction) << VD;
16598 for (const PartialDiagnosticAt &Note : Notes)
16599 Diag(Note.first, Note.second);
16600 }
16601 }
16602
16603 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16604 return;
16605
16606 // Emit warning for non-trivial dtor in global scope (a real global,
16607 // class-static, function-static).
16608 if (!VD->hasAttr<AlwaysDestroyAttr>())
16609 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16610
16611 // TODO: this should be re-enabled for static locals by !CXAAtExit
16612 if (!VD->isStaticLocal())
16613 Diag(VD->getLocation(), diag::warn_global_destructor);
16614}
16615
16617 QualType DeclInitType, MultiExprArg ArgsPtr,
16618 SourceLocation Loc,
16619 SmallVectorImpl<Expr *> &ConvertedArgs,
16620 bool AllowExplicit,
16621 bool IsListInitialization) {
16622 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16623 unsigned NumArgs = ArgsPtr.size();
16624 Expr **Args = ArgsPtr.data();
16625
16626 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16627 unsigned NumParams = Proto->getNumParams();
16628
16629 // If too few arguments are available, we'll fill in the rest with defaults.
16630 if (NumArgs < NumParams)
16631 ConvertedArgs.reserve(NumParams);
16632 else
16633 ConvertedArgs.reserve(NumArgs);
16634
16635 VariadicCallType CallType = Proto->isVariadic()
16638 SmallVector<Expr *, 8> AllArgs;
16640 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16641 CallType, AllowExplicit, IsListInitialization);
16642 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16643
16644 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16645
16646 CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),
16647 Proto, Loc);
16648
16649 return Invalid;
16650}
16651
16653 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16654 return typeAwareAllocationModeFromBool(SeenTypedOperators);
16655}
16656
16659 QualType DeallocType, SourceLocation Loc) {
16660 if (DeallocType.isNull())
16661 return nullptr;
16662
16663 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16664 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16665 return nullptr;
16666
16667 if (FnDecl->isVariadic())
16668 return nullptr;
16669
16670 unsigned NumParams = FnDecl->getNumParams();
16671 constexpr unsigned RequiredParameterCount =
16673 // A usual deallocation function has no placement parameters
16674 if (NumParams != RequiredParameterCount)
16675 return nullptr;
16676
16677 // A type aware allocation is only usual if the only dependent parameter is
16678 // the first parameter.
16679 if (llvm::any_of(FnDecl->parameters().drop_front(),
16680 [](const ParmVarDecl *ParamDecl) {
16681 return ParamDecl->getType()->isDependentType();
16682 }))
16683 return nullptr;
16684
16685 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);
16686 if (SpecializedTypeIdentity.isNull())
16687 return nullptr;
16688
16690 ArgTypes.reserve(NumParams);
16691
16692 // The first parameter to a type aware operator delete is by definition the
16693 // type-identity argument, so we explicitly set this to the target
16694 // type-identity type, the remaining usual parameters should then simply match
16695 // the type declared in the function template.
16696 ArgTypes.push_back(SpecializedTypeIdentity);
16697 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16698 ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());
16699
16701 QualType ExpectedFunctionType =
16702 Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
16705 if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,
16707 return nullptr;
16708 return Result;
16709}
16710
16711static inline bool
16713 const FunctionDecl *FnDecl) {
16714 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16715 if (isa<NamespaceDecl>(DC)) {
16716 return SemaRef.Diag(FnDecl->getLocation(),
16717 diag::err_operator_new_delete_declared_in_namespace)
16718 << FnDecl->getDeclName();
16719 }
16720
16721 if (isa<TranslationUnitDecl>(DC) &&
16722 FnDecl->getStorageClass() == SC_Static) {
16723 return SemaRef.Diag(FnDecl->getLocation(),
16724 diag::err_operator_new_delete_declared_static)
16725 << FnDecl->getDeclName();
16726 }
16727
16728 return false;
16729}
16730
16732 const PointerType *PtrTy) {
16733 auto &Ctx = SemaRef.Context;
16734 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16735 PtrQuals.removeAddressSpace();
16737 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16738}
16739
16741
16743 const FunctionDecl *FD,
16744 bool *WasMalformed) {
16745 const Decl *MalformedDecl = nullptr;
16746 if (FD->getNumParams() > 0 &&
16747 SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
16748 /*TypeArgument=*/nullptr, &MalformedDecl))
16749 return true;
16750
16751 if (!MalformedDecl)
16752 return false;
16753
16754 if (WasMalformed)
16755 *WasMalformed = true;
16756
16757 return true;
16758}
16759
16761 auto *RD = Type->getAsCXXRecordDecl();
16762 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16763 RD->getIdentifier()->isStr("destroying_delete_t");
16764}
16765
16767 const FunctionDecl *FD) {
16768 // C++ P0722:
16769 // Within a class C, a single object deallocation function with signature
16770 // (T, std::destroying_delete_t, <more params>)
16771 // is a destroying operator delete.
16772 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16773 SemaRef, FD, /*WasMalformed=*/nullptr);
16774 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16775 return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&
16776 FD->getNumParams() > DestroyingDeleteIdx &&
16777 isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
16778}
16779
16781 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16782 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16783 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16784 auto NormalizeType = [&SemaRef](QualType T) {
16785 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16786 // The operator is valid on any address space for OpenCL.
16787 // Drop address space from actual and expected result types.
16788 if (const auto PtrTy = T->template getAs<PointerType>())
16789 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16790 }
16791 return SemaRef.Context.getCanonicalType(T);
16792 };
16793
16794 const unsigned NumParams = FnDecl->getNumParams();
16795 unsigned FirstNonTypeParam = 0;
16796 bool MalformedTypeIdentity = false;
16797 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16798 SemaRef, FnDecl, &MalformedTypeIdentity);
16799 unsigned MinimumMandatoryArgumentCount = 1;
16800 unsigned SizeParameterIndex = 0;
16801 if (IsPotentiallyTypeAware) {
16802 // We don't emit this diagnosis for template instantiations as we will
16803 // have already emitted it for the original template declaration.
16804 if (!FnDecl->isTemplateInstantiation())
16805 SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);
16806
16807 if (OperatorKind == AllocationOperatorKind::New) {
16808 SizeParameterIndex = 1;
16809 MinimumMandatoryArgumentCount =
16811 } else {
16812 SizeParameterIndex = 2;
16813 MinimumMandatoryArgumentCount =
16815 }
16816 FirstNonTypeParam = 1;
16817 }
16818
16819 bool IsPotentiallyDestroyingDelete =
16821
16822 if (IsPotentiallyDestroyingDelete) {
16823 ++MinimumMandatoryArgumentCount;
16824 ++SizeParameterIndex;
16825 }
16826
16827 if (NumParams < MinimumMandatoryArgumentCount)
16828 return SemaRef.Diag(FnDecl->getLocation(),
16829 diag::err_operator_new_delete_too_few_parameters)
16830 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16831 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16832
16833 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16834 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);
16835 if (ParamDecl->hasDefaultArg())
16836 return SemaRef.Diag(FnDecl->getLocation(),
16837 diag::err_operator_new_default_arg)
16838 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16839 }
16840
16841 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16842 QualType CanResultType = NormalizeType(FnType->getReturnType());
16843 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16844 QualType CanExpectedSizeOrAddressParamType =
16845 NormalizeType(ExpectedSizeOrAddressParamType);
16846
16847 // Check that the result type is what we expect.
16848 if (CanResultType != CanExpectedResultType) {
16849 // Reject even if the type is dependent; an operator delete function is
16850 // required to have a non-dependent result type.
16851 return SemaRef.Diag(
16852 FnDecl->getLocation(),
16853 CanResultType->isDependentType()
16854 ? diag::err_operator_new_delete_dependent_result_type
16855 : diag::err_operator_new_delete_invalid_result_type)
16856 << FnDecl->getDeclName() << ExpectedResultType;
16857 }
16858
16859 // A function template must have at least 2 parameters.
16860 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16861 return SemaRef.Diag(FnDecl->getLocation(),
16862 diag::err_operator_new_delete_template_too_few_parameters)
16863 << FnDecl->getDeclName();
16864
16865 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16866 auto FallbackType) -> bool {
16867 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);
16868 if (ExpectedType.isNull()) {
16869 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
16870 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16871 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16872 << ParamDecl->getSourceRange();
16873 }
16874 CanQualType CanExpectedTy =
16875 NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));
16876 auto ActualParamType =
16877 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16878 if (ActualParamType == CanExpectedTy)
16879 return false;
16880 unsigned Diagnostic = ActualParamType->isDependentType()
16881 ? DependentParamTypeDiag
16882 : InvalidParamTypeDiag;
16883 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
16884 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16885 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16886 << FallbackType << ParamDecl->getSourceRange();
16887 };
16888
16889 // Check that the first parameter type is what we expect.
16890 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16891 return true;
16892
16893 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16894
16895 // If the first parameter type is not a type-identity we're done, otherwise
16896 // we need to ensure the size and alignment parameters have the correct type
16897 if (!IsPotentiallyTypeAware)
16898 return false;
16899
16900 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16901 return true;
16902 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16903 CanQualType StdAlignValT =
16904 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(StdAlignValTDecl)
16905 : CanQualType();
16906 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16907 return true;
16908
16910 return MalformedTypeIdentity;
16911}
16912
16913static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16914 // C++ [basic.stc.dynamic.allocation]p1:
16915 // A program is ill-formed if an allocation function is declared in a
16916 // namespace scope other than global scope or declared static in global
16917 // scope.
16918 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16919 return true;
16920
16921 CanQualType SizeTy =
16922 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16923
16924 // C++ [basic.stc.dynamic.allocation]p1:
16925 // The return type shall be void*. The first parameter shall have type
16926 // std::size_t.
16928 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
16929 SizeTy, diag::err_operator_new_dependent_param_type,
16930 diag::err_operator_new_param_type);
16931}
16932
16933static bool
16935 // C++ [basic.stc.dynamic.deallocation]p1:
16936 // A program is ill-formed if deallocation functions are declared in a
16937 // namespace scope other than global scope or declared static in global
16938 // scope.
16939 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16940 return true;
16941
16942 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16943 auto ConstructDestroyingDeleteAddressType = [&]() {
16944 assert(MD);
16945 return SemaRef.Context.getPointerType(
16946 SemaRef.Context.getCanonicalTagType(MD->getParent()));
16947 };
16948
16949 // C++ P2719: A destroying operator delete cannot be type aware
16950 // so for QoL we actually check for this explicitly by considering
16951 // an destroying-delete appropriate address type and the presence of
16952 // any parameter of type destroying_delete_t as an erroneous attempt
16953 // to declare a type aware destroying delete, rather than emitting a
16954 // pile of incorrect parameter type errors.
16956 SemaRef, MD, /*WasMalformed=*/nullptr)) {
16957 QualType AddressParamType =
16958 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
16959 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16960 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16961 // The address parameter type implies an author trying to construct a
16962 // type aware destroying delete, so we'll see if we can find a parameter
16963 // of type `std::destroying_delete_t`, and if we find it we'll report
16964 // this as being an attempt at a type aware destroying delete just stop
16965 // here. If we don't do this, the resulting incorrect parameter ordering
16966 // results in a pile mismatched argument type errors that don't explain
16967 // the core problem.
16968 for (auto Param : MD->parameters()) {
16969 if (isDestroyingDeleteT(Param->getType())) {
16970 SemaRef.Diag(MD->getLocation(),
16971 diag::err_type_aware_destroying_operator_delete)
16972 << Param->getSourceRange();
16973 return true;
16974 }
16975 }
16976 }
16977 }
16978
16979 // C++ P0722:
16980 // Within a class C, the first parameter of a destroying operator delete
16981 // shall be of type C *. The first parameter of any other deallocation
16982 // function shall be of type void *.
16983 CanQualType ExpectedAddressParamType =
16984 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
16985 ? SemaRef.Context.getPointerType(
16986 SemaRef.Context.getCanonicalTagType(MD->getParent()))
16987 : SemaRef.Context.VoidPtrTy;
16988
16989 // C++ [basic.stc.dynamic.deallocation]p2:
16990 // Each deallocation function shall return void
16992 SemaRef, FnDecl, AllocationOperatorKind::Delete,
16993 SemaRef.Context.VoidTy, ExpectedAddressParamType,
16994 diag::err_operator_delete_dependent_param_type,
16995 diag::err_operator_delete_param_type))
16996 return true;
16997
16998 // C++ P0722:
16999 // A destroying operator delete shall be a usual deallocation function.
17000 if (MD && !MD->getParent()->isDependentContext() &&
17002 if (!SemaRef.isUsualDeallocationFunction(MD)) {
17003 SemaRef.Diag(MD->getLocation(),
17004 diag::err_destroying_operator_delete_not_usual);
17005 return true;
17006 }
17007 }
17008
17009 return false;
17010}
17011
17013 assert(FnDecl && FnDecl->isOverloadedOperator() &&
17014 "Expected an overloaded operator declaration");
17015
17017
17018 // C++ [over.oper]p5:
17019 // The allocation and deallocation functions, operator new,
17020 // operator new[], operator delete and operator delete[], are
17021 // described completely in 3.7.3. The attributes and restrictions
17022 // found in the rest of this subclause do not apply to them unless
17023 // explicitly stated in 3.7.3.
17024 if (Op == OO_Delete || Op == OO_Array_Delete)
17025 return CheckOperatorDeleteDeclaration(*this, FnDecl);
17026
17027 if (Op == OO_New || Op == OO_Array_New)
17028 return CheckOperatorNewDeclaration(*this, FnDecl);
17029
17030 // C++ [over.oper]p7:
17031 // An operator function shall either be a member function or
17032 // be a non-member function and have at least one parameter
17033 // whose type is a class, a reference to a class, an enumeration,
17034 // or a reference to an enumeration.
17035 // Note: Before C++23, a member function could not be static. The only member
17036 // function allowed to be static is the call operator function.
17037 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
17038 if (MethodDecl->isStatic()) {
17039 if (Op == OO_Call || Op == OO_Subscript)
17040 DiagCompat(FnDecl->getLocation(), diag_compat::operator_overload_static)
17041 << FnDecl;
17042 else
17043 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
17044 << FnDecl;
17045 }
17046 } else {
17047 bool ClassOrEnumParam = false;
17048 for (auto *Param : FnDecl->parameters()) {
17049 QualType ParamType = Param->getType().getNonReferenceType();
17050 if (ParamType->isDependentType() || ParamType->isRecordType() ||
17051 ParamType->isEnumeralType()) {
17052 ClassOrEnumParam = true;
17053 break;
17054 }
17055 }
17056
17057 if (!ClassOrEnumParam)
17058 return Diag(FnDecl->getLocation(),
17059 diag::err_operator_overload_needs_class_or_enum)
17060 << FnDecl->getDeclName();
17061 }
17062
17063 // C++ [over.oper]p8:
17064 // An operator function cannot have default arguments (8.3.6),
17065 // except where explicitly stated below.
17066 //
17067 // Only the function-call operator (C++ [over.call]p1) and the subscript
17068 // operator (CWG2507) allow default arguments.
17069 if (Op != OO_Call) {
17070 ParmVarDecl *FirstDefaultedParam = nullptr;
17071 for (auto *Param : FnDecl->parameters()) {
17072 if (Param->hasDefaultArg()) {
17073 FirstDefaultedParam = Param;
17074 break;
17075 }
17076 }
17077 if (FirstDefaultedParam) {
17078 if (Op == OO_Subscript) {
17079 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17080 ? diag::ext_subscript_overload
17081 : diag::error_subscript_overload)
17082 << FnDecl->getDeclName() << 1
17083 << FirstDefaultedParam->getDefaultArgRange();
17084 } else {
17085 return Diag(FirstDefaultedParam->getLocation(),
17086 diag::err_operator_overload_default_arg)
17087 << FnDecl->getDeclName()
17088 << FirstDefaultedParam->getDefaultArgRange();
17089 }
17090 }
17091 }
17092
17093 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17094 { false, false, false }
17095#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17096 , { Unary, Binary, MemberOnly }
17097#include "clang/Basic/OperatorKinds.def"
17098 };
17099
17100 bool CanBeUnaryOperator = OperatorUses[Op][0];
17101 bool CanBeBinaryOperator = OperatorUses[Op][1];
17102 bool MustBeMemberOperator = OperatorUses[Op][2];
17103
17104 // C++ [over.oper]p8:
17105 // [...] Operator functions cannot have more or fewer parameters
17106 // than the number required for the corresponding operator, as
17107 // described in the rest of this subclause.
17108 unsigned NumParams = FnDecl->getNumParams() +
17109 (isa<CXXMethodDecl>(FnDecl) &&
17111 ? 1
17112 : 0);
17113 if (Op != OO_Call && Op != OO_Subscript &&
17114 ((NumParams == 1 && !CanBeUnaryOperator) ||
17115 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17116 (NumParams > 2))) {
17117 // We have the wrong number of parameters.
17118 unsigned ErrorKind;
17119 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17120 ErrorKind = 2; // 2 -> unary or binary.
17121 } else if (CanBeUnaryOperator) {
17122 ErrorKind = 0; // 0 -> unary
17123 } else {
17124 assert(CanBeBinaryOperator &&
17125 "All non-call overloaded operators are unary or binary!");
17126 ErrorKind = 1; // 1 -> binary
17127 }
17128 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
17129 << FnDecl->getDeclName() << NumParams << ErrorKind;
17130 }
17131
17132 if (Op == OO_Subscript && NumParams != 2) {
17133 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17134 ? diag::ext_subscript_overload
17135 : diag::error_subscript_overload)
17136 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17137 }
17138
17139 // Overloaded operators other than operator() and operator[] cannot be
17140 // variadic.
17141 if (Op != OO_Call &&
17142 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17143 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
17144 << FnDecl->getDeclName();
17145 }
17146
17147 // Some operators must be member functions.
17148 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
17149 return Diag(FnDecl->getLocation(),
17150 diag::err_operator_overload_must_be_member)
17151 << FnDecl->getDeclName();
17152 }
17153
17154 // C++ [over.inc]p1:
17155 // The user-defined function called operator++ implements the
17156 // prefix and postfix ++ operator. If this function is a member
17157 // function with no parameters, or a non-member function with one
17158 // parameter of class or enumeration type, it defines the prefix
17159 // increment operator ++ for objects of that type. If the function
17160 // is a member function with one parameter (which shall be of type
17161 // int) or a non-member function with two parameters (the second
17162 // of which shall be of type int), it defines the postfix
17163 // increment operator ++ for objects of that type.
17164 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17165 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
17166 QualType ParamType = LastParam->getType();
17167
17168 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
17169 !ParamType->isDependentType())
17170 return Diag(LastParam->getLocation(),
17171 diag::err_operator_overload_post_incdec_must_be_int)
17172 << LastParam->getType() << (Op == OO_MinusMinus);
17173 }
17174
17175 return false;
17176}
17177
17178static bool
17180 FunctionTemplateDecl *TpDecl) {
17181 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17182
17183 // Must have one or two template parameters.
17184 if (TemplateParams->size() == 1) {
17185 NonTypeTemplateParmDecl *PmDecl =
17186 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
17187
17188 // The template parameter must be a char parameter pack.
17189 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17190 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
17191 return false;
17192
17193 // C++20 [over.literal]p5:
17194 // A string literal operator template is a literal operator template
17195 // whose template-parameter-list comprises a single non-type
17196 // template-parameter of class type.
17197 //
17198 // As a DR resolution, we also allow placeholders for deduced class
17199 // template specializations.
17200 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17201 !PmDecl->isTemplateParameterPack() &&
17202 (PmDecl->getType()->isRecordType() ||
17203 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17204 return false;
17205 } else if (TemplateParams->size() == 2) {
17206 TemplateTypeParmDecl *PmType =
17207 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
17208 NonTypeTemplateParmDecl *PmArgs =
17209 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
17210
17211 // The second template parameter must be a parameter pack with the
17212 // first template parameter as its type.
17213 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17214 PmArgs->isTemplateParameterPack()) {
17215 if (const auto *TArgs =
17216 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17217 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17218 TArgs->getIndex() == PmType->getIndex()) {
17219 if (!SemaRef.inTemplateInstantiation())
17220 SemaRef.Diag(TpDecl->getLocation(),
17221 diag::ext_string_literal_operator_template);
17222 return false;
17223 }
17224 }
17225 }
17226
17227 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17228 diag::err_literal_operator_template)
17229 << TpDecl->getTemplateParameters()->getSourceRange();
17230 return true;
17231}
17232
17234 if (isa<CXXMethodDecl>(FnDecl)) {
17235 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
17236 << FnDecl->getDeclName();
17237 return true;
17238 }
17239
17240 if (FnDecl->isExternC()) {
17241 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
17242 if (const LinkageSpecDecl *LSD =
17243 FnDecl->getDeclContext()->getExternCContext())
17244 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
17245 return true;
17246 }
17247
17248 // This might be the definition of a literal operator template.
17250
17251 // This might be a specialization of a literal operator template.
17252 if (!TpDecl)
17253 TpDecl = FnDecl->getPrimaryTemplate();
17254
17255 // template <char...> type operator "" name() and
17256 // template <class T, T...> type operator "" name() are the only valid
17257 // template signatures, and the only valid signatures with no parameters.
17258 //
17259 // C++20 also allows template <SomeClass T> type operator "" name().
17260 if (TpDecl) {
17261 if (FnDecl->param_size() != 0) {
17262 Diag(FnDecl->getLocation(),
17263 diag::err_literal_operator_template_with_params);
17264 return true;
17265 }
17266
17268 return true;
17269
17270 } else if (FnDecl->param_size() == 1) {
17271 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
17272
17273 QualType ParamType = Param->getType().getUnqualifiedType();
17274
17275 // Only unsigned long long int, long double, any character type, and const
17276 // char * are allowed as the only parameters.
17277 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
17278 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
17279 Context.hasSameType(ParamType, Context.CharTy) ||
17280 Context.hasSameType(ParamType, Context.WideCharTy) ||
17281 Context.hasSameType(ParamType, Context.Char8Ty) ||
17282 Context.hasSameType(ParamType, Context.Char16Ty) ||
17283 Context.hasSameType(ParamType, Context.Char32Ty)) {
17284 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17285 QualType InnerType = Ptr->getPointeeType();
17286
17287 // Pointer parameter must be a const char *.
17288 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17289 Context.CharTy) &&
17290 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17291 Diag(Param->getSourceRange().getBegin(),
17292 diag::err_literal_operator_param)
17293 << ParamType << "'const char *'" << Param->getSourceRange();
17294 return true;
17295 }
17296
17297 } else if (ParamType->isRealFloatingType()) {
17298 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17299 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17300 return true;
17301
17302 } else if (ParamType->isIntegerType()) {
17303 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17304 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17305 return true;
17306
17307 } else {
17308 Diag(Param->getSourceRange().getBegin(),
17309 diag::err_literal_operator_invalid_param)
17310 << ParamType << Param->getSourceRange();
17311 return true;
17312 }
17313
17314 } else if (FnDecl->param_size() == 2) {
17315 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17316
17317 // First, verify that the first parameter is correct.
17318
17319 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17320
17321 // Two parameter function must have a pointer to const as a
17322 // first parameter; let's strip those qualifiers.
17323 const PointerType *PT = FirstParamType->getAs<PointerType>();
17324
17325 if (!PT) {
17326 Diag((*Param)->getSourceRange().getBegin(),
17327 diag::err_literal_operator_param)
17328 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17329 return true;
17330 }
17331
17332 QualType PointeeType = PT->getPointeeType();
17333 // First parameter must be const
17334 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17335 Diag((*Param)->getSourceRange().getBegin(),
17336 diag::err_literal_operator_param)
17337 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17338 return true;
17339 }
17340
17341 QualType InnerType = PointeeType.getUnqualifiedType();
17342 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17343 // const char32_t* are allowed as the first parameter to a two-parameter
17344 // function
17345 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17346 Context.hasSameType(InnerType, Context.WideCharTy) ||
17347 Context.hasSameType(InnerType, Context.Char8Ty) ||
17348 Context.hasSameType(InnerType, Context.Char16Ty) ||
17349 Context.hasSameType(InnerType, Context.Char32Ty))) {
17350 Diag((*Param)->getSourceRange().getBegin(),
17351 diag::err_literal_operator_param)
17352 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17353 return true;
17354 }
17355
17356 // Move on to the second and final parameter.
17357 ++Param;
17358
17359 // The second parameter must be a std::size_t.
17360 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17361 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
17362 Diag((*Param)->getSourceRange().getBegin(),
17363 diag::err_literal_operator_param)
17364 << SecondParamType << Context.getSizeType()
17365 << (*Param)->getSourceRange();
17366 return true;
17367 }
17368 } else {
17369 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17370 return true;
17371 }
17372
17373 // Parameters are good.
17374
17375 // A parameter-declaration-clause containing a default argument is not
17376 // equivalent to any of the permitted forms.
17377 for (auto *Param : FnDecl->parameters()) {
17378 if (Param->hasDefaultArg()) {
17379 Diag(Param->getDefaultArgRange().getBegin(),
17380 diag::err_literal_operator_default_argument)
17381 << Param->getDefaultArgRange();
17382 break;
17383 }
17384 }
17385
17386 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17389 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
17390 // C++23 [usrlit.suffix]p1:
17391 // Literal suffix identifiers that do not start with an underscore are
17392 // reserved for future standardization. Literal suffix identifiers that
17393 // contain a double underscore __ are reserved for use by C++
17394 // implementations.
17395 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17396 << static_cast<int>(Status)
17398 }
17399
17400 return false;
17401}
17402
17404 Expr *LangStr,
17405 SourceLocation LBraceLoc) {
17406 StringLiteral *Lit = cast<StringLiteral>(LangStr);
17407 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17408
17409 StringRef Lang = Lit->getString();
17411 if (Lang == "C")
17413 else if (Lang == "C++")
17415 else {
17416 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17417 << LangStr->getSourceRange();
17418 return nullptr;
17419 }
17420
17421 // FIXME: Add all the various semantics of linkage specifications
17422
17424 LangStr->getExprLoc(), Language,
17425 LBraceLoc.isValid());
17426
17427 /// C++ [module.unit]p7.2.3
17428 /// - Otherwise, if the declaration
17429 /// - ...
17430 /// - ...
17431 /// - appears within a linkage-specification,
17432 /// it is attached to the global module.
17433 ///
17434 /// If the declaration is already in global module fragment, we don't
17435 /// need to attach it again.
17436 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17437 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
17438 D->setLocalOwningModule(GlobalModule);
17439 }
17440
17441 CurContext->addDecl(D);
17442 PushDeclContext(S, D);
17443 return D;
17444}
17445
17447 Decl *LinkageSpec,
17448 SourceLocation RBraceLoc) {
17449 if (RBraceLoc.isValid()) {
17450 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
17451 LSDecl->setRBraceLoc(RBraceLoc);
17452 }
17453
17454 // If the current module doesn't has Parent, it implies that the
17455 // LinkageSpec isn't in the module created by itself. So we don't
17456 // need to pop it.
17457 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17458 getCurrentModule()->isImplicitGlobalModule() &&
17459 getCurrentModule()->Parent)
17460 PopImplicitGlobalModuleFragment();
17461
17463 return LinkageSpec;
17464}
17465
17467 const ParsedAttributesView &AttrList,
17468 SourceLocation SemiLoc) {
17469 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
17470 // Attribute declarations appertain to empty declaration so we handle
17471 // them here.
17472 ProcessDeclAttributeList(S, ED, AttrList);
17473
17474 CurContext->addDecl(ED);
17475 return ED;
17476}
17477
17479 SourceLocation StartLoc,
17480 SourceLocation Loc,
17481 const IdentifierInfo *Name) {
17482 bool Invalid = false;
17483 QualType ExDeclType = TInfo->getType();
17484
17485 // Arrays and functions decay.
17486 if (ExDeclType->isArrayType())
17487 ExDeclType = Context.getArrayDecayedType(ExDeclType);
17488 else if (ExDeclType->isFunctionType())
17489 ExDeclType = Context.getPointerType(ExDeclType);
17490
17491 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17492 // The exception-declaration shall not denote a pointer or reference to an
17493 // incomplete type, other than [cv] void*.
17494 // N2844 forbids rvalue references.
17495 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17496 Diag(Loc, diag::err_catch_rvalue_ref);
17497 Invalid = true;
17498 }
17499
17500 if (ExDeclType->isVariablyModifiedType()) {
17501 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17502 Invalid = true;
17503 }
17504
17505 QualType BaseType = ExDeclType;
17506 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17507 unsigned DK = diag::err_catch_incomplete;
17508 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17509 BaseType = Ptr->getPointeeType();
17510 Mode = 1;
17511 DK = diag::err_catch_incomplete_ptr;
17512 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17513 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17514 BaseType = Ref->getPointeeType();
17515 Mode = 2;
17516 DK = diag::err_catch_incomplete_ref;
17517 }
17518 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17519 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17520 Invalid = true;
17521
17522 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17523 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17524 Invalid = true;
17525 }
17526
17527 // Reject catch types that need a cross-AS conversion.
17528 // cause runtimes don't yet support cross-address-
17529 // space conversions
17530 if (Mode == 1) {
17531 if (ExDeclType.getAddressSpace() != LangAS::Default ||
17532 BaseType.getAddressSpace() != LangAS::Default) {
17533 Diag(Loc, diag::err_throw_or_catch_address_space_qualified_ptr)
17534 << /*IsCatch=*/1 << /*IsRef=*/0 << ExDeclType;
17535 Invalid = true;
17536 }
17537 } else if (Mode == 2) {
17538 if (const PointerType *PT = BaseType->getAs<PointerType>();
17539 PT && (BaseType.getAddressSpace() != LangAS::Default ||
17540 PT->getPointeeType().getAddressSpace() != LangAS::Default)) {
17541 Diag(Loc, diag::err_throw_or_catch_address_space_qualified_ptr)
17542 << /*IsCatch=*/1 << /*IsRef=*/0 << ExDeclType;
17543 Invalid = true;
17544 } else if (BaseType.getAddressSpace() != LangAS::Default) {
17545 Diag(Loc, diag::err_throw_or_catch_address_space_qualified_ptr)
17546 << /*IsCatch=*/1 << /*IsRef=*/1 << ExDeclType;
17547 Invalid = true;
17548 }
17549 }
17550
17551 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17552 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17553 Invalid = true;
17554 }
17555
17556 if (!Invalid && !ExDeclType->isDependentType() &&
17557 RequireNonAbstractType(Loc, ExDeclType,
17558 diag::err_abstract_type_in_decl,
17560 Invalid = true;
17561
17562 // Only the non-fragile NeXT runtime currently supports C++ catches
17563 // of ObjC types, and no runtime supports catching ObjC types by value.
17564 if (!Invalid && getLangOpts().ObjC) {
17565 QualType T = ExDeclType;
17566 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17567 T = RT->getPointeeType();
17568
17569 if (T->isObjCObjectType()) {
17570 Diag(Loc, diag::err_objc_object_catch);
17571 Invalid = true;
17572 } else if (T->isObjCObjectPointerType()) {
17573 // FIXME: should this be a test for macosx-fragile specifically?
17575 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17576 }
17577 }
17578
17579 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17580 ExDeclType, TInfo, SC_None);
17581 ExDecl->setExceptionVariable(true);
17582
17583 // In ARC, infer 'retaining' for variables of retainable type.
17584 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17585 Invalid = true;
17586
17587 if (!Invalid && !ExDeclType->isDependentType()) {
17588 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17589 // Insulate this from anything else we might currently be parsing.
17592
17593 // C++ [except.handle]p16:
17594 // The object declared in an exception-declaration or, if the
17595 // exception-declaration does not specify a name, a temporary (12.2) is
17596 // copy-initialized (8.5) from the exception object. [...]
17597 // The object is destroyed when the handler exits, after the destruction
17598 // of any automatic objects initialized within the handler.
17599 //
17600 // We just pretend to initialize the object with itself, then make sure
17601 // it can be destroyed later.
17602 QualType initType = Context.getExceptionObjectType(ExDeclType);
17603
17604 InitializedEntity entity =
17606 InitializationKind initKind =
17608
17609 Expr *opaqueValue =
17610 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17611 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17612 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17613 if (result.isInvalid())
17614 Invalid = true;
17615 else {
17616 // If the constructor used was non-trivial, set this as the
17617 // "initializer".
17618 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17619 if (!construct->getConstructor()->isTrivial()) {
17620 Expr *init = MaybeCreateExprWithCleanups(construct);
17621 ExDecl->setInit(init);
17622 }
17623
17624 // And make sure it's destructable.
17625 FinalizeVarWithDestructor(ExDecl, ClassDecl);
17626 }
17627 }
17628 }
17629
17630 if (Invalid)
17631 ExDecl->setInvalidDecl();
17632
17633 return ExDecl;
17634}
17635
17638 bool Invalid = D.isInvalidType();
17639
17640 // Check for unexpanded parameter packs.
17643 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17644 D.getIdentifierLoc());
17645 Invalid = true;
17646 }
17647
17648 const IdentifierInfo *II = D.getIdentifier();
17649 if (NamedDecl *PrevDecl =
17652 // The scope should be freshly made just for us. There is just no way
17653 // it contains any previous declaration, except for function parameters in
17654 // a function-try-block's catch statement.
17655 assert(!S->isDeclScope(PrevDecl));
17656 if (isDeclInScope(PrevDecl, CurContext, S)) {
17657 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17658 << D.getIdentifier();
17659 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17660 Invalid = true;
17661 } else if (PrevDecl->isTemplateParameter())
17662 // Maybe we will complain about the shadowed template parameter.
17664 }
17665
17666 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17667 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17668 << D.getCXXScopeSpec().getRange();
17669 Invalid = true;
17670 }
17671
17673 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17674 if (Invalid)
17675 ExDecl->setInvalidDecl();
17676
17677 // Add the exception declaration into this scope.
17678 if (II)
17679 PushOnScopeChains(ExDecl, S);
17680 else
17681 CurContext->addDecl(ExDecl);
17682
17683 ProcessDeclAttributes(S, ExDecl, D);
17684 return ExDecl;
17685}
17686
17688 Expr *AssertExpr,
17689 Expr *AssertMessageExpr,
17690 SourceLocation RParenLoc) {
17692 return nullptr;
17693
17694 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17695 AssertMessageExpr, RParenLoc, false);
17696}
17697
17698static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17699 switch (BTK) {
17700 case BuiltinType::Char_S:
17701 case BuiltinType::Char_U:
17702 break;
17703 case BuiltinType::Char8:
17704 OS << "u8";
17705 break;
17706 case BuiltinType::Char16:
17707 OS << 'u';
17708 break;
17709 case BuiltinType::Char32:
17710 OS << 'U';
17711 break;
17712 case BuiltinType::WChar_S:
17713 case BuiltinType::WChar_U:
17714 OS << 'L';
17715 break;
17716 default:
17717 llvm_unreachable("Non-character type");
17718 }
17719}
17720
17721/// Convert character's value, interpreted as a code unit, to a string.
17722/// The value needs to be zero-extended to 32-bits.
17723/// FIXME: This assumes Unicode literal encodings
17725 unsigned TyWidth,
17726 SmallVectorImpl<char> &Str) {
17727 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17728 char *Ptr = Arr;
17729 BuiltinType::Kind K = BTy->getKind();
17730 llvm::raw_svector_ostream OS(Str);
17731
17732 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17733 // other types.
17734 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17735 K == BuiltinType::Char8 || Value <= 0x7F) {
17736 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17737 if (!Escaped.empty())
17738 EscapeStringForDiagnostic(Escaped, Str);
17739 else
17740 OS << static_cast<char>(Value);
17741 return;
17742 }
17743
17744 switch (K) {
17745 case BuiltinType::Char16:
17746 case BuiltinType::Char32:
17747 case BuiltinType::WChar_S:
17748 case BuiltinType::WChar_U: {
17749 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17750 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17751 else
17752 OS << "\\x"
17753 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17754 break;
17755 }
17756 default:
17757 llvm_unreachable("Non-character type is passed");
17758 }
17759}
17760
17761/// Convert \V to a string we can present to the user in a diagnostic
17762/// \T is the type of the expression that has been evaluated into \V
17765 ASTContext &Context) {
17766 if (!V.hasValue())
17767 return false;
17768
17769 switch (V.getKind()) {
17771 if (T->isBooleanType()) {
17772 // Bools are reduced to ints during evaluation, but for
17773 // diagnostic purposes we want to print them as
17774 // true or false.
17775 int64_t BoolValue = V.getInt().getExtValue();
17776 assert((BoolValue == 0 || BoolValue == 1) &&
17777 "Bool type, but value is not 0 or 1");
17778 llvm::raw_svector_ostream OS(Str);
17779 OS << (BoolValue ? "true" : "false");
17780 } else {
17781 llvm::raw_svector_ostream OS(Str);
17782 // Same is true for chars.
17783 // We want to print the character representation for textual types
17784 const auto *BTy = T->getAs<BuiltinType>();
17785 if (BTy) {
17786 switch (BTy->getKind()) {
17787 case BuiltinType::Char_S:
17788 case BuiltinType::Char_U:
17789 case BuiltinType::Char8:
17790 case BuiltinType::Char16:
17791 case BuiltinType::Char32:
17792 case BuiltinType::WChar_S:
17793 case BuiltinType::WChar_U: {
17794 unsigned TyWidth = Context.getIntWidth(T);
17795 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17796 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17797 WriteCharTypePrefix(BTy->getKind(), OS);
17798 OS << '\'';
17799 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17800 OS << "' (0x"
17801 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17802 /*Upper=*/true)
17803 << ", " << V.getInt() << ')';
17804 return true;
17805 }
17806 default:
17807 break;
17808 }
17809 }
17810 V.getInt().toString(Str);
17811 }
17812
17813 break;
17814
17816 V.getFloat().toString(Str);
17817 break;
17818
17820 if (V.isNullPointer()) {
17821 llvm::raw_svector_ostream OS(Str);
17822 OS << "nullptr";
17823 } else
17824 return false;
17825 break;
17826
17828 llvm::raw_svector_ostream OS(Str);
17829 OS << '(';
17830 V.getComplexFloatReal().toString(Str);
17831 OS << " + ";
17832 V.getComplexFloatImag().toString(Str);
17833 OS << "i)";
17834 } break;
17835
17837 llvm::raw_svector_ostream OS(Str);
17838 OS << '(';
17839 V.getComplexIntReal().toString(Str);
17840 OS << " + ";
17841 V.getComplexIntImag().toString(Str);
17842 OS << "i)";
17843 } break;
17844
17845 default:
17846 return false;
17847 }
17848
17849 return true;
17850}
17851
17852/// Some Expression types are not useful to print notes about,
17853/// e.g. literals and values that have already been expanded
17854/// before such as int-valued template parameters.
17855static bool UsefulToPrintExpr(const Expr *E) {
17856 E = E->IgnoreParenImpCasts();
17857 // Literals are pretty easy for humans to understand.
17860 return false;
17861
17862 // These have been substituted from template parameters
17863 // and appear as literals in the static assert error.
17865 return false;
17866
17867 // -5 is also simple to understand.
17868 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17869 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17870
17871 // Only print nested arithmetic operators.
17872 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17873 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17874 BO->isBitwiseOp());
17875
17876 return true;
17877}
17878
17880 // FIXME: Should we also ignore explicit casts?
17881 E = E->IgnoreParenImpCasts();
17882 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17883 Op && Op->getOpcode() != BO_LOr) {
17884 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17885 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17886
17887 // Ignore comparisons of boolean expressions with a boolean literal.
17888 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17889 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17890 return;
17891
17892 // Don't print obvious expressions.
17893 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17894 return;
17895
17896 struct {
17897 const clang::Expr *Cond;
17899 SmallString<12> ValueString;
17900 bool Print;
17901 } DiagSides[2] = {{LHS, Expr::EvalResult(), {}, false},
17902 {RHS, Expr::EvalResult(), {}, false}};
17903 for (auto &DiagSide : DiagSides) {
17904 const Expr *Side = DiagSide.Cond;
17905
17906 Side->EvaluateAsRValue(DiagSide.Result, Context, true);
17907
17908 DiagSide.Print = ConvertAPValueToString(
17909 DiagSide.Result.Val, Side->getType(), DiagSide.ValueString, Context);
17910 }
17911 if (DiagSides[0].Print && DiagSides[1].Print) {
17912 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17913 << DiagSides[0].ValueString << Op->getOpcodeStr()
17914 << DiagSides[1].ValueString << Op->getSourceRange();
17915 }
17916 } else if (const auto *RE = dyn_cast<RequiresExpr>(E)) {
17918 } else {
17920 }
17921}
17922
17923template <typename ResultType>
17924static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17925 ResultType &Result, ASTContext &Ctx,
17927 bool ErrorOnInvalidMessage) {
17928
17929 assert(Message);
17930 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17931 "can't evaluate a dependant static assert message");
17932
17933 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17934 assert(SL->isUnevaluated() && "expected an unevaluated string");
17935 if constexpr (std::is_same_v<APValue, ResultType>) {
17936 Result =
17937 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17938 const ConstantArrayType *CAT =
17939 SemaRef.getASTContext().getAsConstantArrayType(SL->getType());
17940 assert(CAT && "string literal isn't an array");
17941 QualType CharType = CAT->getElementType();
17942 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),
17943 CharType->isUnsignedIntegerType());
17944 for (unsigned I = 0; I < SL->getLength(); I++) {
17945 Value = SL->getCodeUnit(I);
17946 Result.getArrayInitializedElt(I) = APValue(Value);
17947 }
17948 } else {
17949 Result.assign(SL->getString().begin(), SL->getString().end());
17950 }
17951 return true;
17952 }
17953
17954 SourceLocation Loc = Message->getBeginLoc();
17955 QualType T = Message->getType().getNonReferenceType();
17956 auto *RD = T->getAsCXXRecordDecl();
17957 if (!RD) {
17958 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
17959 return false;
17960 }
17961
17962 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17964 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17965 SemaRef.LookupQualifiedName(MemberLookup, RD);
17966 if (MemberLookup.empty())
17967 return std::nullopt;
17968 return std::move(MemberLookup);
17969 };
17970
17971 std::optional<LookupResult> SizeMember = FindMember("size");
17972 std::optional<LookupResult> DataMember = FindMember("data");
17973 if (!SizeMember || !DataMember) {
17974 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
17975 << EvalContext
17976 << ((!SizeMember && !DataMember) ? 2
17977 : !SizeMember ? 0
17978 : 1);
17979 return false;
17980 }
17981
17982 auto BuildExpr = [&](LookupResult &LR) {
17984 Message, Message->getType(), Message->getBeginLoc(), false,
17985 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17986 if (Res.isInvalid())
17987 return ExprError();
17988 Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,
17989 false, true);
17990 if (Res.isInvalid())
17991 return ExprError();
17992 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17993 return ExprError();
17994 return SemaRef.TemporaryMaterializationConversion(Res.get());
17995 };
17996
17997 ExprResult SizeE = BuildExpr(*SizeMember);
17998 ExprResult DataE = BuildExpr(*DataMember);
17999
18000 QualType SizeT = SemaRef.Context.getSizeType();
18001 QualType ConstCharPtr = SemaRef.Context.getPointerType(
18002 SemaRef.Context.getConstType(SemaRef.Context.CharTy));
18003
18004 ExprResult EvaluatedSize =
18005 SizeE.isInvalid()
18006 ? ExprError()
18009 if (EvaluatedSize.isInvalid()) {
18010 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
18011 << EvalContext << /*size*/ 0;
18012 return false;
18013 }
18014
18015 ExprResult EvaluatedData =
18016 DataE.isInvalid()
18017 ? ExprError()
18019 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);
18020 if (EvaluatedData.isInvalid()) {
18021 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
18022 << EvalContext << /*data*/ 1;
18023 return false;
18024 }
18025
18026 if (!ErrorOnInvalidMessage &&
18027 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
18028 return true;
18029
18030 Expr::EvalResult Status;
18032 Status.Diag = &Notes;
18033 sema::EvalProxy SProxy(SemaRef);
18034 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
18035 EvaluatedData.get(), Ctx, SProxy,
18036 Status) ||
18037 !Notes.empty()) {
18038 SemaRef.Diag(Message->getBeginLoc(),
18039 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
18040 : diag::warn_user_defined_msg_constexpr)
18041 << EvalContext;
18042 for (const auto &Note : Notes)
18043 SemaRef.Diag(Note.first, Note.second);
18044 return !ErrorOnInvalidMessage;
18045 }
18046 return true;
18047}
18048
18050 StringEvaluationContext EvalContext,
18051 bool ErrorOnInvalidMessage) {
18052 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
18053 ErrorOnInvalidMessage);
18054}
18055
18056bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
18057 StringEvaluationContext EvalContext,
18058 bool ErrorOnInvalidMessage) {
18059 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
18060 ErrorOnInvalidMessage);
18061}
18062
18064 Expr *AssertExpr, Expr *AssertMessage,
18065 SourceLocation RParenLoc,
18066 bool Failed) {
18067 assert(AssertExpr != nullptr && "Expected non-null condition");
18068 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
18069 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
18070 !AssertMessage->isValueDependent())) &&
18071 !Failed) {
18072 // In a static_assert-declaration, the constant-expression shall be a
18073 // constant expression that can be contextually converted to bool.
18074 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
18075 if (Converted.isInvalid())
18076 Failed = true;
18077
18078 ExprResult FullAssertExpr =
18079 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
18080 /*DiscardedValue*/ false,
18081 /*IsConstexpr*/ true);
18082 if (FullAssertExpr.isInvalid())
18083 Failed = true;
18084 else
18085 AssertExpr = FullAssertExpr.get();
18086
18087 llvm::APSInt Cond;
18088 Expr *BaseExpr = AssertExpr;
18090
18091 if (!getLangOpts().CPlusPlus) {
18092 // In C mode, allow folding as an extension for better compatibility with
18093 // C++ in terms of expressions like static_assert("test") or
18094 // static_assert(nullptr).
18095 FoldKind = AllowFoldKind::Allow;
18096 }
18097
18098 if (!Failed && VerifyIntegerConstantExpression(
18099 BaseExpr, &Cond,
18100 diag::err_static_assert_expression_is_not_constant,
18101 FoldKind).isInvalid())
18102 Failed = true;
18103
18104 // If the static_assert passes, only verify that
18105 // the message is grammatically valid without evaluating it.
18106 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18107 std::string Str;
18108 EvaluateAsString(AssertMessage, Str, Context,
18110 /*ErrorOnInvalidMessage=*/false);
18111 }
18112
18113 // CWG2518
18114 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18115 // template definition, the declaration has no effect.
18116 bool InTemplateDefinition =
18117 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18118
18119 if (!Failed && !Cond && !InTemplateDefinition) {
18120 SmallString<256> MsgBuffer;
18121 llvm::raw_svector_ostream Msg(MsgBuffer);
18122 bool HasMessage = AssertMessage;
18123 if (AssertMessage) {
18124 std::string Str;
18125 HasMessage = EvaluateAsString(AssertMessage, Str, Context,
18127 /*ErrorOnInvalidMessage=*/true) ||
18128 !Str.empty();
18129 Msg << Str;
18130 }
18131 Expr *InnerCond = nullptr;
18132 std::string InnerCondDescription;
18133 std::tie(InnerCond, InnerCondDescription) =
18134 findFailedBooleanCondition(Converted.get());
18135 if (const auto *ConceptIDExpr =
18136 dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {
18137 const ASTConstraintSatisfaction &Satisfaction =
18138 ConceptIDExpr->getSatisfaction();
18139 if (!Satisfaction.containsErrors() || Satisfaction.record_size()) {
18140 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18141 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18142 // Drill down into concept specialization expressions to see why they
18143 // weren't satisfied.
18144 DiagnoseUnsatisfiedConstraint(ConceptIDExpr);
18145 }
18146 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&
18147 !isa<IntegerLiteral>(InnerCond)) {
18148 Diag(InnerCond->getBeginLoc(),
18149 diag::err_static_assert_requirement_failed)
18150 << InnerCondDescription << !HasMessage << Msg.str()
18151 << InnerCond->getSourceRange();
18152 DiagnoseStaticAssertDetails(InnerCond);
18153 } else {
18154 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18155 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18157 }
18158 Failed = true;
18159 }
18160 } else {
18161 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
18162 /*DiscardedValue*/false,
18163 /*IsConstexpr*/true);
18164 if (FullAssertExpr.isInvalid())
18165 Failed = true;
18166 else
18167 AssertExpr = FullAssertExpr.get();
18168 }
18169
18171 AssertExpr, AssertMessage, RParenLoc,
18172 Failed);
18173
18174 CurContext->addDecl(Decl);
18175 return Decl;
18176}
18177
18179 if (const auto *PIT = dyn_cast<PackIndexingType>(T))
18180 return PIT->getPattern();
18181 return T;
18182}
18183
18184static const TemplateSpecializationType *
18187 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(T))
18188 T = ICNT->getDecl()->getCanonicalTemplateSpecializationType(Context);
18189
18190 const auto *TST = dyn_cast<TemplateSpecializationType>(T);
18191 if (!TST)
18192 return nullptr;
18193
18194 TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
18195 if (!TD || isa<ClassTemplateDecl>(TD))
18196 return TST;
18197 return nullptr;
18198}
18199
18201 NestedNameSpecifierLoc NNSLoc) {
18202 for (TypeLoc TL = NNSLoc.getAsTypeLoc(); TL;
18203 TL = TL.getPrefix().getAsTypeLoc()) {
18204 if (TL.getTypeLocClass() != TypeLoc::PackIndexing)
18205 continue;
18206
18207 Diag(Loc, diag::err_pack_indexing_in_friend) << TL.getSourceRange();
18208 return true;
18209 }
18210 return false;
18211}
18212
18214 NestedNameSpecifier NNS) {
18215 QualType T(NNS.getAsType(), 0);
18216 if (const auto *TST =
18217 dyn_cast<TemplateSpecializationType>(IgnorePackIndexing(T))) {
18218 if (isa_and_nonnull<TypeAliasTemplateDecl>(
18219 TST->getTemplateName().getAsTemplateDecl())) {
18220 S.Diag(Loc, diag::err_dependent_friend_not_member_of_template_spec)
18221 << NNS;
18222 return;
18223 }
18224 }
18225
18226 if (NNS.getAsRecordDecl()) {
18227 S.Diag(Loc, diag::err_dependent_friend_not_member_of_template_spec) << NNS;
18228 } else {
18229 S.Diag(Loc, diag::err_dependent_friend_not_member);
18230 }
18231}
18232
18236 bool IsInstantiation) {
18238 if (!NNS.isDependent() && !IsInstantiation)
18239 return false;
18240
18241 assert(NNS.getKind() == NestedNameSpecifier::Kind::Type &&
18242 "nested-name-specifier of dependent friend must be a type");
18243
18244 QualType T(NNS.getAsType(), 0);
18245 if (DiagnosePackIndexingInFriendNNS(Loc, NNSLoc))
18246 return true;
18247
18248 const TemplateSpecializationType *TST =
18250 if (!TST) {
18251 DiagnoseDependentFriendNotMember(*this, Loc, NNS);
18252 return true;
18253 }
18254
18255 if (TPLs.empty())
18256 return false;
18257
18258 SmallVector<NamedDecl *, 4> UndeducedParameters;
18259 for (TemplateParameterList *Params : TPLs) {
18260 llvm::SmallBitVector UsedParameters(Params->size());
18261 MarkUsedTemplateParameters(TST->template_arguments(),
18262 /*OnlyDeduced=*/true, Params->getDepth(),
18263 UsedParameters);
18264
18265 for (unsigned I = 0, N = UsedParameters.size(); I != N; ++I)
18266 if (!UsedParameters[I])
18267 UndeducedParameters.push_back(Params->getParam(I));
18268 }
18269
18270 if (UndeducedParameters.empty())
18271 return false;
18272
18273 Diag(Loc, diag::err_dependent_friend_undeduced_params)
18274 << (UndeducedParameters.size() > 1) << QualType(TST, 0);
18275
18276 for (NamedDecl *Param : UndeducedParameters) {
18277 if (Param->getDeclName())
18278 Diag(Param->getLocation(), diag::note_non_deducible_parameter)
18279 << Param->getDeclName();
18280 else
18281 Diag(Param->getLocation(), diag::note_non_deducible_parameter)
18282 << "(anonymous)";
18283 }
18284
18285 return true;
18286}
18287
18289 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18290 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18291 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18292 MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId) {
18294
18295 bool IsMemberSpecialization = false;
18296 bool Invalid = false;
18297
18298 TemplateParameterList *TemplateParams =
18299 MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, TemplateId,
18300 TempParamLists, /*friend*/ true,
18301 IsMemberSpecialization, Invalid);
18302 if (TemplateId) {
18303 if (Invalid)
18304 return true;
18305
18306 if (TemplateParams) {
18307 Diag(NameLoc, diag::err_not_class_template_specialization) << 0;
18308 return true;
18309 }
18310 }
18311
18312 if (TemplateParams) {
18313 if (TemplateParams->size() > 0) {
18314 if (Invalid)
18315 return true;
18316
18317 if (SS.isEmpty() || !SS.getScopeRep().isDependent()) {
18319 S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc, Attr,
18320 TemplateParams, AS_public, /*ModulePrivateLoc=*/SourceLocation(),
18321 FriendLoc, TempParamLists.size() - 1, TempParamLists.data(),
18322 IsMemberSpecialization);
18323 return Result.get();
18324 }
18325 } else {
18326 // The "template<>" header is extraneous.
18327 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18328 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18329 }
18330 }
18331
18332 if (Invalid)
18333 return true;
18334
18335 bool IsAllExplicitSpecializations =
18336 llvm::all_of(TempParamLists, [](const TemplateParameterList *List) {
18337 return List->size() == 0;
18338 });
18339
18340 // FIXME: don't ignore attributes.
18341
18342 // If it's explicit specializations all the way down, just forget
18343 // about the template header and build an appropriate non-templated
18344 // friend. TODO: for source fidelity, remember the headers.
18346 if (!TemplateId && IsAllExplicitSpecializations) {
18347 if (SS.isEmpty()) {
18348 bool Owned = false;
18349 bool IsDependent = false;
18350 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
18351 Attr, AS_public,
18352 /*ModulePrivateLoc=*/SourceLocation(),
18353 MultiTemplateParamsArg(), Owned, IsDependent,
18354 /*ScopedEnumKWLoc=*/SourceLocation(),
18355 /*ScopedEnumUsesClassTag=*/false,
18356 /*UnderlyingType=*/TypeResult(),
18357 /*IsTypeSpecifier=*/false,
18358 /*IsTemplateParamOrArg=*/false,
18359 /*OOK=*/OffsetOfKind::Outside);
18360 }
18361
18362 TypeSourceInfo *TSI = nullptr;
18365 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name,
18366 NameLoc, &TSI, /*DeducedTSTContext=*/true);
18367 if (T.isNull())
18368 return true;
18369
18371 FriendLoc, EllipsisLoc);
18372 Friend->setAccess(AS_public);
18373 CurContext->addDecl(Friend);
18374 return Friend;
18375 }
18376
18377 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18378
18379 ArrayRef<TemplateParameterList *> TPLs = TempParamLists;
18380 if (TemplateParams)
18381 TPLs = TPLs.drop_back();
18382 if (CheckDependentFriend(TagLoc, QualifierLoc, TPLs,
18383 /*IsInstantiation=*/false))
18384 return true;
18385
18386 TypeSourceInfo *TSI = nullptr;
18387 if (TemplateId) {
18388 ASTTemplateArgsPtr ParsedArgs(TemplateId->getTemplateArgs(),
18389 TemplateId->NumArgs);
18391 TagUseKind::Friend, static_cast<TypeSpecifierType>(TagSpec), TagLoc, SS,
18392 TemplateId->TemplateKWLoc, TemplateId->Template, NameLoc,
18393 TemplateId->LAngleLoc, ParsedArgs, TemplateId->RAngleLoc);
18394 if (ParsedType.isInvalid())
18395 return true;
18396
18397 GetTypeFromParser(ParsedType.get(), &TSI);
18398 } else {
18400 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
18401 TSI = Context.CreateTypeSourceInfo(T);
18402
18404 TL.setElaboratedKeywordLoc(TagLoc);
18405 TL.setQualifierLoc(QualifierLoc);
18406 TL.setNameLoc(NameLoc);
18407 }
18408
18410 collectUnexpandedParameterPacks(TSI->getTypeLoc(), Unexpanded);
18411 if (EllipsisLoc.isInvalid()) {
18413 return true;
18414 } else if (Unexpanded.empty()) {
18415 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18416 << TSI->getTypeLoc().getSourceRange();
18417 return true;
18418 } else {
18419 // CWG 2917: a pack expanded by a friend-type-specifier cannot have been
18420 // introduced by the template-declaration containing that specifier.
18421 if (!TempParamLists.empty()) {
18422 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18423 for (UnexpandedParameterPack &U : Unexpanded) {
18424 if (std::optional<std::pair<unsigned, unsigned>> DI =
18426 DI && DI->first >= FriendDeclDepth) {
18427 auto *ND = dyn_cast<NamedDecl *>(U.first);
18428 if (!ND)
18429 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
18430 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18431 << ND->getDeclName()
18432 << SourceRange(TSI->getTypeLoc().getBeginLoc(), EllipsisLoc);
18433 return true;
18434 }
18435 }
18436 }
18437 }
18438
18440 if (TempParamLists.empty())
18441 Friend = FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18442 EllipsisLoc);
18443 else {
18444 if (CheckTemplateDeclScope(S, TempParamLists.back()))
18445 return true;
18446
18448 if (TemplateParams)
18449 FriendTemplate = Context.getDependentTemplateName(
18450 {SS.getScopeRep(), Name, /*HasTemplateKeyword=*/false});
18451 Friend =
18452 FriendTemplateDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18453 TempParamLists, EllipsisLoc, FriendTemplate);
18454 }
18455
18456 Friend->setAccess(AS_public);
18457 CurContext->addDecl(Friend);
18458
18459 return Friend;
18460}
18461
18463 MultiTemplateParamsArg TempParams,
18464 SourceLocation EllipsisLoc) {
18465 SourceLocation Loc = DS.getBeginLoc();
18466 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18467
18468 assert(DS.isFriendSpecified());
18470
18471 // C++ [class.friend]p3:
18472 // A friend declaration that does not declare a function shall have one of
18473 // the following forms:
18474 // friend elaborated-type-specifier ;
18475 // friend simple-type-specifier ;
18476 // friend typename-specifier ;
18477 //
18478 // If the friend keyword isn't first, or if the declarations has any type
18479 // qualifiers, then the declaration doesn't have that form.
18481 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
18482 if (DS.getTypeQualifiers()) {
18484 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
18486 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
18488 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
18490 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
18492 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
18493 }
18494
18495 // Try to convert the decl specifier to a type. This works for
18496 // friend templates because ActOnTag never produces a ClassTemplateDecl
18497 // for a TagUseKind::Friend.
18498 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18500 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
18501 QualType T = TSI->getType();
18502 if (TheDeclarator.isInvalidType())
18503 return nullptr;
18504
18505 // If '...' is present, the type must contain an unexpanded parameter
18506 // pack, and vice versa.
18507 bool Invalid = false;
18508 if (EllipsisLoc.isInvalid() &&
18510 return nullptr;
18511 if (EllipsisLoc.isValid() &&
18513 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18514 << TSI->getTypeLoc().getSourceRange();
18515 Invalid = true;
18516 }
18517
18518 if (!T->isElaboratedTypeSpecifier()) {
18519 if (TempParams.size()) {
18520 // C++23 [dcl.pre]p5:
18521 // In a simple-declaration, the optional init-declarator-list can be
18522 // omitted only when declaring a class or enumeration, that is, when
18523 // the decl-specifier-seq contains either a class-specifier, an
18524 // elaborated-type-specifier with a class-key, or an enum-specifier.
18525 //
18526 // The declaration of a template-declaration or explicit-specialization
18527 // is never a member-declaration, so this must be a simple-declaration
18528 // with no init-declarator-list. Therefore, this is ill-formed.
18529 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
18530 return nullptr;
18531 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18532 SmallString<16> InsertionText(" ");
18533 InsertionText += RD->getKindName();
18534
18536 ? diag::warn_cxx98_compat_unelaborated_friend_type
18537 : diag::ext_unelaborated_friend_type)
18538 << (unsigned)RD->getTagKind() << T
18540 InsertionText);
18541 } else {
18542 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
18543 << T << DS.getSourceRange();
18544 }
18545 }
18546
18547 // C++98 [class.friend]p1: A friend of a class is a function
18548 // or class that is not a member of the class . . .
18549 // This is fixed in DR77, which just barely didn't make the C++03
18550 // deadline. It's also a very silly restriction that seriously
18551 // affects inner classes and which nobody else seems to implement;
18552 // thus we never diagnose it, not even in -pedantic.
18553 //
18554 // But note that we could warn about it: it's always useless to
18555 // friend one of your own members (it's not, however, worthless to
18556 // friend a member of an arbitrary specialization of your template).
18557
18558 Decl *D;
18559 if (!TempParams.empty()) {
18560 if (CheckTemplateDeclScope(S, TempParams.back()))
18561 return nullptr;
18562
18563 // TODO: Support variadic friend template decls?
18564 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TSI, FriendLoc,
18565 TempParams, EllipsisLoc);
18566 } else
18568 TSI, FriendLoc, EllipsisLoc);
18569
18570 if (!D)
18571 return nullptr;
18572
18573 D->setAccess(AS_public);
18574 CurContext->addDecl(D);
18575
18576 if (Invalid)
18577 D->setInvalidDecl();
18578
18579 return D;
18580}
18581
18583 MultiTemplateParamsArg TemplateParams) {
18584 const DeclSpec &DS = D.getDeclSpec();
18585
18586 assert(DS.isFriendSpecified());
18588
18591
18592 // C++ [class.friend]p1
18593 // A friend of a class is a function or class....
18594 // Note that this sees through typedefs, which is intended.
18595 // It *doesn't* see through dependent types, which is correct
18596 // according to [temp.arg.type]p3:
18597 // If a declaration acquires a function type through a
18598 // type dependent on a template-parameter and this causes
18599 // a declaration that does not use the syntactic form of a
18600 // function declarator to have a function type, the program
18601 // is ill-formed.
18602 if (!TInfo->getType()->isFunctionType()) {
18603 Diag(Loc, diag::err_unexpected_friend);
18604
18605 // It might be worthwhile to try to recover by creating an
18606 // appropriate declaration.
18607 return nullptr;
18608 }
18609
18610 // C++ [namespace.memdef]p3
18611 // - If a friend declaration in a non-local class first declares a
18612 // class or function, the friend class or function is a member
18613 // of the innermost enclosing namespace.
18614 // - The name of the friend is not found by simple name lookup
18615 // until a matching declaration is provided in that namespace
18616 // scope (either before or after the class declaration granting
18617 // friendship).
18618 // - If a friend function is called, its name may be found by the
18619 // name lookup that considers functions from namespaces and
18620 // classes associated with the types of the function arguments.
18621 // - When looking for a prior declaration of a class or a function
18622 // declared as a friend, scopes outside the innermost enclosing
18623 // namespace scope are not considered.
18624
18625 CXXScopeSpec &SS = D.getCXXScopeSpec();
18627 assert(NameInfo.getName());
18628
18630 NameInfo.getLoc(), SS.getWithLocInContext(Context)))
18631 return nullptr;
18632
18633 // Check for unexpanded parameter packs.
18637 return nullptr;
18638
18639 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18640
18641 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
18642 auto Kind = SS.getScopeRep().getKind();
18643 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
18645 if (IsNamespaceOrGlobal) {
18646 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
18647 << SS.getScopeRep();
18648 SS.clear();
18649 }
18650 }
18651
18652 // The context we found the declaration in, or in which we should
18653 // create the declaration.
18654 DeclContext *DC;
18655 Scope *DCScope = S;
18656 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18658
18659 // There are five cases here.
18660 // - There's no scope specifier and we're in a local class. Only look
18661 // for functions declared in the immediately-enclosing block scope.
18662 // We recover from invalid scope qualifiers as if they just weren't there.
18663 FunctionDecl *FunctionContainingLocalClass = nullptr;
18664 if ((SS.isInvalid() || !SS.isSet()) &&
18665 (FunctionContainingLocalClass =
18666 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
18667 // C++11 [class.friend]p11:
18668 // If a friend declaration appears in a local class and the name
18669 // specified is an unqualified name, a prior declaration is
18670 // looked up without considering scopes that are outside the
18671 // innermost enclosing non-class scope. For a friend function
18672 // declaration, if there is no prior declaration, the program is
18673 // ill-formed.
18674
18675 // Find the innermost enclosing non-class scope. This is the block
18676 // scope containing the local class definition (or for a nested class,
18677 // the outer local class).
18678 DCScope = S->getFnParent();
18679
18680 // Look up the function name in the scope.
18682 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
18683
18684 if (!Previous.empty()) {
18685 // All possible previous declarations must have the same context:
18686 // either they were declared at block scope or they are members of
18687 // one of the enclosing local classes.
18688 DC = Previous.getRepresentativeDecl()->getDeclContext();
18689 } else {
18690 // This is ill-formed, but provide the context that we would have
18691 // declared the function in, if we were permitted to, for error recovery.
18692 DC = FunctionContainingLocalClass;
18693 }
18695
18696 // - There's no scope specifier, in which case we just go to the
18697 // appropriate scope and look for a function or function template
18698 // there as appropriate.
18699 } else if (SS.isInvalid() || !SS.isSet()) {
18700 // C++11 [namespace.memdef]p3:
18701 // If the name in a friend declaration is neither qualified nor
18702 // a template-id and the declaration is a function or an
18703 // elaborated-type-specifier, the lookup to determine whether
18704 // the entity has been previously declared shall not consider
18705 // any scopes outside the innermost enclosing namespace.
18706
18707 // Find the appropriate context according to the above.
18708 DC = CurContext;
18709
18710 // Skip class contexts. If someone can cite chapter and verse
18711 // for this behavior, that would be nice --- it's what GCC and
18712 // EDG do, and it seems like a reasonable intent, but the spec
18713 // really only says that checks for unqualified existing
18714 // declarations should stop at the nearest enclosing namespace,
18715 // not that they should only consider the nearest enclosing
18716 // namespace.
18717 while (DC->isRecord())
18718 DC = DC->getParent();
18719
18720 DeclContext *LookupDC = DC->getNonTransparentContext();
18721 while (true) {
18722 LookupQualifiedName(Previous, LookupDC);
18723
18724 if (!Previous.empty()) {
18725 DC = LookupDC;
18726 break;
18727 }
18728
18729 if (isTemplateId) {
18730 if (isa<TranslationUnitDecl>(LookupDC)) break;
18731 } else {
18732 if (LookupDC->isFileContext()) break;
18733 }
18734 LookupDC = LookupDC->getParent();
18735 }
18736
18737 DCScope = getScopeForDeclContext(S, DC);
18738
18739 // - There's a non-dependent scope specifier, in which case we
18740 // compute it and do a previous lookup there for a function
18741 // or function template.
18742 } else if (!SS.getScopeRep().isDependent()) {
18743 DC = computeDeclContext(SS);
18744 if (!DC) return nullptr;
18745
18746 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18747
18749
18750 // C++ [class.friend]p1: A friend of a class is a function or
18751 // class that is not a member of the class . . .
18752 if (DC->Equals(CurContext))
18755 diag::warn_cxx98_compat_friend_is_member :
18756 diag::err_friend_is_member);
18757
18758 // - There's a dependent scope specifier, in which case we use an
18759 // arbitrary context and wait for instantiation.
18760 } else {
18761 DC = CurContext;
18762 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18763 }
18764
18765 if (!DC->isRecord()) {
18766 int DiagArg = -1;
18767 switch (D.getName().getKind()) {
18770 DiagArg = 0;
18771 break;
18773 DiagArg = 1;
18774 break;
18776 DiagArg = 2;
18777 break;
18779 DiagArg = 3;
18780 break;
18786 break;
18787 }
18788 // This implies that it has to be an operator or function.
18789 if (DiagArg >= 0) {
18790 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18791 return nullptr;
18792 }
18793 } else {
18794 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(DC);
18795 if (RC->isLambda()) {
18796 Diag(NameInfo.getBeginLoc(), diag::err_friend_lambda_decl);
18797 }
18798 }
18799
18800 // FIXME: This is an egregious hack to cope with cases where the scope stack
18801 // does not contain the declaration context, i.e., in an out-of-line
18802 // definition of a class.
18803 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18804 if (!DCScope) {
18805 FakeDCScope.setEntity(DC);
18806 DCScope = &FakeDCScope;
18807 }
18808
18809 bool AddToScope = true;
18810 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18811 TemplateParams, AddToScope);
18812 if (!ND) return nullptr;
18813
18814 assert(ND->getLexicalDeclContext() == CurContext);
18815
18816 // If we performed typo correction, we might have added a scope specifier
18817 // and changed the decl context.
18818 DC = ND->getDeclContext();
18819
18820 // Add the function declaration to the appropriate lookup tables,
18821 // adjusting the redeclarations list as necessary. We don't
18822 // want to do this yet if the friending class is dependent.
18823 //
18824 // Also update the scope-based lookup if the target context's
18825 // lookup context is in lexical scope.
18826 if (!CurContext->isDependentContext()) {
18827 DC = DC->getRedeclContext();
18829 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18830 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18831 }
18832
18834
18835 if (ND->isInvalidDecl()) {
18838 Friend->setAccess(AS_public);
18839 Friend->setInvalidDecl();
18840 CurContext->addDecl(Friend);
18841 return ND;
18842 }
18843
18844 FunctionDecl *FD = ND->getAsFunction();
18845 assert(FD && "Expected a function declaration!");
18846
18848 if (!TPLs.empty() && SS.isValid() && CheckTemplateDeclScope(S, TPLs.back()))
18849 return nullptr;
18850
18852 if (!TPLs.empty() && SS.isValid())
18853 Friend =
18855 ND, DS.getFriendSpecLoc(), TPLs);
18856 else
18858 DS.getFriendSpecLoc());
18859
18860 Friend->setAccess(AS_public);
18861 CurContext->addDecl(Friend);
18862
18863 if (DC->isRecord())
18865
18866 if (!TemplateParams.empty() && SS.isValid() &&
18869 /*IsInstantiation=*/false))
18870 return ND;
18871
18872 // C++ [class.friend]p6:
18873 // A function may be defined in a friend declaration of a class if and
18874 // only if the class is a non-local class, and the function name is
18875 // unqualified.
18876 if (D.isFunctionDefinition()) {
18877 // Qualified friend function definition.
18878 if (SS.isNotEmpty()) {
18880 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18881
18882 DB << SS.getScopeRep();
18883
18884 // Friend function defined in a local class.
18885 } else if (FunctionContainingLocalClass) {
18886 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18887
18888 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18889 // a template-id, the function name is not unqualified because these is
18890 // no name. While the wording requires some reading in-between the
18891 // lines, GCC, MSVC, and EDG all consider a friend function
18892 // specialization definitions to be de facto explicit specialization
18893 // and diagnose them as such.
18894 } else if (isTemplateId) {
18895 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18896 }
18897 }
18898
18899 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18900 // default argument expression, that declaration shall be a definition
18901 // and shall be the only declaration of the function or function
18902 // template in the translation unit.
18904 // We can't look at FD->getPreviousDecl() because it may not have been set
18905 // if we're in a dependent context. If the function is known to be a
18906 // redeclaration, we will have narrowed Previous down to the right decl.
18907 if (D.isRedeclaration()) {
18908 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18909 Diag(Previous.getRepresentativeDecl()->getLocation(),
18910 diag::note_previous_declaration);
18911 } else if (!D.isFunctionDefinition())
18912 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18913 }
18914
18915 return ND;
18916}
18917
18919 StringLiteral *Message) {
18921
18922 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18923 if (!Fn) {
18924 Diag(DelLoc, diag::err_deleted_non_function);
18925 return;
18926 }
18927
18928 // Deleted function does not have a body.
18929 Fn->setWillHaveBody(false);
18930
18931 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18932 // Don't consider the implicit declaration we generate for explicit
18933 // specializations. FIXME: Do not generate these implicit declarations.
18934 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18935 Prev->getPreviousDecl()) &&
18936 !Prev->isDefined()) {
18937 Diag(DelLoc, diag::err_deleted_decl_not_first);
18938 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18939 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18940 : diag::note_previous_declaration);
18941 // We can't recover from this; the declaration might have already
18942 // been used.
18943 Fn->setInvalidDecl();
18944 return;
18945 }
18946
18947 // To maintain the invariant that functions are only deleted on their first
18948 // declaration, mark the implicitly-instantiated declaration of the
18949 // explicitly-specialized function as deleted instead of marking the
18950 // instantiated redeclaration.
18951 Fn = Fn->getCanonicalDecl();
18952 }
18953
18954 // dllimport/dllexport cannot be deleted.
18955 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18956 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18957 Fn->setInvalidDecl();
18958 }
18959
18960 // C++11 [basic.start.main]p3:
18961 // A program that defines main as deleted [...] is ill-formed.
18962 if (Fn->isMain())
18963 Diag(DelLoc, diag::err_deleted_main);
18964
18965 // C++11 [dcl.fct.def.delete]p4:
18966 // A deleted function is implicitly inline.
18967 Fn->setImplicitlyInline();
18968 Fn->setDeletedAsWritten(true, Message);
18969}
18970
18972 if (!Dcl || Dcl->isInvalidDecl())
18973 return;
18974
18975 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18976 if (!FD) {
18977 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18978 if (FTD->getTemplatedDecl()->getDefaultedFunctionKind().isComparison()) {
18979 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18980 return;
18981 }
18982 }
18983
18984 Diag(DefaultLoc, diag::err_default_special_members)
18985 << getLangOpts().CPlusPlus20;
18986 return;
18987 }
18988
18989 // Reject if this can't possibly be a defaultable function.
18990 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
18991 if (!DefKind &&
18992 // A dependent function that doesn't locally look defaultable can
18993 // still instantiate to a defaultable function if it's a constructor
18994 // or assignment operator.
18995 (!FD->isDependentContext() ||
18997 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18998 Diag(DefaultLoc, diag::err_default_special_members)
18999 << getLangOpts().CPlusPlus20;
19000 return;
19001 }
19002
19003 // Issue compatibility warning. We already warned if the operator is
19004 // 'operator<=>' when parsing the '<=>' token.
19005 if (DefKind.isComparison() &&
19007 DiagCompat(DefaultLoc, diag_compat::defaulted_comparison);
19008 }
19009
19010 FD->setDefaulted();
19011 FD->setExplicitlyDefaulted();
19012 FD->setDefaultLoc(DefaultLoc);
19013
19014 // Defer checking functions that are defaulted in a dependent context.
19015 if (FD->isDependentContext())
19016 return;
19017
19018 // Unset that we will have a body for this function. We might not,
19019 // if it turns out to be trivial, and we don't need this marking now
19020 // that we've marked it as defaulted.
19021 FD->setWillHaveBody(false);
19022
19023 if (DefKind.isComparison()) {
19024 // If this comparison's defaulting occurs within the definition of its
19025 // lexical class context, we have to do the checking when complete.
19026 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
19027 if (!RD->isCompleteDefinition())
19028 return;
19029 }
19030
19031 // If this member fn was defaulted on its first declaration, we will have
19032 // already performed the checking in CheckCompletedCXXClass. Such a
19033 // declaration doesn't trigger an implicit definition.
19034 if (isa<CXXMethodDecl>(FD)) {
19035 const FunctionDecl *Primary = FD;
19036 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
19037 // Ask the template instantiation pattern that actually had the
19038 // '= default' on it.
19039 Primary = Pattern;
19040 if (Primary->getCanonicalDecl()->isDefaulted())
19041 return;
19042 }
19043
19044 // Only allocate DefaultedOrDeletedFunctionInfo if we actually have
19045 // non-default FP features to stash. This avoids memory overhead for
19046 // the vast majority of defaulted functions.
19047 if (!FD->getDefaultedOrDeletedInfo() &&
19048 CurFPFeatureOverrides().requiresTrailingStorage()) {
19049 FD->setDefaultedOrDeletedInfo(
19051 Context, /*Lookups=*/{}, CurFPFeatureOverrides()));
19052 }
19053
19054 if (DefKind.isComparison()) {
19055 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
19056 FD->setInvalidDecl();
19057 else
19058 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
19059 } else {
19060 auto *MD = cast<CXXMethodDecl>(FD);
19061
19063 DefaultLoc))
19064 MD->setInvalidDecl();
19065 else
19066 DefineDefaultedFunction(*this, MD, DefaultLoc);
19067 }
19068}
19069
19071 for (Stmt *SubStmt : S->children()) {
19072 if (!SubStmt)
19073 continue;
19074 if (isa<ReturnStmt>(SubStmt))
19075 Self.Diag(SubStmt->getBeginLoc(),
19076 diag::err_return_in_constructor_handler);
19077 if (!isa<Expr>(SubStmt))
19078 SearchForReturnInStmt(Self, SubStmt);
19079 }
19080}
19081
19083 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
19084 CXXCatchStmt *Handler = TryBlock->getHandler(I);
19085 SearchForReturnInStmt(*this, Handler);
19086 }
19087}
19088
19090 StringLiteral *DeletedMessage) {
19091 switch (BodyKind) {
19092 case FnBodyKind::Delete:
19093 SetDeclDeleted(D, Loc, DeletedMessage);
19094 break;
19096 SetDeclDefaulted(D, Loc);
19097 break;
19098 case FnBodyKind::Other:
19099 llvm_unreachable(
19100 "Parsed function body should be '= delete;' or '= default;'");
19101 }
19102}
19103
19105 const CXXMethodDecl *Old) {
19106 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19107 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
19108
19109 if (OldFT->hasExtParameterInfos()) {
19110 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
19111 // A parameter of the overriding method should be annotated with noescape
19112 // if the corresponding parameter of the overridden method is annotated.
19113 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
19114 !NewFT->getExtParameterInfo(I).isNoEscape()) {
19115 Diag(New->getParamDecl(I)->getLocation(),
19116 diag::warn_overriding_method_missing_noescape);
19117 Diag(Old->getParamDecl(I)->getLocation(),
19118 diag::note_overridden_marked_noescape);
19119 }
19120 }
19121
19122 // SME attributes must match when overriding a function declaration.
19123 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
19124 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
19125 << New << New->getType() << Old->getType();
19126 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
19127 return true;
19128 }
19129
19130 // Virtual overrides must have the same code_seg.
19131 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
19132 const auto *NewCSA = New->getAttr<CodeSegAttr>();
19133 if ((NewCSA || OldCSA) &&
19134 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
19135 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
19136 Diag(Old->getLocation(), diag::note_previous_declaration);
19137 return true;
19138 }
19139
19140 // Virtual overrides: check for matching effects.
19141 if (Context.hasAnyFunctionEffects()) {
19142 const auto OldFX = Old->getFunctionEffects();
19143 const auto NewFXOrig = New->getFunctionEffects();
19144
19145 if (OldFX != NewFXOrig) {
19146 FunctionEffectSet NewFX(NewFXOrig);
19147 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
19149 for (const auto &Diff : Diffs) {
19150 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
19152 break;
19154 Diag(New->getLocation(), diag::warn_conflicting_func_effect_override)
19155 << Diff.effectName();
19156 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19157 << Old->getReturnTypeSourceRange();
19158 break;
19160 NewFX.insert(Diff.Old.value(), Errs);
19161 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19162 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
19164 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
19165 NewFT->getParamTypes(), EPI);
19166 New->setType(ModQT);
19167 if (Errs.empty()) {
19168 // A warning here is somewhat pedantic. Skip this if there was
19169 // already a merge conflict, which is more serious.
19170 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
19171 << Diff.effectName();
19172 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19173 << Old->getReturnTypeSourceRange();
19174 }
19175 break;
19176 }
19177 }
19178 }
19179 if (!Errs.empty())
19180 diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
19181 Old->getLocation());
19182 }
19183 }
19184
19185 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
19186
19187 // If the calling conventions match, everything is fine
19188 if (NewCC == OldCC)
19189 return false;
19190
19191 // If the calling conventions mismatch because the new function is static,
19192 // suppress the calling convention mismatch error; the error about static
19193 // function override (err_static_overrides_virtual from
19194 // Sema::CheckFunctionDeclaration) is more clear.
19195 if (New->getStorageClass() == SC_Static)
19196 return false;
19197
19198 Diag(New->getLocation(),
19199 diag::err_conflicting_overriding_cc_attributes)
19200 << New->getDeclName() << New->getType() << Old->getType();
19201 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
19202 return true;
19203}
19204
19206 const CXXMethodDecl *Old) {
19207 // CWG2553
19208 // A virtual function shall not be an explicit object member function.
19209 if (!New->isExplicitObjectMemberFunction())
19210 return true;
19211 Diag(New->getParamDecl(0)->getBeginLoc(),
19212 diag::err_explicit_object_parameter_nonmember)
19213 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
19214 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
19215 New->setInvalidDecl();
19216 return false;
19217}
19218
19220 const CXXMethodDecl *Old) {
19221 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
19222 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
19223
19224 if (Context.hasSameType(NewTy, OldTy) ||
19225 NewTy->isDependentType() || OldTy->isDependentType())
19226 return false;
19227
19228 // Check if the return types are covariant
19229 QualType NewClassTy, OldClassTy;
19230
19231 /// Both types must be pointers or references to classes.
19232 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
19233 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
19234 NewClassTy = NewPT->getPointeeType();
19235 OldClassTy = OldPT->getPointeeType();
19236 }
19237 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
19238 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
19239 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
19240 NewClassTy = NewRT->getPointeeType();
19241 OldClassTy = OldRT->getPointeeType();
19242 }
19243 }
19244 }
19245
19246 // The return types aren't either both pointers or references to a class type.
19247 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
19248 Diag(New->getLocation(),
19249 diag::err_different_return_type_for_overriding_virtual_function)
19250 << New->getDeclName() << NewTy << OldTy
19251 << New->getReturnTypeSourceRange();
19252 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19253 << Old->getReturnTypeSourceRange();
19254
19255 return true;
19256 }
19257
19258 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
19259 // C++14 [class.virtual]p8:
19260 // If the class type in the covariant return type of D::f differs from
19261 // that of B::f, the class type in the return type of D::f shall be
19262 // complete at the point of declaration of D::f or shall be the class
19263 // type D.
19264 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
19265 if (!RD->isBeingDefined() &&
19266 RequireCompleteType(New->getLocation(), NewClassTy,
19267 diag::err_covariant_return_incomplete,
19268 New->getDeclName()))
19269 return true;
19270 }
19271
19272 // Check if the new class derives from the old class.
19273 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
19274 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
19275 << New->getDeclName() << NewTy << OldTy
19276 << New->getReturnTypeSourceRange();
19277 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19278 << Old->getReturnTypeSourceRange();
19279 return true;
19280 }
19281
19282 // Check if we the conversion from derived to base is valid.
19284 NewClassTy, OldClassTy,
19285 diag::err_covariant_return_inaccessible_base,
19286 diag::err_covariant_return_ambiguous_derived_to_base_conv,
19287 New->getLocation(), New->getReturnTypeSourceRange(),
19288 New->getDeclName(), nullptr)) {
19289 // FIXME: this note won't trigger for delayed access control
19290 // diagnostics, and it's impossible to get an undelayed error
19291 // here from access control during the original parse because
19292 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19293 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19294 << Old->getReturnTypeSourceRange();
19295 return true;
19296 }
19297 }
19298
19299 // The qualifiers of the return types must be the same.
19300 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19301 Diag(New->getLocation(),
19302 diag::err_covariant_return_type_different_qualifications)
19303 << New->getDeclName() << NewTy << OldTy
19304 << New->getReturnTypeSourceRange();
19305 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19306 << Old->getReturnTypeSourceRange();
19307 return true;
19308 }
19309
19310
19311 // The new class type must have the same or less qualifiers as the old type.
19312 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
19313 Diag(New->getLocation(),
19314 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19315 << New->getDeclName() << NewTy << OldTy
19316 << New->getReturnTypeSourceRange();
19317 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
19318 << Old->getReturnTypeSourceRange();
19319 return true;
19320 }
19321
19322 return false;
19323}
19324
19326 SourceLocation EndLoc = InitRange.getEnd();
19327 if (EndLoc.isValid())
19328 Method->setRangeEnd(EndLoc);
19329
19330 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19331 Method->setIsPureVirtual();
19332 return false;
19333 }
19334
19335 if (!Method->isInvalidDecl())
19336 Diag(Method->getLocation(), diag::err_non_virtual_pure)
19337 << Method->getDeclName() << InitRange;
19338 return true;
19339}
19340
19342 if (D->getFriendObjectKind())
19343 Diag(D->getLocation(), diag::err_pure_friend);
19344 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
19345 CheckPureMethod(M, ZeroLoc);
19346 else
19347 Diag(D->getLocation(), diag::err_illegal_initializer);
19348}
19349
19350/// Invoked when we are about to parse an initializer for the declaration
19351/// 'Dcl'.
19352///
19353/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19354/// static data member of class X, names should be looked up in the scope of
19355/// class X. If the declaration had a scope specifier, a scope will have
19356/// been created and passed in for this purpose. Otherwise, S will be null.
19358 assert(D && !D->isInvalidDecl());
19359
19360 // We will always have a nested name specifier here, but this declaration
19361 // might not be out of line if the specifier names the current namespace:
19362 // extern int n;
19363 // int ::n = 0;
19364 if (S && D->isOutOfLine())
19366
19370}
19371
19373 assert(D);
19374
19375 if (S && D->isOutOfLine())
19377
19379}
19380
19382 // C++ 6.4p2:
19383 // The declarator shall not specify a function or an array.
19384 // The type-specifier-seq shall not contain typedef and shall not declare a
19385 // new class or enumeration.
19387 "Parser allowed 'typedef' as storage class of condition decl.");
19388
19389 Decl *Dcl = ActOnDeclarator(S, D);
19390 if (!Dcl)
19391 return true;
19392
19393 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
19394 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
19395 << D.getSourceRange();
19396 return true;
19397 }
19398
19399 if (auto *VD = dyn_cast<VarDecl>(Dcl))
19400 VD->setCXXCondDecl();
19401
19402 return Dcl;
19403}
19404
19406 if (!ExternalSource)
19407 return;
19408
19410 ExternalSource->ReadUsedVTables(VTables);
19412 for (const ExternalVTableUse &VTable : VTables) {
19413 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19414 VTablesUsed.find(VTable.Record);
19415 // Even if a definition wasn't required before, it may be required now.
19416 if (Pos != VTablesUsed.end()) {
19417 if (!Pos->second && VTable.DefinitionRequired)
19418 Pos->second = true;
19419 continue;
19420 }
19421
19422 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19423 NewUses.push_back(VTableUse(VTable.Record, VTable.Location));
19424 }
19425
19426 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
19427}
19428
19430 bool DefinitionRequired) {
19431 // Ignore any vtable uses in unevaluated operands or for classes that do
19432 // not have a vtable.
19433 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19434 CurContext->isDependentContext() || isUnevaluatedContext())
19435 return;
19436 // Do not mark as used if compiling for the device outside of the target
19437 // region.
19438 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19439 !OpenMP().isInOpenMPDeclareTargetContext() &&
19440 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19441 if (!DefinitionRequired)
19443 return;
19444 }
19445
19446 // Try to insert this class into the map.
19448 Class = Class->getCanonicalDecl();
19449 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19450 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
19451 if (!Pos.second) {
19452 // If we already had an entry, check to see if we are promoting this vtable
19453 // to require a definition. If so, we need to reappend to the VTableUses
19454 // list, since we may have already processed the first entry.
19455 if (DefinitionRequired && !Pos.first->second) {
19456 Pos.first->second = true;
19457 } else {
19458 // Otherwise, we can early exit.
19459 return;
19460 }
19461 } else {
19462 // The Microsoft ABI requires that we perform the destructor body
19463 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19464 // the deleting destructor is emitted with the vtable, not with the
19465 // destructor definition as in the Itanium ABI.
19466 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19467 CXXDestructorDecl *DD = Class->getDestructor();
19468 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19469 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19470 // If this is an out-of-line declaration, marking it referenced will
19471 // not do anything. Manually call CheckDestructor to look up operator
19472 // delete().
19473 ContextRAII SavedContext(*this, DD);
19474 CheckDestructor(DD);
19475 if (!DD->getOperatorDelete())
19476 DD->setInvalidDecl();
19477 } else {
19478 MarkFunctionReferenced(Loc, Class->getDestructor());
19479 }
19480 }
19481 }
19482 }
19483
19484 // Local classes need to have their virtual members marked
19485 // immediately. For all other classes, we mark their virtual members
19486 // at the end of the translation unit.
19487 if (Class->isLocalClass())
19488 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
19489 else
19490 VTableUses.push_back(std::make_pair(Class, Loc));
19491}
19492
19495 if (VTableUses.empty())
19496 return false;
19497
19498 // Note: The VTableUses vector could grow as a result of marking
19499 // the members of a class as "used", so we check the size each
19500 // time through the loop and prefer indices (which are stable) to
19501 // iterators (which are not).
19502 bool DefinedAnything = false;
19503 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19504 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19505 if (!Class)
19506 continue;
19508 Class->getTemplateSpecializationKind();
19509
19510 SourceLocation Loc = VTableUses[I].second;
19511
19512 bool DefineVTable = true;
19513
19514 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
19515 // V-tables for non-template classes with an owning module are always
19516 // uniquely emitted in that module.
19517 if (Class->isInCurrentModuleUnit()) {
19518 DefineVTable = true;
19519 } else if (KeyFunction && !KeyFunction->hasBody()) {
19520 // If this class has a key function, but that key function is
19521 // defined in another translation unit, we don't need to emit the
19522 // vtable even though we're using it.
19523 // The key function is in another translation unit.
19524 DefineVTable = false;
19526 KeyFunction->getTemplateSpecializationKind();
19529 "Instantiations don't have key functions");
19530 (void)TSK;
19531 } else if (!KeyFunction) {
19532 // If we have a class with no key function that is the subject
19533 // of an explicit instantiation declaration, suppress the
19534 // vtable; it will live with the explicit instantiation
19535 // definition.
19536 bool IsExplicitInstantiationDeclaration =
19538 for (auto *R : Class->redecls()) {
19540 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
19542 IsExplicitInstantiationDeclaration = true;
19543 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19544 IsExplicitInstantiationDeclaration = false;
19545 break;
19546 }
19547 }
19548
19549 if (IsExplicitInstantiationDeclaration) {
19550 const bool HasExcludeFromExplicitInstantiation =
19551 llvm::any_of(Class->methods(), [](CXXMethodDecl *method) {
19552 // If the class has a member function declared with
19553 // `__attribute__((exclude_from_explicit_instantiation))`, the
19554 // explicit instantiation declaration should not suppress emitting
19555 // the vtable, since the corresponding explicit instantiation
19556 // definition might not emit the vtable if a triggering method is
19557 // excluded.
19558 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19559 });
19560 if (!HasExcludeFromExplicitInstantiation)
19561 DefineVTable = false;
19562 }
19563 }
19564
19565 // The exception specifications for all virtual members may be needed even
19566 // if we are not providing an authoritative form of the vtable in this TU.
19567 // We may choose to emit it available_externally anyway.
19568 if (!DefineVTable) {
19570 continue;
19571 }
19572
19573 // Mark all of the virtual members of this class as referenced, so
19574 // that we can build a vtable. Then, tell the AST consumer that a
19575 // vtable for this class is required.
19576 DefinedAnything = true;
19578 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19579 // The vtable is assumed to be emitted in an external source only for
19580 // classes attached to a named module, which is guaranteed to have an object
19581 // file. This isn't true for -fmodules-debuginfo, which still has
19582 // shouldEmitInExternalSource as true so that debug info gets supressed.
19583 if (VTablesUsed[Canonical] &&
19584 !(Class->isInNamedModule() && Class->shouldEmitInExternalSource()))
19585 Consumer.HandleVTable(Class);
19586
19587 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19588 // no key function or the key function is inlined. Don't warn in C++ ABIs
19589 // that lack key functions, since the user won't be able to make one.
19590 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19591 Class->isExternallyVisible() &&
19592 !(Class->getOwningModule() &&
19593 Class->getOwningModule()->isInterfaceOrPartition()) &&
19594 ClassTSK != TSK_ImplicitInstantiation &&
19597 const FunctionDecl *KeyFunctionDef = nullptr;
19598 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
19599 KeyFunctionDef->isInlined()))
19600 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
19601 }
19602 }
19603 VTableUses.clear();
19604
19605 return DefinedAnything;
19606}
19607
19609 const CXXRecordDecl *RD) {
19610 for (const auto *I : RD->methods())
19611 if (I->isVirtual() && !I->isPureVirtual())
19612 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
19613}
19614
19616 const CXXRecordDecl *RD,
19617 bool ConstexprOnly) {
19618 // Mark all functions which will appear in RD's vtable as used.
19619 CXXFinalOverriderMap FinalOverriders;
19620 RD->getFinalOverriders(FinalOverriders);
19621 for (const auto &FinalOverrider : FinalOverriders) {
19622 for (const auto &OverridingMethod : FinalOverrider.second) {
19623 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19624 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19625
19626 // C++ [basic.def.odr]p2:
19627 // [...] A virtual member function is used if it is not pure. [...]
19628 if (!Overrider->isPureVirtual() &&
19629 (!ConstexprOnly || Overrider->isConstexpr()))
19630 MarkFunctionReferenced(Loc, Overrider);
19631 }
19632 }
19633
19634 // Only classes that have virtual bases need a VTT.
19635 if (RD->getNumVBases() == 0)
19636 return;
19637
19638 for (const auto &I : RD->bases()) {
19639 const auto *Base = I.getType()->castAsCXXRecordDecl();
19640 if (Base->getNumVBases() == 0)
19641 continue;
19643 }
19644}
19645
19646static
19651 Sema &S) {
19652 if (Ctor->isInvalidDecl())
19653 return;
19654
19656
19657 // Target may not be determinable yet, for instance if this is a dependent
19658 // call in an uninstantiated template.
19659 if (Target) {
19660 const FunctionDecl *FNTarget = nullptr;
19661 (void)Target->hasBody(FNTarget);
19662 Target = const_cast<CXXConstructorDecl*>(
19663 cast_or_null<CXXConstructorDecl>(FNTarget));
19664 }
19665
19666 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19667 // Avoid dereferencing a null pointer here.
19668 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19669
19670 if (!Current.insert(Canonical).second)
19671 return;
19672
19673 // We know that beyond here, we aren't chaining into a cycle.
19674 if (!Target || !Target->isDelegatingConstructor() ||
19675 Target->isInvalidDecl() || Valid.count(TCanonical)) {
19676 Valid.insert_range(Current);
19677 Current.clear();
19678 // We've hit a cycle.
19679 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
19680 Current.count(TCanonical)) {
19681 // If we haven't diagnosed this cycle yet, do so now.
19682 if (!Invalid.count(TCanonical)) {
19683 S.Diag((*Ctor->init_begin())->getSourceLocation(),
19684 diag::warn_delegating_ctor_cycle)
19685 << Ctor;
19686
19687 // Don't add a note for a function delegating directly to itself.
19688 if (TCanonical != Canonical)
19689 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
19690
19692 while (C->getCanonicalDecl() != Canonical) {
19693 const FunctionDecl *FNTarget = nullptr;
19694 (void)C->getTargetConstructor()->hasBody(FNTarget);
19695 assert(FNTarget && "Ctor cycle through bodiless function");
19696
19697 C = const_cast<CXXConstructorDecl*>(
19698 cast<CXXConstructorDecl>(FNTarget));
19699 S.Diag(C->getLocation(), diag::note_which_delegates_to);
19700 }
19701 }
19702
19703 Invalid.insert_range(Current);
19704 Current.clear();
19705 } else {
19707 }
19708}
19709
19710
19713
19714 for (DelegatingCtorDeclsType::iterator
19715 I = DelegatingCtorDecls.begin(ExternalSource.get()),
19716 E = DelegatingCtorDecls.end();
19717 I != E; ++I)
19718 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
19719
19720 for (CXXConstructorDecl *CI : Invalid)
19721 CI->setInvalidDecl();
19722}
19723
19724namespace {
19725 /// AST visitor that finds references to the 'this' expression.
19726class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19727 Sema &S;
19728
19729public:
19730 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19731
19732 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19733 S.Diag(E->getLocation(), diag::err_this_static_member_func)
19734 << E->isImplicit();
19735 return false;
19736 }
19737};
19738}
19739
19741 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19742 if (!TSInfo)
19743 return false;
19744
19745 TypeLoc TL = TSInfo->getTypeLoc();
19747 if (!ProtoTL)
19748 return false;
19749
19750 // C++11 [expr.prim.general]p3:
19751 // [The expression this] shall not appear before the optional
19752 // cv-qualifier-seq and it shall not appear within the declaration of a
19753 // static member function (although its type and value category are defined
19754 // within a static member function as they are within a non-static member
19755 // function). [ Note: this is because declaration matching does not occur
19756 // until the complete declarator is known. - end note ]
19757 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19758 FindCXXThisExpr Finder(*this);
19759
19760 // If the return type came after the cv-qualifier-seq, check it now.
19761 if (Proto->hasTrailingReturn() &&
19762 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19763 return true;
19764
19765 // Check the exception specification.
19767 return true;
19768
19769 // Check the trailing requires clause
19770 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19771 if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))
19772 return true;
19773
19775}
19776
19778 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19779 if (!TSInfo)
19780 return false;
19781
19782 TypeLoc TL = TSInfo->getTypeLoc();
19784 if (!ProtoTL)
19785 return false;
19786
19787 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19788 FindCXXThisExpr Finder(*this);
19789
19790 switch (Proto->getExceptionSpecType()) {
19791 case EST_Unparsed:
19792 case EST_Uninstantiated:
19793 case EST_Unevaluated:
19794 case EST_BasicNoexcept:
19795 case EST_NoThrow:
19796 case EST_DynamicNone:
19797 case EST_MSAny:
19798 case EST_None:
19799 break;
19800
19802 case EST_NoexceptFalse:
19803 case EST_NoexceptTrue:
19804 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19805 return true;
19806 [[fallthrough]];
19807
19808 case EST_Dynamic:
19809 for (const auto &E : Proto->exceptions()) {
19810 if (!Finder.TraverseType(E))
19811 return true;
19812 }
19813 break;
19814 }
19815
19816 return false;
19817}
19818
19820 FindCXXThisExpr Finder(*this);
19821
19822 // Check attributes.
19823 for (const auto *A : Method->attrs()) {
19824 // FIXME: This should be emitted by tblgen.
19825 Expr *Arg = nullptr;
19826 ArrayRef<Expr *> Args;
19827 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19828 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19829 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19830 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19831 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19832 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19833 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19834 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19835 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19836 Arg = LR->getArg();
19837 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19838 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19839 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19840 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19841 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19842 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19843 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {
19844 Arg = AC->getSuccessValue();
19845 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19846 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19847 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19848
19849 if (Arg && !Finder.TraverseStmt(Arg))
19850 return true;
19851
19852 for (Expr *A : Args) {
19853 if (!Finder.TraverseStmt(A))
19854 return true;
19855 }
19856 }
19857
19858 return false;
19859}
19860
19862 bool IsTopLevel, ExceptionSpecificationType EST,
19863 ArrayRef<ParsedType> DynamicExceptions,
19864 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19865 SmallVectorImpl<QualType> &Exceptions,
19867 Exceptions.clear();
19868 ESI.Type = EST;
19869 if (EST == EST_Dynamic) {
19870 Exceptions.reserve(DynamicExceptions.size());
19871 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19872 // FIXME: Preserve type source info.
19873 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19874
19875 if (IsTopLevel) {
19877 collectUnexpandedParameterPacks(ET, Unexpanded);
19878 if (!Unexpanded.empty()) {
19880 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19881 Unexpanded);
19882 continue;
19883 }
19884 }
19885
19886 // Check that the type is valid for an exception spec, and
19887 // drop it if not.
19888 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19889 Exceptions.push_back(ET);
19890 }
19891 ESI.Exceptions = Exceptions;
19892 return;
19893 }
19894
19895 if (isComputedNoexcept(EST)) {
19896 assert((NoexceptExpr->isTypeDependent() ||
19897 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19898 Context.BoolTy) &&
19899 "Parser should have made sure that the expression is boolean");
19900 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19901 ESI.Type = EST_BasicNoexcept;
19902 return;
19903 }
19904
19905 ESI.NoexceptExpr = NoexceptExpr;
19906 return;
19907 }
19908}
19909
19911 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19912 ArrayRef<ParsedType> DynamicExceptions,
19913 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19914 if (!D)
19915 return;
19916
19917 // Dig out the function we're referring to.
19918 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
19919 D = FTD->getTemplatedDecl();
19920
19921 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
19922 if (!FD)
19923 return;
19924
19925 // Check the exception specification.
19928 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19929 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19930 ESI);
19931
19932 // Update the exception specification on the function type.
19933 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19934
19935 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19936 if (MD->isStatic())
19938
19939 if (MD->isVirtual()) {
19940 // Check overrides, which we previously had to delay.
19941 for (const CXXMethodDecl *O : MD->overridden_methods())
19943 }
19944 }
19945}
19946
19947/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19948///
19950 SourceLocation DeclStart, Declarator &D,
19951 Expr *BitWidth,
19952 InClassInitStyle InitStyle,
19953 AccessSpecifier AS,
19954 const ParsedAttr &MSPropertyAttr) {
19955 const IdentifierInfo *II = D.getIdentifier();
19956 if (!II) {
19957 Diag(DeclStart, diag::err_anonymous_property);
19958 return nullptr;
19959 }
19961
19963 QualType T = TInfo->getType();
19964 if (getLangOpts().CPlusPlus) {
19966
19969 D.setInvalidType();
19970 T = Context.IntTy;
19971 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19972 }
19973 }
19974
19976
19978 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19979 << getLangOpts().CPlusPlus17;
19982 diag::err_invalid_thread)
19984
19985 // Check to see if this name was declared as a member previously
19986 NamedDecl *PrevDecl = nullptr;
19987 LookupResult Previous(*this, II, Loc, LookupMemberName,
19989 LookupName(Previous, S);
19990 switch (Previous.getResultKind()) {
19993 PrevDecl = Previous.getAsSingle<NamedDecl>();
19994 break;
19995
19997 PrevDecl = Previous.getRepresentativeDecl();
19998 break;
19999
20003 break;
20004 }
20005
20006 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20007 // Maybe we will complain about the shadowed template parameter.
20009 // Just pretend that we didn't see the previous declaration.
20010 PrevDecl = nullptr;
20011 }
20012
20013 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
20014 PrevDecl = nullptr;
20015
20016 SourceLocation TSSL = D.getBeginLoc();
20017 MSPropertyDecl *NewPD =
20018 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
20019 MSPropertyAttr.getPropertyDataGetter(),
20020 MSPropertyAttr.getPropertyDataSetter());
20021 ProcessDeclAttributes(TUScope, NewPD, D);
20022 NewPD->setAccess(AS);
20023
20024 if (NewPD->isInvalidDecl())
20025 Record->setInvalidDecl();
20026
20028 NewPD->setModulePrivate();
20029
20030 if (NewPD->isInvalidDecl() && PrevDecl) {
20031 // Don't introduce NewFD into scope; there's already something
20032 // with the same name in the same scope.
20033 } else if (II) {
20034 PushOnScopeChains(NewPD, S);
20035 } else
20036 Record->addDecl(NewPD);
20037
20038 return NewPD;
20039}
20040
20042 Declarator &Declarator, unsigned TemplateParameterDepth) {
20043 auto &Info = InventedParameterInfos.emplace_back();
20044 TemplateParameterList *ExplicitParams = nullptr;
20045 ArrayRef<TemplateParameterList *> ExplicitLists =
20047 if (!ExplicitLists.empty()) {
20048 bool IsMemberSpecialization, IsInvalid;
20051 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
20052 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
20053 /*SuppressDiagnostic=*/true);
20054 }
20055 // C++23 [dcl.fct]p23:
20056 // An abbreviated function template can have a template-head. The invented
20057 // template-parameters are appended to the template-parameter-list after
20058 // the explicitly declared template-parameters.
20059 //
20060 // A template-head must have one or more template-parameters (read:
20061 // 'template<>' is *not* a template-head). Only append the invented
20062 // template parameters if we matched the nested-name-specifier to a non-empty
20063 // TemplateParameterList.
20064 if (ExplicitParams && !ExplicitParams->empty()) {
20065 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
20066 llvm::append_range(Info.TemplateParams, *ExplicitParams);
20067 Info.NumExplicitTemplateParams = ExplicitParams->size();
20068 } else {
20069 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
20070 Info.NumExplicitTemplateParams = 0;
20071 }
20072}
20073
20075 auto &FSI = InventedParameterInfos.back();
20076 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
20077 if (FSI.NumExplicitTemplateParams != 0) {
20078 TemplateParameterList *ExplicitParams =
20082 Context, ExplicitParams->getTemplateLoc(),
20083 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
20084 ExplicitParams->getRAngleLoc(),
20085 ExplicitParams->getRequiresClause()));
20086 } else {
20089 FSI.TemplateParams, Declarator.getEndLoc(),
20090 /*RequiresClause=*/nullptr));
20091 }
20092 }
20093 InventedParameterInfos.pop_back();
20094}
20095
20097 CXXConstructorDecl *Ctor, bool IsCopy) {
20098 assert(Context.getTargetInfo().getCXXABI().isMicrosoft());
20099
20100 if (!Ctor->getCtorClosureDefaultArgs().empty()) {
20101 // If we build args for default constructor closures, those will have
20102 // been generated *before* building args for any copy constructor closures.
20103 assert(IsCopy || Ctor->getCtorClosureDefaultArgs()[0] != nullptr);
20104 return false;
20105 }
20106
20107 unsigned NumParams = Ctor->getNumParams();
20108 if (NumParams == 0)
20109 return false;
20110
20111 CXXDefaultArgExpr **Args =
20112 new (getASTContext()) CXXDefaultArgExpr *[NumParams];
20113
20114 if (IsCopy)
20115 Args[0] = nullptr; // Copy ctor closure will provide the first argument.
20116
20117 for (unsigned I = IsCopy ? 1 : 0; I != NumParams; ++I) {
20118 ExprResult R = BuildCXXDefaultArgExpr(Loc, Ctor, Ctor->getParamDecl(I));
20120 if (R.isInvalid())
20121 return true;
20122 Args[I] = cast<CXXDefaultArgExpr>(R.get());
20123 }
20124
20125 Ctor->setCtorClosureDefaultArgs(ArrayRef(Args, NumParams));
20126 return false;
20127}
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)
static AccessResult DeduceTemplateArguments(Sema &S, FriendTemplateDecl *FTD, DeclContext *DC, const TemplateSpecializationType *TST, ArrayRef< TemplateParameterList * > TPLs, TemplateSpecCandidateSet *FailedTSC, MultiLevelTemplateArgumentList &DeducedArgs)
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 Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
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 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 const TemplateSpecializationType * GetClassTemplateSpecializationType(ASTContext &Context, QualType T)
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 QualType IgnorePackIndexing(QualType T)
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 void DiagnoseDependentFriendNotMember(Sema &S, SourceLocation Loc, NestedNameSpecifier NNS)
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 void MarkUsedTemplateParameters(ASTContext &Ctx, const TemplateArgument &TemplateArg, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark the template parameters that are used by this template argument.
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:158
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:75
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:245
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:856
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:852
const LangOptions & getLangOpts() const
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:905
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:971
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:1838
QualType getElementType() const
Definition TypeBase.h:3832
Attr - This represents one attribute.
Definition Attr.h:47
attr::Kind getKind() const
Definition Attr.h:93
bool isInherited() const
Definition Attr.h:102
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition Attr.h:100
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3526
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3604
void addShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3516
shadow_iterator shadow_begin() const
Definition DeclCXX.h:3596
void removeShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3525
Expr * getLHS() const
Definition Expr.h:4157
Expr * getRHS() const
Definition Expr.h:4159
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:5144
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4248
Opcode getOpcode() const
Definition Expr.h:4152
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2179
A binding in a decomposition declaration.
Definition DeclCXX.h:4215
void setDecomposedDecl(DecompositionDecl *Decomposed)
Set the decomposed variable for this BindingDecl.
Definition DeclCXX.h:4259
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition DeclCXX.cpp:3707
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:4253
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6758
Wrapper for source info for block pointers.
Definition TypeLoc.h:1557
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Kind getKind() const
Definition TypeBase.h:3299
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:728
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:29
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
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:1212
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
bool isImmediateEscalating() const
Definition ExprCXX.h:1711
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2882
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:3063
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition DeclCXX.h:2736
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition DeclCXX.cpp:3040
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:3058
void setCtorClosureDefaultArgs(ArrayRef< CXXDefaultArgExpr * > Args)
Definition DeclCXX.cpp:3143
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition DeclCXX.h:2877
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:3018
ArrayRef< CXXDefaultArgExpr * > getCtorClosureDefaultArgs() const
Definition DeclCXX.cpp:3139
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclCXX.h:2714
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2977
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3013
Represents a C++ base or member initializer.
Definition DeclCXX.h:2407
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition DeclCXX.h:2579
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition DeclCXX.cpp:2966
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition DeclCXX.cpp:2953
bool isAnyMemberInitializer() const
Definition DeclCXX.h:2487
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition DeclCXX.h:2541
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2553
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1275
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
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:3158
const FunctionDecl * getOperatorDelete() const
Definition DeclCXX.cpp:3230
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:1756
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:184
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:773
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
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:2719
bool isVirtual() const
Definition DeclCXX.h:2205
CXXSpecialMemberKind getSpecialMemberKind() const
Definition DeclCXX.h:2229
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:2504
unsigned getNumExplicitParams() const
Definition DeclCXX.h:2321
CXXMethodDecl * getMostRecentDecl()
Definition DeclCXX.h:2270
overridden_method_range overridden_methods() const
Definition DeclCXX.cpp:2828
unsigned size_overridden_methods() const
Definition DeclCXX.cpp:2822
method_iterator begin_overridden_methods() const
Definition DeclCXX.cpp:2812
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2293
bool isInstance() const
Definition DeclCXX.h:2177
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2317
bool isStatic() const
Definition DeclCXX.cpp:2417
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2263
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:773
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:1286
friend_range friends() const
Definition DeclFriend.h:183
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition DeclCXX.h:1357
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition DeclCXX.cpp:613
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1256
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1681
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1382
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition DeclCXX.h:1011
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition DeclCXX.h:827
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition DeclCXX.h:719
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition DeclCXX.h:1436
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1407
bool hasTrivialDestructorForCall() const
Definition DeclCXX.h:1386
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition DeclCXX.h:711
bool isLiteral() const
Determine whether this class is a literal type.
Definition DeclCXX.cpp:1508
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition DeclCXX.h:970
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1372
base_class_range bases()
Definition DeclCXX.h:609
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:606
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1028
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1317
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition DeclCXX.h:771
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition DeclCXX.h:899
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition DeclCXX.h:918
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:651
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition DeclCXX.h:940
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition DeclCXX.h:1745
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1279
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1294
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition DeclCXX.h:982
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition DeclCXX.cpp:601
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1224
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition DeclCXX.h:702
bool hasTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1298
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:732
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2062
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition DeclCXX.h:1344
base_class_range vbases()
Definition DeclCXX.h:626
base_class_iterator vbases_begin()
Definition DeclCXX.h:633
ctor_range ctors() const
Definition DeclCXX.h:671
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition DeclCXX.h:874
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1231
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition DeclCXX.h:1246
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition DeclCXX.h:865
bool isDynamicClass() const
Definition DeclCXX.h:575
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1158
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition DeclCXX.h:805
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition DeclCXX.h:1418
bool hasNonTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1309
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition DeclCXX.h:1210
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition DeclCXX.h:799
bool hasDefinition() const
Definition DeclCXX.h:562
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition DeclCXX.h:924
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition DeclCXX.h:1017
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2054
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:910
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2154
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition DeclCXX.h:1004
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2129
bool hasNonTrivialDestructorForCall() const
Definition DeclCXX.h:1396
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition DeclCXX.h:1023
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition DeclCXX.h:1430
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition DeclCXX.cpp:1756
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition DeclCXX.h:812
CXXRecordDecl * getDefinitionOrSelf() const
Definition DeclCXX.h:556
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition DeclCXX.h:853
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition DeclCXX.h:992
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition DeclCXX.h:933
bool hasTrivialMoveConstructorForCall() const
Definition DeclCXX.h:1322
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:523
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:624
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:955
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:184
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:189
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:83
SourceLocation getBeginLoc() const
Definition DeclSpec.h:87
bool isSet() const
Deprecated.
Definition DeclSpec.h:202
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:98
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:187
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:182
Represents the this expression in C++.
Definition ExprCXX.h:1159
SourceLocation getBeginLoc() const
Definition ExprCXX.h:1179
bool isImplicit() const
Definition ExprCXX.h:1182
SourceLocation getLocation() const
Definition ExprCXX.h:1176
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:70
CXXCatchStmt * getHandler(unsigned i)
Definition StmtCXX.h:109
unsigned getNumHandlers() const
Definition StmtCXX.h:108
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
bool isCallToStdMove() const
Definition Expr.cpp:3682
Expr * getCallee()
Definition Expr.h:3159
arg_range arguments()
Definition Expr.h:3264
QualType withConst() const
Retrieves a version of this type with const applied.
CastKind getCastKind() const
Definition Expr.h:3789
Expr * getSubExpr()
Definition Expr.h:3795
static CharSourceRange getTokenRange(SourceRange R)
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
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:3362
QualType getElementType() const
Definition TypeBase.h:3372
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:3858
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
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:3707
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition DeclCXX.h:3771
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition DeclCXX.cpp:3498
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:5402
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:1400
DeclListNode::iterator iterator
Definition DeclBase.h:1410
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition DeclBase.h:2438
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2121
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2274
lookup_result::iterator lookup_iterator
Definition DeclBase.h:2623
bool isFileContext() const
Definition DeclBase.h:2212
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:2217
bool isRecord() const
Definition DeclBase.h:2221
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:2420
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2418
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2176
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:2114
DeclContext * getNonTransparentContext()
decl_iterator decls_begin() const
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
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:498
ValueDecl * getDecl()
Definition Expr.h:1383
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1513
SourceLocation getBeginLoc() const
Definition Expr.h:1394
bool isImmediateEscalating() const
Definition Expr.h:1523
Captures information about "declaration specifiers".
Definition DeclSpec.h:279
bool isVirtualSpecified() const
Definition DeclSpec.h:721
bool isModulePrivateSpecified() const
Definition DeclSpec.h:902
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:764
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:637
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:296
void ClearStorageClassSpecs()
Definition DeclSpec.h:566
TST getTypeSpecType() const
Definition DeclSpec.h:588
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:561
SCS getStorageClassSpec() const
Definition DeclSpec.h:552
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:626
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:625
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:668
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:727
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:900
ParsedType getRepAsType() const
Definition DeclSpec.h:598
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:553
bool isFriendSpecifiedFirst() const
Definition DeclSpec.h:898
ParsedAttributes & getAttributes()
Definition DeclSpec.h:946
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:669
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:728
Expr * getRepAsExpr() const
Definition DeclSpec.h:606
bool isInlineSpecified() const
Definition DeclSpec.h:710
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:670
TypeSpecifierType TST
Definition DeclSpec.h:309
bool SetTypeQual(TQ T, SourceLocation Loc)
void ClearConstexprSpec()
Definition DeclSpec.h:914
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:534
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:562
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:672
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:722
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:909
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:633
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:429
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:713
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:673
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:671
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:894
bool hasExplicitSpecifier() const
Definition DeclSpec.h:724
bool hasConstexprSpecifier() const
Definition DeclSpec.h:910
static const TST TST_auto
Definition DeclSpec.h:350
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1642
decl_range decls()
Definition Stmt.h:1690
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:1668
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:1079
bool isInStdNamespace() const
Definition DeclBase.cpp:453
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:444
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1244
T * getAttr() const
Definition DeclBase.h:582
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:101
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:594
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1237
@ FOK_None
Not a friend object.
Definition DeclBase.h:1235
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:2820
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
Definition DeclBase.h:597
unsigned getIdentifierNamespace() const
Definition DeclBase.h:907
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1187
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:511
SourceLocation getLocation() const
Definition DeclBase.h:448
@ 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:842
void setImplicit(bool I=true)
Definition DeclBase.h:603
void setReferenced(bool R=true)
Definition DeclBase.h:632
DeclContext * getDeclContext()
Definition DeclBase.h:457
AccessSpecifier getAccess() const
Definition DeclBase.h:516
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:440
void dropAttr()
Definition DeclBase.h:565
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
bool hasAttr() const
Definition DeclBase.h:586
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
@ 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:899
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:782
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2005
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:833
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:857
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:816
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
Definition Decl.h:864
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:811
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1996
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2559
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:2501
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2146
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2613
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2436
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2439
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2183
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2514
bool hasGroupingParens() const
Definition DeclSpec.h:2827
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2821
void DropFirstTypeObject()
Definition DeclSpec.h:2518
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2497
bool isRedeclaration() const
Definition DeclSpec.h:2873
DeclaratorContext getContext() const
Definition DeclSpec.h:2171
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2167
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2182
bool isFunctionDefinition() const
Definition DeclSpec.h:2845
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2165
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2161
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition DeclSpec.h:2752
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition DeclSpec.h:2759
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition DeclSpec.h:2311
bool isInvalidType() const
Definition DeclSpec.h:2822
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2181
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2426
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:391
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2153
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2590
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2430
A decomposition declaration.
Definition DeclCXX.h:4279
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4319
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1884
ArrayRef< Binding > bindings() const
Definition DeclSpec.h:1924
SourceRange getSourceRange() const
Definition DeclSpec.h:1932
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1930
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2632
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2612
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2621
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:992
virtual bool TraverseConstructorInitializer(MaybeConst< CXXCtorInitializer > *Init)
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5994
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:3574
Represents an enum.
Definition Decl.h:4162
enumerator_range enumerators() const
Definition Decl.h:4308
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
const Expr * getExpr() const
Definition DeclCXX.h:1958
void setExpr(Expr *E)
Definition DeclCXX.h:1983
void setKind(ExplicitSpecKind Kind)
Definition DeclCXX.h:1982
This represents one expression.
Definition Expr.h:114
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:179
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3117
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isPRValue() const
Definition Expr.h:287
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
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:3292
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:146
Represents difference between two FPOptions values.
FPOptions applyOverrides(FPOptions Base)
Represents a member of a struct/union/class.
Definition Decl.h:3311
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3411
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4816
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3491
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4806
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3485
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition Decl.cpp:4826
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3547
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3558
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3417
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
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:116
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:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
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:103
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:46
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend, SourceLocation FriendL, SourceLocation EllipsisLoc={})
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, FriendUnion Friend, SourceLocation FriendLoc, ArrayRef< TemplateParameterList * > FriendTPLists, SourceLocation EllipsisLoc={}, TemplateName Template={})
For a defaulted function, the kind of defaulted function that it is.
Definition Decl.h:2135
CXXSpecialMemberKind asSpecialMember() const
Definition Decl.h:2164
DefaultedComparisonKind asComparison() const
Definition Decl.h:2167
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, FPOptionsOverride FPFeatures, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3146
Represents a function declaration or definition.
Definition Decl.h:2071
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2785
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2944
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3286
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition Decl.h:3016
bool isTrivialForCall() const
Definition Decl.h:2519
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2615
DefaultedOrDeletedFunctionInfo * getDefaultedOrDeletedInfo() const
Definition Decl.cpp:3201
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3914
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4257
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2440
bool isImmediateFunction() const
Definition Decl.cpp:3402
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition Decl.cpp:3167
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4091
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3613
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3932
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3068
SourceLocation getDefaultLoc() const
Definition Decl.h:2537
QualType getReturnType() const
Definition Decl.h:2992
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2917
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2528
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2516
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4377
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition Decl.h:2925
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3809
param_iterator param_begin()
Definition Decl.h:2929
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2970
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3139
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2452
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2679
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition Decl.h:2625
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4393
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3285
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4321
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:3035
bool isStatic() const
Definition Decl.h:3076
void setTrivial(bool IT)
Definition Decl.h:2517
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4208
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2609
static constexpr unsigned RequiredTypeAwareNewParameterCount
Count of mandatory parameters for type aware operator new.
Definition Decl.h:2781
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2492
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3680
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isImmediateEscalating() const
Definition Decl.cpp:3373
void setIsDestroyingOperatorDelete(bool IsDestroyingDelete)
Definition Decl.cpp:3617
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3621
void setIsTypeAwareOperatorNewOrDelete(bool IsTypeAwareOperator=true)
Definition Decl.cpp:3625
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2524
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4634
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:3080
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4194
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2612
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4481
void setDefaulted(bool D=true)
Definition Decl.h:2525
bool isConsteval() const
Definition Decl.h:2621
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2549
DefaultedFunctionKind getDefaultedFunctionKind() const
Determine the kind of defaulting that would be done for a given function.
Definition Decl.cpp:3306
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:3009
void setBody(Stmt *B)
Definition Decl.cpp:3298
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2483
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition Decl.cpp:3946
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3888
size_t param_size() const
Definition Decl.h:2933
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2337
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3206
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:3253
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:2952
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2828
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5484
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:6006
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5516
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5348
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ValueDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ValueDecl * > Params)
Definition ExprCXX.cpp:1832
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:6052
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5855
unsigned getNumParams() const
Definition TypeBase.h:5826
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5968
const QualType * param_type_iterator
Definition TypeBase.h:5986
QualType getParamType(unsigned i) const
Definition TypeBase.h:5828
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5952
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5837
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5913
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5833
ArrayRef< QualType > exceptions() const
Definition TypeBase.h:6002
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:6017
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:1675
unsigned getNumParams() const
Definition TypeLoc.h:1747
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1753
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1754
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1756
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4967
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
CallingConv getCallConv() const
Definition TypeBase.h:5099
QualType getReturnType() const
Definition TypeBase.h:5084
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:2270
RAII class that temporarily sets the "ignore all warnings" state on a DiagnosticsEngine and restores ...
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1776
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2109
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6143
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3618
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3639
void setInherited(bool I)
Definition Attr.h:164
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2613
ConstructorUsingShadowDecl * getShadowDecl() const
Definition DeclCXX.h:2625
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5377
unsigned getNumInits() const
Definition Expr.h:5410
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
child_range children()
Definition Expr.h:5584
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:985
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3715
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition ExprCXX.cpp:1390
capture_range captures() const
Retrieve this lambda's captures.
Definition ExprCXX.cpp:1403
@ 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:1075
Represents a linkage specification.
Definition DeclCXX.h:3045
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3313
void setRBraceLoc(SourceLocation L)
Definition DeclCXX.h:3087
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.
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:4397
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition DeclCXX.cpp:3839
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3510
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3628
Wrapper for source info for member pointers.
Definition TypeLoc.h:1575
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
Describes a module or submodule.
Definition Module.h:340
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:953
bool isExplicitGlobalModule() const
Definition Module.h:444
This represents a decl that may have a name.
Definition Decl.h:276
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:489
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1097
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:719
Represents a C++ namespace alias.
Definition DeclCXX.h:3231
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamespaceBaseDecl *Namespace)
Definition DeclCXX.cpp:3414
Represents C++ namespaces and their aliases.
Definition Decl.h:575
NamespaceDecl * getNamespace()
Definition DeclCXX.cpp:3351
Represent a C++ namespace.
Definition Decl.h:594
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition Decl.h:650
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3374
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace that inhabits this namespace, if any.
Definition Decl.h:677
void setRBraceLoc(SourceLocation L)
Definition Decl.h:696
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.
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
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...
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier, or null.
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:1223
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1175
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1380
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:280
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:5016
Represents a parameter to a function.
Definition Decl.h:1832
void setDefaultArg(Expr *defarg)
Definition Decl.cpp:3028
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1973
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1961
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition Decl.cpp:3033
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3053
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1865
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1965
bool hasInheritedDefaultArg() const
Definition Decl.h:1977
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:2963
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3058
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3064
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1981
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2986
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:838
const ParsedAttr * getMSPropertyAttr() const
Definition ParsedAttr.h:924
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:918
bool isAddressDiscriminated() const
Definition TypeBase.h:266
Wrapper for source info for pointers.
Definition TypeLoc.h:1544
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
ArrayRef< Expr * > semantics()
Definition Expr.h:6962
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1473
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8667
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1241
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
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:8763
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1090
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8624
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1458
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2914
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:8743
Represents a template name as written in source code.
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
void addAddressSpace(LangAS space)
Definition TypeBase.h:598
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
void removeAddressSpace()
Definition TypeBase.h:597
void removeVolatile()
Definition TypeBase.h:470
LangAS getAddressSpace() const
Definition TypeBase.h:572
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:549
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3733
Represents a struct/union/class.
Definition Decl.h:4476
bool hasFlexibleArrayMember() const
Definition Decl.h:4509
bool hasObjectMember() const
Definition Decl.h:4536
field_iterator field_end() const
Definition Decl.h:4682
field_range fields() const
Definition Decl.h:4679
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4676
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4664
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4528
bool field_empty() const
Definition Decl.h:4687
field_iterator field_begin() const
Definition Decl.cpp:5372
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:5484
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
QualType getPointeeType() const
Definition TypeBase.h:3700
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:395
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:348
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:384
void RemoveDecl(Decl *D)
Definition Scope.h:356
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
Scope * getDeclParent()
Definition Scope.h:321
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:639
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:1340
A RAII object to temporarily push a declaration context.
Definition Sema.h:3633
Records and restores the CurFPFeatures state on entry/exit of compound statements.
Definition Sema.h:14313
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition Sema.h:5671
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:5713
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:9463
CXXMethodDecl * getMethod() const
Definition Sema.h:9475
RAII object to handle the state changes required to synthesize a function body.
Definition Sema.h:13776
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7874
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:862
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:13294
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2721
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:6691
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
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.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9501
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9528
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9536
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9524
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9509
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:419
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:13913
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:1558
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6481
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:1285
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:6664
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:6645
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:1498
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:7995
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:1717
@ AR_accessible
Definition Sema.h:1715
@ AR_inaccessible
Definition Sema.h:1716
@ AR_delayed
Definition Sema.h:1718
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2493
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.
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2105
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:4314
@ Default
= default ;
Definition Sema.h:4316
@ Delete
deleted-function-body
Definition Sema.h:4322
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:2106
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:1331
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:229
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:931
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:1543
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.
void CleanupVarDeclMarking()
ASTContext & getASTContext() const
Definition Sema.h:934
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6671
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:6755
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:774
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...
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:6686
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:1235
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:12378
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1798
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8518
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2512
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:929
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:278
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
void DiagnoseUnsatisfiedRequiresExpr(const RequiresExpr *RequiresExpr, bool First=true)
@ UPPC_RequiresClause
Definition Sema.h:14730
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14685
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14703
@ UPPC_Initializer
An initializer.
Definition Sema.h:14694
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14664
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14688
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14697
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14667
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14670
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14676
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:927
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:6073
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:2624
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:1330
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)
bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor, bool IsCopy=false)
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:1329
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:6649
SemaHLSL & HLSL()
Definition Sema.h:1508
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:6079
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition Sema.h:5447
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5454
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6642
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:6747
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6679
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.
bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc)
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:13306
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:6069
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:649
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:15804
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:10029
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:7124
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6656
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1471
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:6675
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:8337
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:14213
SourceManager & getSourceManager() const
Definition Sema.h:932
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,...
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:6189
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
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:15759
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
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:6667
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:1609
ASTConsumer & Consumer
Definition Sema.h:1332
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:4829
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:128
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1371
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:6877
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6887
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6856
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:1290
bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc, ArrayRef< TemplateParameterList * > TPLs, bool IsInstantiation)
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:1334
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)
ExprResult BuildCXXCtorDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
DiagnosticsEngine & Diags
Definition Sema.h:1333
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7944
FPOptions CurFPFeatures
Definition Sema.h:1327
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:6651
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)
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
friend class InitializationSequence
Definition Sema.h:1613
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:6683
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:339
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:6480
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:6426
@ AbstractVariableType
Definition Sema.h:6430
@ AbstractReturnType
Definition Sema.h:6428
@ AbstractNone
Definition Sema.h:6427
@ AbstractFieldType
Definition Sema.h:6431
@ AbstractArrayType
Definition Sema.h:6434
@ AbstractParamType
Definition Sema.h:6429
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:8522
llvm::DenseMap< SpecialMemberCacheKey, SpecialMemberOverloadResult > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:9487
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId)
Handle a friend tag declaration where the scope specifier was templated.
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
CheckConstexprKind
Definition Sema.h:6562
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6567
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6564
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:457
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:3626
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
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)
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:669
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8817
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:3680
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1504
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:1844
bool isUnevaluated() const
Definition Expr.h:1982
StringRef getString() const
Definition Expr.h:1912
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3868
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3989
StringRef getKindName() const
Definition Decl.h:4064
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3969
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4996
bool isUnion() const
Definition Decl.h:4079
TagKind getTagKind() const
Definition Decl.h:4068
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:4014
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:1948
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:107
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3839
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5914
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3858
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:3664
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
NestedNameSpecifierLoc getPrefix() const
If this type represents a qualified-id, this returns it's nested name specifier.
Definition TypeLoc.cpp:478
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1468
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:2766
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8549
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:8560
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9200
bool isBooleanType() const
Definition TypeBase.h:9341
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:2092
bool isIncompleteArrayType() const
Definition TypeBase.h:8922
bool isUndeducedAutoType() const
Definition TypeBase.h:9011
bool isRValueReferenceType() const
Definition TypeBase.h:8847
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:8914
bool isPointerType() const
Definition TypeBase.h:8815
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
bool isEnumeralType() const
Definition TypeBase.h:8946
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
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:8843
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9169
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3200
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9384
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9354
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2881
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9347
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isFunctionType() const
Definition TypeBase.h:8811
bool isStructureOrClassType() const
Definition Type.cpp:839
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2533
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
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:2460
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
bool isRecordType() const
Definition TypeBase.h:8942
bool isUnionType() const
Definition Type.cpp:851
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3713
QualType getUnderlyingType() const
Definition Decl.h:3768
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:2354
Opcode getOpcode() const
Definition Expr.h:2349
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2409
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:5201
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:283
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1110
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1322
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1319
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1154
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1168
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1157
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1138
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1192
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1162
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:464
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:4148
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition DeclCXX.cpp:3659
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:3638
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3610
Represents a C++ using-declaration.
Definition DeclCXX.h:3621
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3670
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition DeclCXX.h:3658
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3662
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition DeclCXX.cpp:3547
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition DeclCXX.h:3648
Represents C++ using-directive.
Definition DeclCXX.h:3126
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition DeclCXX.cpp:3330
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3822
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition DeclCXX.cpp:3568
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition DeclCXX.cpp:3590
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3429
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition DeclCXX.h:3465
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3493
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:3487
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
void setType(QualType newType)
Definition Decl.h:726
QualType getType() const
Definition Decl.h:725
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5690
Represents a variable declaration or definition.
Definition Decl.h:934
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2802
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2132
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1606
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2256
bool evaluateConstantDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes, SemaProxy &SProxy) const
Evaluate the destruction of a variable that is required by the language to have constant destruction.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2171
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2828
void setCXXCondDecl()
Definition Decl.h:1652
bool isInlineSpecified() const
Definition Decl.h:1591
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1308
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1249
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1216
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2843
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1185
const Expr * getInit() const
Definition Decl.h:1393
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2568
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:960
void setInit(Expr *I)
Definition Decl.cpp:2470
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1176
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:2521
void setExceptionVariable(bool EV)
Definition Decl.h:1534
Declaration of a variable template.
Represents a GCC generic vector type.
Definition TypeBase.h:4398
unsigned getNumElements() const
Definition TypeBase.h:4413
QualType getElementType() const
Definition TypeBase.h:4412
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2888
SourceLocation getOverrideLoc() const
Definition DeclSpec.h:2908
SourceLocation getLastLocation() const
Definition DeclSpec.h:2920
bool isOverrideSpecified() const
Definition DeclSpec.h:2907
SourceLocation getFinalLoc() const
Definition DeclSpec.h:2912
bool isFinalSpecified() const
Definition DeclSpec.h:2910
bool isFinalSpelledSealed() const
Definition DeclSpec.h:2911
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)
1) Pops the value from the stack.
Definition Interp.h:1176
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:960
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.
Top level wrappers for InstallAPI frontend operations.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
@ 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:827
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:823
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:819
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:216
@ 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:506
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition DeclCXX.h:3037
@ 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:660
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:275
@ ICIS_ListInit
Direct list-initialization.
Definition Specifiers.h:278
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:276
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1801
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
@ 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:1545
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:626
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:242
@ 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:1106
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1104
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1102
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1098
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1096
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1094
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1088
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1100
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1090
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1092
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:127
@ AS_public
Definition Specifiers.h:128
@ AS_protected
Definition Specifiers.h:129
@ AS_none
Definition Specifiers.h:131
@ AS_private
Definition Specifiers.h:130
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:252
@ SC_Static
Definition Specifiers.h:256
@ SC_None
Definition Specifiers.h:254
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
@ 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:906
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
const FunctionProtoType * T
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:6171
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6176
@ Struct
The "struct" keyword.
Definition TypeBase.h:6173
@ Class
The "class" keyword.
Definition TypeBase.h:6182
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:555
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Decl.h:2042
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Decl.h:2056
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Decl.h:2053
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Decl.h:2050
@ None
This is not a defaultable comparison operator.
Definition Decl.h:2044
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Decl.h:2047
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:4455
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4469
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4464
AllowFoldKind
Definition Sema.h:648
@ 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.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2031
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:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
TypeAwareAllocationMode
Definition ExprCXX.h:2256
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1306
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TrivialABIHandling
Definition Sema.h:638
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:643
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:640
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:383
@ Success
Template argument deduction was successful.
Definition Sema.h:375
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:389
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:192
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:210
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:206
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
TypeAwareAllocationMode typeAwareAllocationModeFromBool(bool IsTypeAwareAllocation)
Definition ExprCXX.h:2263
U cast(CodeGen::Address addr)
Definition Address.h:327
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:842
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:840
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:838
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:6146
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6167
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6160
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:181
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
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:1456
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1516
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1465
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1519
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1617
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1491
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition DeclSpec.h:1646
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1649
void freeParams()
Reset the parameter list to having zero parameters.
Definition DeclSpec.h:1555
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1642
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition DeclSpec.h:1431
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/unaligned/atomic.
Definition DeclSpec.h:1354
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1330
SourceRange getSourceRange() const
Definition DeclSpec.h:1342
FunctionTypeInfo Fun
Definition DeclSpec.h:1730
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
PointerTypeInfo Ptr
Definition DeclSpec.h:1727
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
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:5605
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5617
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5607
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5610
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5613
Extra information about a function prototype.
Definition TypeBase.h:5633
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:6210
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3518
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3500
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:13345
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13476
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13436
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13433
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13389
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13407
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13479
Abstract class used to diagnose incomplete types.
Definition Sema.h:8414
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.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
OpaquePtr< T > get() const
Definition Ownership.h:105