clang 23.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
28#include "clang/AST/TypeLoc.h"
37#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/Lookup.h"
43#include "clang/Sema/Scope.h"
45#include "clang/Sema/SemaCUDA.h"
47#include "clang/Sema/SemaObjC.h"
49#include "clang/Sema/Template.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/Support/ConvertUTF.h"
55#include "llvm/Support/SaveAndRestore.h"
56#include <map>
57#include <optional>
58#include <set>
59
60using namespace clang;
61
62//===----------------------------------------------------------------------===//
63// CheckDefaultArgumentVisitor
64//===----------------------------------------------------------------------===//
65
66namespace {
67/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
68/// the default argument of a parameter to determine whether it
69/// contains any ill-formed subexpressions. For example, this will
70/// diagnose the use of local variables or parameters within the
71/// default argument expression.
72class CheckDefaultArgumentVisitor
73 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
74 Sema &S;
75 const Expr *DefaultArg;
76
77public:
78 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
79 : S(S), DefaultArg(DefaultArg) {}
80
81 bool VisitExpr(const Expr *Node);
82 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
83 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
84 bool VisitLambdaExpr(const LambdaExpr *Lambda);
85 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
86};
87
88/// VisitExpr - Visit all of the children of this expression.
89bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
90 bool IsInvalid = false;
91 for (const Stmt *SubStmt : Node->children())
92 if (SubStmt)
93 IsInvalid |= Visit(SubStmt);
94 return IsInvalid;
95}
96
97/// VisitDeclRefExpr - Visit a reference to a declaration, to
98/// determine whether this declaration can be used in the default
99/// argument expression.
100bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
101 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
102
103 if (!isa<VarDecl, BindingDecl>(Decl))
104 return false;
105
106 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
107 // C++ [dcl.fct.default]p9:
108 // [...] parameters of a function shall not be used in default
109 // argument expressions, even if they are not evaluated. [...]
110 //
111 // C++17 [dcl.fct.default]p9 (by CWG 2082):
112 // [...] A parameter shall not appear as a potentially-evaluated
113 // expression in a default argument. [...]
114 //
115 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
116 return S.Diag(DRE->getBeginLoc(),
117 diag::err_param_default_argument_references_param)
118 << Param->getDeclName() << DefaultArg->getSourceRange();
119 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
120 // C++ [dcl.fct.default]p7:
121 // Local variables shall not be used in default argument
122 // expressions.
123 //
124 // C++17 [dcl.fct.default]p7 (by CWG 2082):
125 // A local variable shall not appear as a potentially-evaluated
126 // expression in a default argument.
127 //
128 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
129 // Note: A local variable cannot be odr-used (6.3) in a default
130 // argument.
131 //
132 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
133 return S.Diag(DRE->getBeginLoc(),
134 diag::err_param_default_argument_references_local)
135 << Decl << DefaultArg->getSourceRange();
136 }
137 return false;
138}
139
140/// VisitCXXThisExpr - Visit a C++ "this" expression.
141bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
142 // C++ [dcl.fct.default]p8:
143 // The keyword this shall not be used in a default argument of a
144 // member function.
145 return S.Diag(ThisE->getBeginLoc(),
146 diag::err_param_default_argument_references_this)
147 << ThisE->getSourceRange();
148}
149
150bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
151 const PseudoObjectExpr *POE) {
152 bool Invalid = false;
153 for (const Expr *E : POE->semantics()) {
154 // Look through bindings.
155 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
156 E = OVE->getSourceExpr();
157 assert(E && "pseudo-object binding without source expression?");
158 }
159
160 Invalid |= Visit(E);
161 }
162 return Invalid;
163}
164
165bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
166 // [expr.prim.lambda.capture]p9
167 // a lambda-expression appearing in a default argument cannot implicitly or
168 // explicitly capture any local entity. Such a lambda-expression can still
169 // have an init-capture if any full-expression in its initializer satisfies
170 // the constraints of an expression appearing in a default argument.
171 bool Invalid = false;
172 for (const LambdaCapture &LC : Lambda->captures()) {
173 if (!Lambda->isInitCapture(&LC))
174 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
175 // Init captures are always VarDecl.
176 auto *D = cast<VarDecl>(LC.getCapturedVar());
177 Invalid |= Visit(D->getInit());
178 }
179 return Invalid;
180}
181} // namespace
182
183void
185 const CXXMethodDecl *Method) {
186 // If we have an MSAny spec already, don't bother.
187 if (!Method || ComputedEST == EST_MSAny)
188 return;
189
190 const FunctionProtoType *Proto
191 = Method->getType()->getAs<FunctionProtoType>();
192 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
193 if (!Proto)
194 return;
195
197
198 // If we have a throw-all spec at this point, ignore the function.
199 if (ComputedEST == EST_None)
200 return;
201
202 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
203 EST = EST_BasicNoexcept;
204
205 switch (EST) {
206 case EST_Unparsed:
208 case EST_Unevaluated:
209 llvm_unreachable("should not see unresolved exception specs here");
210
211 // If this function can throw any exceptions, make a note of that.
212 case EST_MSAny:
213 case EST_None:
214 // FIXME: Whichever we see last of MSAny and None determines our result.
215 // We should make a consistent, order-independent choice here.
216 ClearExceptions();
217 ComputedEST = EST;
218 return;
220 ClearExceptions();
221 ComputedEST = EST_None;
222 return;
223 // FIXME: If the call to this decl is using any of its default arguments, we
224 // need to search them for potentially-throwing calls.
225 // If this function has a basic noexcept, it doesn't affect the outcome.
227 case EST_NoexceptTrue:
228 case EST_NoThrow:
229 return;
230 // If we're still at noexcept(true) and there's a throw() callee,
231 // change to that specification.
232 case EST_DynamicNone:
233 if (ComputedEST == EST_BasicNoexcept)
234 ComputedEST = EST_DynamicNone;
235 return;
237 llvm_unreachable(
238 "should not generate implicit declarations for dependent cases");
239 case EST_Dynamic:
240 break;
241 }
242 assert(EST == EST_Dynamic && "EST case not considered earlier.");
243 assert(ComputedEST != EST_None &&
244 "Shouldn't collect exceptions when throw-all is guaranteed.");
245 ComputedEST = EST_Dynamic;
246 // Record the exceptions in this function's exception specification.
247 for (const auto &E : Proto->exceptions())
248 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
249 Exceptions.push_back(E);
250}
251
253 if (!S || ComputedEST == EST_MSAny)
254 return;
255
256 // FIXME:
257 //
258 // C++0x [except.spec]p14:
259 // [An] implicit exception-specification specifies the type-id T if and
260 // only if T is allowed by the exception-specification of a function directly
261 // invoked by f's implicit definition; f shall allow all exceptions if any
262 // function it directly invokes allows all exceptions, and f shall allow no
263 // exceptions if every function it directly invokes allows no exceptions.
264 //
265 // Note in particular that if an implicit exception-specification is generated
266 // for a function containing a throw-expression, that specification can still
267 // be noexcept(true).
268 //
269 // Note also that 'directly invoked' is not defined in the standard, and there
270 // is no indication that we should only consider potentially-evaluated calls.
271 //
272 // Ultimately we should implement the intent of the standard: the exception
273 // specification should be the set of exceptions which can be thrown by the
274 // implicit definition. For now, we assume that any non-nothrow expression can
275 // throw any exception.
276
277 if (Self->canThrow(S))
278 ComputedEST = EST_None;
279}
280
282 SourceLocation EqualLoc) {
283 if (RequireCompleteType(Param->getLocation(), Param->getType(),
284 diag::err_typecheck_decl_incomplete_type))
285 return true;
286
287 // C++ [dcl.fct.default]p5
288 // A default argument expression is implicitly converted (clause
289 // 4) to the parameter type. The default argument expression has
290 // the same semantic constraints as the initializer expression in
291 // a declaration of a variable of the parameter type, using the
292 // copy-initialization semantics (8.5).
294 Param);
295 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
296 EqualLoc);
297 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
298 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
299 if (Result.isInvalid())
300 return true;
301 Arg = Result.getAs<Expr>();
302
303 CheckCompletedExpr(Arg, EqualLoc);
305
306 return Arg;
307}
308
310 SourceLocation EqualLoc) {
311 // Add the default argument to the parameter
312 Param->setDefaultArg(Arg);
313
314 // We have already instantiated this parameter; provide each of the
315 // instantiations with the uninstantiated default argument.
316 UnparsedDefaultArgInstantiationsMap::iterator InstPos
318 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
319 for (auto &Instantiation : InstPos->second)
320 Instantiation->setUninstantiatedDefaultArg(Arg);
321
322 // We're done tracking this parameter's instantiations.
324 }
325}
326
327void
329 Expr *DefaultArg) {
330 if (!param || !DefaultArg)
331 return;
332
333 ParmVarDecl *Param = cast<ParmVarDecl>(param);
334 UnparsedDefaultArgLocs.erase(Param);
335
336 // Default arguments are only permitted in C++
337 if (!getLangOpts().CPlusPlus) {
338 Diag(EqualLoc, diag::err_param_default_argument)
339 << DefaultArg->getSourceRange();
340 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
341 }
342
343 // Check for unexpanded parameter packs.
345 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
346
347 // C++11 [dcl.fct.default]p3
348 // A default argument expression [...] shall not be specified for a
349 // parameter pack.
350 if (Param->isParameterPack()) {
351 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
352 << DefaultArg->getSourceRange();
353 // Recover by discarding the default argument.
354 Param->setDefaultArg(nullptr);
355 return;
356 }
357
358 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
359 if (Result.isInvalid())
360 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
361
362 DefaultArg = Result.getAs<Expr>();
363
364 // Check that the default argument is well-formed
365 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
366 if (DefaultArgChecker.Visit(DefaultArg))
367 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
368
369 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
370}
371
373 SourceLocation EqualLoc,
374 SourceLocation ArgLoc) {
375 if (!param)
376 return;
377
378 ParmVarDecl *Param = cast<ParmVarDecl>(param);
379 Param->setUnparsedDefaultArg();
380 UnparsedDefaultArgLocs[Param] = ArgLoc;
381}
382
384 Expr *DefaultArg) {
385 if (!param)
386 return;
387
388 ParmVarDecl *Param = cast<ParmVarDecl>(param);
389 Param->setInvalidDecl();
390 UnparsedDefaultArgLocs.erase(Param);
391 ExprResult RE;
392 if (DefaultArg) {
393 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
394 Param->getType().getNonReferenceType());
395 } else {
396 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
397 Param->getType().getNonReferenceType());
398 }
399 Param->setDefaultArg(RE.get());
400}
401
403 // C++ [dcl.fct.default]p3
404 // A default argument expression shall be specified only in the
405 // parameter-declaration-clause of a function declaration or in a
406 // template-parameter (14.1). It shall not be specified for a
407 // parameter pack. If it is specified in a
408 // parameter-declaration-clause, it shall not occur within a
409 // declarator or abstract-declarator of a parameter-declaration.
410 bool MightBeFunction = D.isFunctionDeclarationContext();
411 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
412 DeclaratorChunk &chunk = D.getTypeObject(i);
413 if (chunk.Kind == DeclaratorChunk::Function) {
414 if (MightBeFunction) {
415 // This is a function declaration. It can have default arguments, but
416 // keep looking in case its return type is a function type with default
417 // arguments.
418 MightBeFunction = false;
419 continue;
420 }
421 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
422 ++argIdx) {
423 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
424 if (Param->hasUnparsedDefaultArg()) {
425 std::unique_ptr<CachedTokens> Toks =
426 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
427 SourceRange SR;
428 if (Toks->size() > 1)
429 SR = SourceRange((*Toks)[1].getLocation(),
430 Toks->back().getLocation());
431 else
432 SR = UnparsedDefaultArgLocs[Param];
433 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
434 << SR;
435 } else if (Param->getDefaultArg()) {
436 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
437 << Param->getDefaultArg()->getSourceRange();
438 Param->setDefaultArg(nullptr);
439 }
440 }
441 } else if (chunk.Kind != DeclaratorChunk::Paren) {
442 MightBeFunction = false;
443 }
444 }
445}
446
448 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
449 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
450 });
451}
452
454 Scope *S) {
455 bool Invalid = false;
456
457 // The declaration context corresponding to the scope is the semantic
458 // parent, unless this is a local function declaration, in which case
459 // it is that surrounding function.
460 DeclContext *ScopeDC = New->isLocalExternDecl()
461 ? New->getLexicalDeclContext()
462 : New->getDeclContext();
463
464 // Find the previous declaration for the purpose of default arguments.
465 FunctionDecl *PrevForDefaultArgs = Old;
466 for (/**/; PrevForDefaultArgs;
467 // Don't bother looking back past the latest decl if this is a local
468 // extern declaration; nothing else could work.
469 PrevForDefaultArgs = New->isLocalExternDecl()
470 ? nullptr
471 : PrevForDefaultArgs->getPreviousDecl()) {
472 // Ignore hidden declarations.
473 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
474 continue;
475
476 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
477 !New->isCXXClassMember()) {
478 // Ignore default arguments of old decl if they are not in
479 // the same scope and this is not an out-of-line definition of
480 // a member function.
481 continue;
482 }
483
484 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
485 // If only one of these is a local function declaration, then they are
486 // declared in different scopes, even though isDeclInScope may think
487 // they're in the same scope. (If both are local, the scope check is
488 // sufficient, and if neither is local, then they are in the same scope.)
489 continue;
490 }
491
492 // We found the right previous declaration.
493 break;
494 }
495
496 // C++ [dcl.fct.default]p4:
497 // For non-template functions, default arguments can be added in
498 // later declarations of a function in the same
499 // scope. Declarations in different scopes have completely
500 // distinct sets of default arguments. That is, declarations in
501 // inner scopes do not acquire default arguments from
502 // declarations in outer scopes, and vice versa. In a given
503 // function declaration, all parameters subsequent to a
504 // parameter with a default argument shall have default
505 // arguments supplied in this or previous declarations. A
506 // default argument shall not be redefined by a later
507 // declaration (not even to the same value).
508 //
509 // C++ [dcl.fct.default]p6:
510 // Except for member functions of class templates, the default arguments
511 // in a member function definition that appears outside of the class
512 // definition are added to the set of default arguments provided by the
513 // member function declaration in the class definition.
514 for (unsigned p = 0, NumParams = PrevForDefaultArgs
515 ? PrevForDefaultArgs->getNumParams()
516 : 0;
517 p < NumParams; ++p) {
518 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
519 ParmVarDecl *NewParam = New->getParamDecl(p);
520
521 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
522 bool NewParamHasDfl = NewParam->hasDefaultArg();
523
524 if (OldParamHasDfl && NewParamHasDfl) {
525 unsigned DiagDefaultParamID =
526 diag::err_param_default_argument_redefinition;
527
528 // MSVC accepts that default parameters be redefined for member functions
529 // of template class. The new default parameter's value is ignored.
530 Invalid = true;
531 if (getLangOpts().MicrosoftExt) {
532 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
533 if (MD && MD->getParent()->getDescribedClassTemplate()) {
534 // Merge the old default argument into the new parameter.
535 NewParam->setHasInheritedDefaultArg();
536 if (OldParam->hasUninstantiatedDefaultArg())
538 OldParam->getUninstantiatedDefaultArg());
539 else
540 NewParam->setDefaultArg(OldParam->getInit());
541 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
542 Invalid = false;
543 }
544 }
545
546 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
547 // hint here. Alternatively, we could walk the type-source information
548 // for NewParam to find the last source location in the type... but it
549 // isn't worth the effort right now. This is the kind of test case that
550 // is hard to get right:
551 // int f(int);
552 // void g(int (*fp)(int) = f);
553 // void g(int (*fp)(int) = &f);
554 Diag(NewParam->getLocation(), DiagDefaultParamID)
555 << NewParam->getDefaultArgRange();
556
557 // Look for the function declaration where the default argument was
558 // actually written, which may be a declaration prior to Old.
559 for (auto Older = PrevForDefaultArgs;
560 OldParam->hasInheritedDefaultArg(); /**/) {
561 Older = Older->getPreviousDecl();
562 OldParam = Older->getParamDecl(p);
563 }
564
565 Diag(OldParam->getLocation(), diag::note_previous_definition)
566 << OldParam->getDefaultArgRange();
567 } else if (OldParamHasDfl) {
568 // Merge the old default argument into the new parameter unless the new
569 // function is a friend declaration in a template class. In the latter
570 // case the default arguments will be inherited when the friend
571 // declaration will be instantiated.
572 if (New->getFriendObjectKind() == Decl::FOK_None ||
573 !New->getLexicalDeclContext()->isDependentContext()) {
574 // It's important to use getInit() here; getDefaultArg()
575 // strips off any top-level ExprWithCleanups.
576 NewParam->setHasInheritedDefaultArg();
577 if (OldParam->hasUnparsedDefaultArg())
578 NewParam->setUnparsedDefaultArg();
579 else if (OldParam->hasUninstantiatedDefaultArg())
581 OldParam->getUninstantiatedDefaultArg());
582 else
583 NewParam->setDefaultArg(OldParam->getInit());
584 }
585 } else if (NewParamHasDfl) {
586 if (New->getDescribedFunctionTemplate()) {
587 // Paragraph 4, quoted above, only applies to non-template functions.
588 Diag(NewParam->getLocation(),
589 diag::err_param_default_argument_template_redecl)
590 << NewParam->getDefaultArgRange();
591 Diag(PrevForDefaultArgs->getLocation(),
592 diag::note_template_prev_declaration)
593 << false;
594 } else if (New->getTemplateSpecializationKind()
596 New->getTemplateSpecializationKind() != TSK_Undeclared) {
597 // C++ [temp.expr.spec]p21:
598 // Default function arguments shall not be specified in a declaration
599 // or a definition for one of the following explicit specializations:
600 // - the explicit specialization of a function template;
601 // - the explicit specialization of a member function template;
602 // - the explicit specialization of a member function of a class
603 // template where the class template specialization to which the
604 // member function specialization belongs is implicitly
605 // instantiated.
606 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
607 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
608 << New->getDeclName()
609 << NewParam->getDefaultArgRange();
610 } else if (New->getDeclContext()->isDependentContext()) {
611 // C++ [dcl.fct.default]p6 (DR217):
612 // Default arguments for a member function of a class template shall
613 // be specified on the initial declaration of the member function
614 // within the class template.
615 //
616 // Reading the tea leaves a bit in DR217 and its reference to DR205
617 // leads me to the conclusion that one cannot add default function
618 // arguments for an out-of-line definition of a member function of a
619 // dependent type.
620 int WhichKind = 2;
622 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
623 if (Record->getDescribedClassTemplate())
624 WhichKind = 0;
626 WhichKind = 1;
627 else
628 WhichKind = 2;
629 }
630
631 Diag(NewParam->getLocation(),
632 diag::err_param_default_argument_member_template_redecl)
633 << WhichKind
634 << NewParam->getDefaultArgRange();
635 }
636 }
637 }
638
639 // DR1344: If a default argument is added outside a class definition and that
640 // default argument makes the function a special member function, the program
641 // is ill-formed. This can only happen for constructors.
643 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
646 if (NewSM != OldSM) {
647 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
648 assert(NewParam->hasDefaultArg());
649 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
650 << NewParam->getDefaultArgRange() << NewSM;
651 Diag(Old->getLocation(), diag::note_previous_declaration);
652 }
653 }
654
655 const FunctionDecl *Def;
656 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
657 // template has a constexpr specifier then all its declarations shall
658 // contain the constexpr specifier.
659 if (New->getConstexprKind() != Old->getConstexprKind()) {
660 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
661 << New << static_cast<int>(New->getConstexprKind())
662 << static_cast<int>(Old->getConstexprKind());
663 Diag(Old->getLocation(), diag::note_previous_declaration);
664 Invalid = true;
665 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
666 Old->isDefined(Def) &&
667 // If a friend function is inlined but does not have 'inline'
668 // specifier, it is a definition. Do not report attribute conflict
669 // in this case, redefinition will be diagnosed later.
670 (New->isInlineSpecified() ||
671 New->getFriendObjectKind() == Decl::FOK_None)) {
672 // C++11 [dcl.fcn.spec]p4:
673 // If the definition of a function appears in a translation unit before its
674 // first declaration as inline, the program is ill-formed.
675 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
676 Diag(Def->getLocation(), diag::note_previous_definition);
677 Invalid = true;
678 }
679
680 // C++17 [temp.deduct.guide]p3:
681 // Two deduction guide declarations in the same translation unit
682 // for the same class template shall not have equivalent
683 // parameter-declaration-clauses.
685 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
686 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
687 Diag(Old->getLocation(), diag::note_previous_declaration);
688 }
689
690 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
691 // argument expression, that declaration shall be a definition and shall be
692 // the only declaration of the function or function template in the
693 // translation unit.
696 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
697 Diag(Old->getLocation(), diag::note_previous_declaration);
698 Invalid = true;
699 }
700
701 // C++11 [temp.friend]p4 (DR329):
702 // When a function is defined in a friend function declaration in a class
703 // template, the function is instantiated when the function is odr-used.
704 // The same restrictions on multiple declarations and definitions that
705 // apply to non-template function declarations and definitions also apply
706 // to these implicit definitions.
707 const FunctionDecl *OldDefinition = nullptr;
708 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
709 Old->isDefined(OldDefinition, true))
710 CheckForFunctionRedefinition(New, OldDefinition);
711
712 return Invalid;
713}
714
717 ? diag::warn_cxx23_placeholder_var_definition
718 : diag::ext_placeholder_var_definition);
719}
720
721NamedDecl *
723 MultiTemplateParamsArg TemplateParamLists) {
724 assert(D.isDecompositionDeclarator());
726
727 // The syntax only allows a decomposition declarator as a simple-declaration,
728 // a for-range-declaration, or a condition in Clang, but we parse it in more
729 // cases than that.
731 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
732 << Decomp.getSourceRange();
733 return nullptr;
734 }
735
736 if (!TemplateParamLists.empty()) {
737 // C++17 [temp]/1:
738 // A template defines a family of class, functions, or variables, or an
739 // alias for a family of types.
740 //
741 // Structured bindings are not included.
742 Diag(TemplateParamLists.front()->getTemplateLoc(),
743 diag::err_decomp_decl_template);
744 return nullptr;
745 }
746
747 unsigned DiagID;
749 DiagID = diag::compat_pre_cxx17_decomp_decl;
751 DiagID = getLangOpts().CPlusPlus26
752 ? diag::compat_cxx26_decomp_decl_cond
753 : diag::compat_pre_cxx26_decomp_decl_cond;
754 else
755 DiagID = diag::compat_cxx17_decomp_decl;
756
757 Diag(Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
758
759 // The semantic context is always just the current context.
760 DeclContext *const DC = CurContext;
761
762 // C++17 [dcl.dcl]/8:
763 // The decl-specifier-seq shall contain only the type-specifier auto
764 // and cv-qualifiers.
765 // C++20 [dcl.dcl]/8:
766 // If decl-specifier-seq contains any decl-specifier other than static,
767 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
768 // C++23 [dcl.pre]/6:
769 // Each decl-specifier in the decl-specifier-seq shall be static,
770 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
771 // C++23 [dcl.pre]/7:
772 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
773 // constinit, static, thread_local, auto, or a cv-qualifier
774 auto &DS = D.getDeclSpec();
775 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
776 Diag(Loc, diag::err_decomp_decl_spec) << Name;
777 };
778
779 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
780 DiagCompat(Loc, diag_compat::decomp_decl_spec) << Name;
781 };
782
783 if (auto SCS = DS.getStorageClassSpec()) {
784 if (SCS == DeclSpec::SCS_static)
785 DiagCpp20Specifier(DeclSpec::getSpecifierName(SCS),
786 DS.getStorageClassSpecLoc());
787 else
788 DiagBadSpecifier(DeclSpec::getSpecifierName(SCS),
789 DS.getStorageClassSpecLoc());
790 }
791 if (auto TSCS = DS.getThreadStorageClassSpec())
792 DiagCpp20Specifier(DeclSpec::getSpecifierName(TSCS),
793 DS.getThreadStorageClassSpecLoc());
794
795 if (DS.isInlineSpecified())
796 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
797
798 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
799 ConstexprSpec != ConstexprSpecKind::Unspecified) {
800 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
802 DiagBadSpecifier(DeclSpec::getSpecifierName(ConstexprSpec),
803 DS.getConstexprSpecLoc());
804 }
805
806 // We can't recover from it being declared as a typedef.
807 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
808 return nullptr;
809
810 // C++2a [dcl.struct.bind]p1:
811 // A cv that includes volatile is deprecated
812 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
814 Diag(DS.getVolatileSpecLoc(),
815 diag::warn_deprecated_volatile_structured_binding);
816
818 QualType R = TInfo->getType();
819
822 D.setInvalidType();
823
824 // The syntax only allows a single ref-qualifier prior to the decomposition
825 // declarator. No other declarator chunks are permitted. Also check the type
826 // specifier here.
827 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
828 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
829 (D.getNumTypeObjects() == 1 &&
831 Diag(Decomp.getLSquareLoc(),
832 (D.hasGroupingParens() ||
833 (D.getNumTypeObjects() &&
835 ? diag::err_decomp_decl_parens
836 : diag::err_decomp_decl_type)
837 << R;
838
839 // In most cases, there's no actual problem with an explicitly-specified
840 // type, but a function type won't work here, and ActOnVariableDeclarator
841 // shouldn't be called for such a type.
842 if (R->isFunctionType())
843 D.setInvalidType();
844 }
845
846 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
847 if (DS.isConstrainedAuto()) {
848 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
849 assert(TemplRep->Kind == TNK_Concept_template &&
850 "No other template kind should be possible for a constrained auto");
851
852 SourceRange TemplRange{TemplRep->TemplateNameLoc,
853 TemplRep->RAngleLoc.isValid()
854 ? TemplRep->RAngleLoc
855 : TemplRep->TemplateNameLoc};
856 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
857 << TemplRange << FixItHint::CreateRemoval(TemplRange);
858 }
859
860 // Build the BindingDecls.
862
863 // Build the BindingDecls.
864 for (auto &B : D.getDecompositionDeclarator().bindings()) {
865 // Check for name conflicts.
866 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
867 IdentifierInfo *VarName = B.Name;
868 assert(VarName && "Cannot have an unnamed binding declaration");
869
873 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
874
875 // It's not permitted to shadow a template parameter name.
876 if (Previous.isSingleResult() &&
877 Previous.getFoundDecl()->isTemplateParameter()) {
878 DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());
879 Previous.clear();
880 }
881
882 QualType QT;
883 if (B.EllipsisLoc.isValid()) {
884 if (!cast<Decl>(DC)->isTemplated())
885 Diag(B.EllipsisLoc, diag::err_pack_outside_template);
886 QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,
887 /*ExpectsPackInType=*/false);
888 }
889
890 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);
891
892 ProcessDeclAttributeList(S, BD, *B.Attrs);
893
894 // Find the shadowed declaration before filtering for scope.
895 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
897 : nullptr;
898
899 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
900 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
901 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
902 /*AllowInlineNamespace*/false);
903
904 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
905 DC->isFunctionOrMethod() && VarName->isPlaceholder();
906 if (!Previous.empty()) {
907 if (IsPlaceholder) {
908 bool sameDC = (Previous.end() - 1)
909 ->getDeclContext()
910 ->getRedeclContext()
911 ->Equals(DC->getRedeclContext());
912 if (sameDC &&
913 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
914 Previous.clear();
916 }
917 } else {
918 auto *Old = Previous.getRepresentativeDecl();
919 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
920 Diag(Old->getLocation(), diag::note_previous_definition);
921 }
922 } else if (ShadowedDecl && !D.isRedeclaration()) {
923 CheckShadow(BD, ShadowedDecl, Previous);
924 }
925 PushOnScopeChains(BD, S, true);
926 Bindings.push_back(BD);
927 ParsingInitForAutoVars.insert(BD);
928 }
929
930 // There are no prior lookup results for the variable itself, because it
931 // is unnamed.
932 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
933 Decomp.getLSquareLoc());
936
937 // Build the variable that holds the non-decomposed object.
938 bool AddToScope = true;
939 NamedDecl *New =
940 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
941 MultiTemplateParamsArg(), AddToScope, Bindings);
942 if (AddToScope) {
943 S->AddDecl(New);
944 CurContext->addHiddenDecl(New);
945 }
946
947 if (OpenMP().isInOpenMPDeclareTargetContext())
948 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
949
950 return New;
951}
952
953// Check the arity of the structured bindings.
954// Create the resolved pack expr if needed.
956 QualType DecompType,
958 unsigned MemberCount) {
959 auto BindingWithPackItr = llvm::find_if(
960 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });
961 bool HasPack = BindingWithPackItr != Bindings.end();
962 bool IsValid;
963 if (!HasPack) {
964 IsValid = Bindings.size() == MemberCount;
965 } else {
966 // There may not be more members than non-pack bindings.
967 IsValid = MemberCount >= Bindings.size() - 1;
968 }
969
970 if (IsValid && HasPack) {
971 // Create the pack expr and assign it to the binding.
972 unsigned PackSize = MemberCount - Bindings.size() + 1;
973
974 BindingDecl *BPack = *BindingWithPackItr;
975 BPack->setDecomposedDecl(DD);
976 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
977 // Create the nested BindingDecls.
978 for (unsigned I = 0; I < PackSize; ++I) {
980 S.Context, BPack->getDeclContext(), BPack->getLocation(),
981 BPack->getIdentifier(), QualType());
982 NestedBD->setDecomposedDecl(DD);
983 NestedBDs[I] = NestedBD;
984 }
985
987 S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);
988 auto *PackExpr = FunctionParmPackExpr::Create(
989 S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);
990 BPack->setBinding(PackType, PackExpr);
991 }
992
993 if (IsValid)
994 return false;
995
996 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
997 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
998 << (MemberCount < Bindings.size());
999 return true;
1000}
1001
1004 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1005 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1006 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1007 auto *DD = cast<DecompositionDecl>(Src);
1008
1009 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1010 return true;
1011
1012 unsigned I = 0;
1013 for (auto *B : DD->flat_bindings()) {
1014 SourceLocation Loc = B->getLocation();
1015 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1016 if (E.isInvalid())
1017 return true;
1018 E = GetInit(Loc, E.get(), I++);
1019 if (E.isInvalid())
1020 return true;
1021 B->setBinding(ElemType, E.get());
1022 }
1023
1024 return false;
1025}
1026
1029 ValueDecl *Src, QualType DecompType,
1030 const llvm::APSInt &NumElems,
1031 QualType ElemType) {
1033 S, Bindings, Src, DecompType, NumElems, ElemType,
1034 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1035 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1036 if (E.isInvalid())
1037 return ExprError();
1038 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1039 });
1040}
1041
1043 ValueDecl *Src, QualType DecompType,
1044 const ConstantArrayType *CAT) {
1045 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1046 llvm::APSInt(CAT->getSize()),
1047 CAT->getElementType());
1048}
1049
1051 ValueDecl *Src, QualType DecompType,
1052 const VectorType *VT) {
1054 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1056 DecompType.getQualifiers()));
1057}
1058
1061 ValueDecl *Src, QualType DecompType,
1062 const ComplexType *CT) {
1064 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1066 DecompType.getQualifiers()),
1067 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1068 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1069 });
1070}
1071
1074 const TemplateParameterList *Params) {
1076 llvm::raw_svector_ostream OS(SS);
1077 bool First = true;
1078 unsigned I = 0;
1079 for (auto &Arg : Args.arguments()) {
1080 if (!First)
1081 OS << ", ";
1082 Arg.getArgument().print(PrintingPolicy, OS,
1084 PrintingPolicy, Params, I));
1085 First = false;
1086 I++;
1087 }
1088 return std::string(OS.str());
1089}
1090
1091static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1092 TemplateArgumentListInfo &Args, unsigned DiagID) {
1093 auto DiagnoseMissing = [&] {
1094 if (DiagID)
1095 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1096 Args, /*Params*/ nullptr);
1097 return QualType();
1098 };
1099
1100 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1101 NamespaceDecl *Std = S.getStdNamespace();
1102 if (!Std)
1103 return DiagnoseMissing();
1104
1105 // Look up the trait itself, within namespace std. We can diagnose various
1106 // problems with this lookup even if we've been asked to not diagnose a
1107 // missing specialization, because this can only fail if the user has been
1108 // declaring their own names in namespace std or we don't support the
1109 // standard library implementation in use.
1110 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), Loc,
1112 if (!S.LookupQualifiedName(Result, Std))
1113 return DiagnoseMissing();
1114 if (Result.isAmbiguous())
1115 return QualType();
1116
1117 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1118 if (!TraitTD) {
1119 Result.suppressDiagnostics();
1120 NamedDecl *Found = *Result.begin();
1121 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1122 S.Diag(Found->getLocation(), diag::note_declared_at);
1123 return QualType();
1124 }
1125
1126 // Build the template-id.
1127 QualType TraitTy = S.CheckTemplateIdType(
1128 ElaboratedTypeKeyword::None, TemplateName(TraitTD), Loc, Args,
1129 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1130 if (TraitTy.isNull())
1131 return QualType();
1132
1133 if (!S.isCompleteType(Loc, TraitTy)) {
1134 if (DiagID)
1136 Loc, TraitTy, DiagID,
1138 TraitTD->getTemplateParameters()));
1139 return QualType();
1140 }
1141 return TraitTy;
1142}
1143
1144static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1145 LookupResult &MemberLookup) {
1146 assert(RD && "specialization of class template is not a class?");
1147 S.LookupQualifiedName(MemberLookup, RD);
1148 return MemberLookup.isAmbiguous();
1149}
1150
1151static TemplateArgumentLoc
1153 uint64_t I) {
1154 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1155 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1156}
1157
1158static TemplateArgumentLoc
1162
1163namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1164
1165static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1166 unsigned &OutSize) {
1169
1170 // Form template argument list for tuple_size<T>.
1171 TemplateArgumentListInfo Args(Loc, Loc);
1173
1174 QualType TraitTy = getStdTrait(S, Loc, "tuple_size", Args, /*DiagID=*/0);
1175 if (TraitTy.isNull())
1176 return IsTupleLike::NotTupleLike;
1177
1180
1181 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1182 // it's not tuple-like.
1183 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R) || R.empty())
1184 return IsTupleLike::NotTupleLike;
1185
1186 // If we get this far, we've committed to the tuple interpretation, but
1187 // we can still fail if there actually isn't a usable ::value.
1188
1189 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1190 LookupResult &R;
1192 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1193 : R(R), Args(Args) {}
1194 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1195 SourceLocation Loc) override {
1196 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1198 /*Params*/ nullptr);
1199 }
1200 } Diagnoser(R, Args);
1201
1202 ExprResult E =
1203 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1204 if (E.isInvalid())
1205 return IsTupleLike::Error;
1206
1207 llvm::APSInt Size;
1208 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1209 if (E.isInvalid())
1210 return IsTupleLike::Error;
1211
1212 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1213 // an UnsignedOrNone.
1214 if (Size < 0 || Size >= UINT_MAX) {
1216 Size.toString(Str);
1217 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_invalid)
1219 /*Params=*/nullptr)
1220 << StringRef(Str.data(), Str.size());
1221 return IsTupleLike::Error;
1222 }
1223
1224 OutSize = Size.getExtValue();
1225 return IsTupleLike::TupleLike;
1226}
1227
1228/// \return std::tuple_element<I, T>::type.
1230 unsigned I, QualType T) {
1231 // Form template argument list for tuple_element<I, T>.
1232 TemplateArgumentListInfo Args(Loc, Loc);
1233 Args.addArgument(
1236
1237 QualType TraitTy =
1238 getStdTrait(S, Loc, "tuple_element", Args,
1239 diag::err_decomp_decl_std_tuple_element_not_specialized);
1240 if (TraitTy.isNull())
1241 return QualType();
1242
1243 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1244 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1245 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R))
1246 return QualType();
1247
1248 auto *TD = R.getAsSingle<TypeDecl>();
1249 if (!TD) {
1250 R.suppressDiagnostics();
1251 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1253 /*Params*/ nullptr);
1254 if (!R.empty())
1255 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1256 return QualType();
1257 }
1258
1259 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1260 return S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, Qualifier, TD);
1261}
1262
1263namespace {
1264struct InitializingBinding {
1265 Sema &S;
1266 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1267 Sema::CodeSynthesisContext Ctx;
1270 Ctx.Entity = BD;
1272 }
1273 ~InitializingBinding() {
1275 }
1276};
1277}
1278
1281 VarDecl *Src, QualType DecompType,
1282 unsigned NumElems) {
1283 auto *DD = cast<DecompositionDecl>(Src);
1284 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))
1285 return true;
1286
1287 if (Bindings.empty())
1288 return false;
1289
1290 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1291
1292 // [dcl.decomp]p3:
1293 // The unqualified-id get is looked up in the scope of E by class member
1294 // access lookup ...
1295 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1296 bool UseMemberGet = false;
1297 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1298 if (auto *RD = DecompType->getAsCXXRecordDecl())
1299 S.LookupQualifiedName(MemberGet, RD);
1300 if (MemberGet.isAmbiguous())
1301 return true;
1302 // ... and if that finds at least one declaration that is a function
1303 // template whose first template parameter is a non-type parameter ...
1304 for (NamedDecl *D : MemberGet) {
1305 if (FunctionTemplateDecl *FTD =
1306 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1307 TemplateParameterList *TPL = FTD->getTemplateParameters();
1308 if (TPL->size() != 0 &&
1310 // ... the initializer is e.get<i>().
1311 UseMemberGet = true;
1312 break;
1313 }
1314 }
1315 }
1316 }
1317
1318 unsigned I = 0;
1319 for (auto *B : DD->flat_bindings()) {
1320 InitializingBinding InitContext(S, B);
1321 SourceLocation Loc = B->getLocation();
1322
1323 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1324 if (E.isInvalid())
1325 return true;
1326
1327 // e is an lvalue if the type of the entity is an lvalue reference and
1328 // an xvalue otherwise
1329 if (!Src->getType()->isLValueReferenceType())
1330 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1331 E.get(), nullptr, VK_XValue,
1333
1334 TemplateArgumentListInfo Args(Loc, Loc);
1335 Args.addArgument(
1337
1338 if (UseMemberGet) {
1339 // if [lookup of member get] finds at least one declaration, the
1340 // initializer is e.get<i-1>().
1341 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1342 CXXScopeSpec(), SourceLocation(), nullptr,
1343 MemberGet, &Args, nullptr);
1344 if (E.isInvalid())
1345 return true;
1346
1347 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);
1348 } else {
1349 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1350 // in the associated namespaces.
1353 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1355 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1356
1357 Expr *Arg = E.get();
1358 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1359 }
1360 if (E.isInvalid())
1361 return true;
1362 Expr *Init = E.get();
1363
1364 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1365 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1366 if (T.isNull())
1367 return true;
1368
1369 // each vi is a variable of type "reference to T" initialized with the
1370 // initializer, where the reference is an lvalue reference if the
1371 // initializer is an lvalue and an rvalue reference otherwise
1372 QualType RefType =
1373 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1374 if (RefType.isNull())
1375 return true;
1376
1377 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1378 // entity and this type was never written in source code.
1379 auto *RefVD =
1380 VarDecl::Create(S.Context, Src->getDeclContext(), Loc, Loc,
1381 B->getDeclName().getAsIdentifierInfo(), RefType,
1382 /*TInfo=*/nullptr, Src->getStorageClass());
1383 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1384 RefVD->setTSCSpec(Src->getTSCSpec());
1385 RefVD->setImplicit();
1386 if (Src->isInlineSpecified())
1387 RefVD->setInlineSpecified();
1388 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1389
1392 InitializationSequence Seq(S, Entity, Kind, Init);
1393 E = Seq.Perform(S, Entity, Kind, Init);
1394 if (E.isInvalid())
1395 return true;
1396 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1397 if (E.isInvalid())
1398 return true;
1399 RefVD->setInit(E.get());
1401
1403 DeclarationNameInfo(B->getDeclName(), Loc),
1404 RefVD);
1405 if (E.isInvalid())
1406 return true;
1407
1408 B->setBinding(T, E.get());
1409 I++;
1410 }
1411
1412 return false;
1413}
1414
1415/// Find the base class to decompose in a built-in decomposition of a class type.
1416/// This base class search is, unfortunately, not quite like any other that we
1417/// perform anywhere else in C++.
1419 const CXXRecordDecl *RD,
1420 CXXCastPath &BasePath) {
1421 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1422 CXXBasePath &Path) {
1423 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1424 };
1425
1426 const CXXRecordDecl *ClassWithFields = nullptr;
1428 if (RD->hasDirectFields())
1429 // [dcl.decomp]p4:
1430 // Otherwise, all of E's non-static data members shall be public direct
1431 // members of E ...
1432 ClassWithFields = RD;
1433 else {
1434 // ... or of ...
1435 CXXBasePaths Paths;
1436 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1437 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1438 // If no classes have fields, just decompose RD itself. (This will work
1439 // if and only if zero bindings were provided.)
1440 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1441 }
1442
1443 CXXBasePath *BestPath = nullptr;
1444 for (auto &P : Paths) {
1445 if (!BestPath)
1446 BestPath = &P;
1447 else if (!S.Context.hasSameType(P.back().Base->getType(),
1448 BestPath->back().Base->getType())) {
1449 // ... the same ...
1450 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1451 << false << RD << BestPath->back().Base->getType()
1452 << P.back().Base->getType();
1453 return DeclAccessPair();
1454 } else if (P.Access < BestPath->Access) {
1455 BestPath = &P;
1456 }
1457 }
1458
1459 // ... unambiguous ...
1460 QualType BaseType = BestPath->back().Base->getType();
1461 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1462 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1463 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1464 return DeclAccessPair();
1465 }
1466
1467 // ... [accessible, implied by other rules] base class of E.
1468 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getCanonicalTagType(RD),
1469 *BestPath, diag::err_decomp_decl_inaccessible_base);
1470 AS = BestPath->Access;
1471
1472 ClassWithFields = BaseType->getAsCXXRecordDecl();
1473 S.BuildBasePathArray(Paths, BasePath);
1474 }
1475
1476 // The above search did not check whether the selected class itself has base
1477 // classes with fields, so check that now.
1478 CXXBasePaths Paths;
1479 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1480 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1481 << (ClassWithFields == RD) << RD << ClassWithFields
1482 << Paths.front().back().Base->getType();
1483 return DeclAccessPair();
1484 }
1485
1486 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1487}
1488
1490 const CXXRecordDecl *OrigRD,
1491 QualType DecompType,
1492 DeclAccessPair BasePair) {
1493 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1494 if (!RD)
1495 return true;
1496
1497 for (auto *FD : RD->fields()) {
1498 if (FD->isUnnamedBitField())
1499 continue;
1500
1501 // All the non-static data members are required to be nameable, so they
1502 // must all have names.
1503 if (!FD->getDeclName()) {
1504 if (RD->isLambda()) {
1505 S.Diag(Loc, diag::err_decomp_decl_lambda);
1506 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1507 return true;
1508 }
1509
1510 if (FD->isAnonymousStructOrUnion()) {
1511 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)
1512 << DecompType << FD->getType()->isUnionType();
1513 S.Diag(FD->getLocation(), diag::note_declared_at);
1514 return true;
1515 }
1516
1517 // FIXME: Are there any other ways we could have an anonymous member?
1518 }
1519 // The field must be accessible in the context of the structured binding.
1520 // We already checked that the base class is accessible.
1521 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1522 // const_cast here.
1524 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1526 BasePair.getAccess(), FD->getAccess())));
1527 }
1528 return false;
1529}
1530
1532 ValueDecl *Src, QualType DecompType,
1533 const CXXRecordDecl *OrigRD) {
1534 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1535 diag::err_incomplete_type))
1536 return true;
1537
1538 CXXCastPath BasePath;
1539 DeclAccessPair BasePair =
1540 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1541 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1542 if (!RD)
1543 return true;
1544 QualType BaseType = S.Context.getQualifiedType(
1545 S.Context.getCanonicalTagType(RD), DecompType.getQualifiers());
1546
1547 auto *DD = cast<DecompositionDecl>(Src);
1548 unsigned NumFields = llvm::count_if(
1549 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1550 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))
1551 return true;
1552
1553 // all of E's non-static data members shall be [...] well-formed
1554 // when named as e.name in the context of the structured binding,
1555 // E shall not have an anonymous union member, ...
1556 auto FlatBindings = DD->flat_bindings();
1557 assert(llvm::range_size(FlatBindings) == NumFields);
1558 auto FlatBindingsItr = FlatBindings.begin();
1559
1560 if (CheckMemberDecompositionFields(S, Src->getLocation(), OrigRD, DecompType,
1561 BasePair))
1562 return true;
1563
1564 for (auto *FD : RD->fields()) {
1565 if (FD->isUnnamedBitField())
1566 continue;
1567
1568 // We have a real field to bind.
1569 assert(FlatBindingsItr != FlatBindings.end());
1570 BindingDecl *B = *(FlatBindingsItr++);
1571 SourceLocation Loc = B->getLocation();
1572
1573 // Initialize the binding to Src.FD.
1574 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1575 if (E.isInvalid())
1576 return true;
1577 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1578 VK_LValue, &BasePath);
1579 if (E.isInvalid())
1580 return true;
1581 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1582 CXXScopeSpec(), FD,
1584 DeclarationNameInfo(FD->getDeclName(), Loc));
1585 if (E.isInvalid())
1586 return true;
1587
1588 // If the type of the member is T, the referenced type is cv T, where cv is
1589 // the cv-qualification of the decomposition expression.
1590 //
1591 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1592 // 'const' to the type of the field.
1593 Qualifiers Q = DecompType.getQualifiers();
1594 if (FD->isMutable())
1595 Q.removeConst();
1596 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1597 }
1598
1599 return false;
1600}
1601
1603 QualType DecompType = DD->getType();
1604
1605 // If the type of the decomposition is dependent, then so is the type of
1606 // each binding.
1607 if (DecompType->isDependentType()) {
1608 // Note that all of the types are still Null or PackExpansionType.
1609 for (auto *B : DD->bindings()) {
1610 // Do not overwrite any pack type.
1611 if (B->getType().isNull())
1612 B->setType(Context.DependentTy);
1613 }
1614 return;
1615 }
1616
1617 DecompType = DecompType.getNonReferenceType();
1619
1620 // C++1z [dcl.decomp]/2:
1621 // If E is an array type [...]
1622 // As an extension, we also support decomposition of built-in complex and
1623 // vector types.
1624 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1625 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1626 DD->setInvalidDecl();
1627 return;
1628 }
1629 if (auto *VT = DecompType->getAs<VectorType>()) {
1630 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1631 DD->setInvalidDecl();
1632 return;
1633 }
1634 if (auto *CT = DecompType->getAs<ComplexType>()) {
1635 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1636 DD->setInvalidDecl();
1637 return;
1638 }
1639
1640 // C++1z [dcl.decomp]/3:
1641 // if the expression std::tuple_size<E>::value is a well-formed integral
1642 // constant expression, [...]
1643 unsigned TupleSize;
1644 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1645 case IsTupleLike::Error:
1646 DD->setInvalidDecl();
1647 return;
1648
1649 case IsTupleLike::TupleLike:
1650 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1651 DD->setInvalidDecl();
1652 return;
1653
1654 case IsTupleLike::NotTupleLike:
1655 break;
1656 }
1657
1658 // C++1z [dcl.dcl]/8:
1659 // [E shall be of array or non-union class type]
1660 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1661 if (!RD || RD->isUnion()) {
1662 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1663 << DD << !RD << DecompType;
1664 DD->setInvalidDecl();
1665 return;
1666 }
1667
1668 // C++1z [dcl.decomp]/4:
1669 // all of E's non-static data members shall be [...] direct members of
1670 // E or of the same unambiguous public base class of E, ...
1671 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1672 DD->setInvalidDecl();
1673}
1674
1676 SourceLocation Loc) {
1677 const ASTContext &Ctx = getASTContext();
1678 assert(!T->isDependentType());
1679
1680 Qualifiers Quals;
1681 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1682 Quals.removeCVRQualifiers();
1683 T = Context.getQualifiedType(Unqual, Quals);
1684
1685 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1686 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1687 if (auto *VT = T->getAs<VectorType>())
1688 return VT->getNumElements();
1689 if (T->getAs<ComplexType>())
1690 return 2u;
1691
1692 unsigned TupleSize;
1693 switch (isTupleLike(*this, Loc, T, TupleSize)) {
1694 case IsTupleLike::Error:
1695 return std::nullopt;
1696 case IsTupleLike::TupleLike:
1697 return TupleSize;
1698 case IsTupleLike::NotTupleLike:
1699 break;
1700 }
1701
1702 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1703 if (!OrigRD || OrigRD->isUnion())
1704 return std::nullopt;
1705
1706 if (RequireCompleteType(Loc, T, diag::err_incomplete_type))
1707 return std::nullopt;
1708
1709 CXXCastPath BasePath;
1710 DeclAccessPair BasePair =
1711 findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);
1712 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1713 if (!RD)
1714 return std::nullopt;
1715
1716 unsigned NumFields = llvm::count_if(
1717 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1718
1719 if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))
1720 return std::nullopt;
1721
1722 return NumFields;
1723}
1724
1726 // Shortcut if exceptions are disabled.
1727 if (!getLangOpts().CXXExceptions)
1728 return;
1729
1730 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1731 "Should only be called if types are otherwise the same.");
1732
1733 QualType NewType = New->getType();
1734 QualType OldType = Old->getType();
1735
1736 // We're only interested in pointers and references to functions, as well
1737 // as pointers to member functions.
1738 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1739 NewType = R->getPointeeType();
1740 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1741 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1742 NewType = P->getPointeeType();
1743 OldType = OldType->castAs<PointerType>()->getPointeeType();
1744 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1745 NewType = M->getPointeeType();
1746 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1747 }
1748
1749 if (!NewType->isFunctionProtoType())
1750 return;
1751
1752 // There's lots of special cases for functions. For function pointers, system
1753 // libraries are hopefully not as broken so that we don't need these
1754 // workarounds.
1756 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1757 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1758 New->setInvalidDecl();
1759 }
1760}
1761
1762/// CheckCXXDefaultArguments - Verify that the default arguments for a
1763/// function declaration are well-formed according to C++
1764/// [dcl.fct.default].
1766 // This checking doesn't make sense for explicit specializations; their
1767 // default arguments are determined by the declaration we're specializing,
1768 // not by FD.
1770 return;
1771 if (auto *FTD = FD->getDescribedFunctionTemplate())
1772 if (FTD->isMemberSpecialization())
1773 return;
1774
1775 unsigned NumParams = FD->getNumParams();
1776 unsigned ParamIdx = 0;
1777
1778 // Find first parameter with a default argument
1779 for (; ParamIdx < NumParams; ++ParamIdx) {
1780 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1781 if (Param->hasDefaultArg())
1782 break;
1783 }
1784
1785 // C++20 [dcl.fct.default]p4:
1786 // In a given function declaration, each parameter subsequent to a parameter
1787 // with a default argument shall have a default argument supplied in this or
1788 // a previous declaration, unless the parameter was expanded from a
1789 // parameter pack, or shall be a function parameter pack.
1790 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1791 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1792 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1794 CurrentInstantiationScope->isLocalPackExpansion(Param)))
1795 continue;
1796 if (Param->isInvalidDecl())
1797 /* We already complained about this parameter. */;
1798 else if (Param->getIdentifier())
1799 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1800 << Param->getIdentifier();
1801 else
1802 Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1803 }
1804}
1805
1806/// Check that the given type is a literal type. Issue a diagnostic if not,
1807/// if Kind is Diagnose.
1808/// \return \c true if a problem has been found (and optionally diagnosed).
1809template <typename... Ts>
1811 SourceLocation Loc, QualType T, unsigned DiagID,
1812 Ts &&...DiagArgs) {
1813 if (T->isDependentType())
1814 return false;
1815
1816 switch (Kind) {
1818 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1819 std::forward<Ts>(DiagArgs)...);
1820
1822 return !T->isLiteralType(SemaRef.Context);
1823 }
1824
1825 llvm_unreachable("unknown CheckConstexprKind");
1826}
1827
1828/// Determine whether a destructor cannot be constexpr due to
1830 const CXXDestructorDecl *DD,
1832 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1833 "this check is obsolete for C++23");
1834 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1835 const CXXRecordDecl *RD =
1836 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1837 if (!RD || RD->hasConstexprDestructor())
1838 return true;
1839
1841 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1842 << static_cast<int>(DD->getConstexprKind()) << !FD
1843 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1844 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1845 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1846 }
1847 return false;
1848 };
1849
1850 const CXXRecordDecl *RD = DD->getParent();
1851 for (const CXXBaseSpecifier &B : RD->bases())
1852 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1853 return false;
1854 for (const FieldDecl *FD : RD->fields())
1855 if (!Check(FD->getLocation(), FD->getType(), FD))
1856 return false;
1857 return true;
1858}
1859
1860/// Check whether a function's parameter types are all literal types. If so,
1861/// return true. If not, produce a suitable diagnostic and return false.
1863 const FunctionDecl *FD,
1865 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1866 "this check is obsolete for C++23");
1867 unsigned ArgIndex = 0;
1868 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1869 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1870 e = FT->param_type_end();
1871 i != e; ++i, ++ArgIndex) {
1872 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1873 assert(PD && "null in a parameter list");
1874 SourceLocation ParamLoc = PD->getLocation();
1875 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1876 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1878 FD->isConsteval()))
1879 return false;
1880 }
1881 return true;
1882}
1883
1884/// Check whether a function's return type is a literal type. If so, return
1885/// true. If not, produce a suitable diagnostic and return false.
1886static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1888 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1889 "this check is obsolete for C++23");
1890 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1891 diag::err_constexpr_non_literal_return,
1892 FD->isConsteval()))
1893 return false;
1894 return true;
1895}
1896
1897/// Get diagnostic %select index for tag kind for
1898/// record diagnostic message.
1899/// WARNING: Indexes apply to particular diagnostics only!
1900///
1901/// \returns diagnostic %select index.
1903 switch (Tag) {
1905 return 0;
1907 return 1;
1908 case TagTypeKind::Class:
1909 return 2;
1910 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1911 }
1912}
1913
1914static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1915 Stmt *Body,
1917static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1918
1920 CheckConstexprKind Kind) {
1921 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1922 if (MD && MD->isInstance()) {
1923 // C++11 [dcl.constexpr]p4:
1924 // The definition of a constexpr constructor shall satisfy the following
1925 // constraints:
1926 // - the class shall not have any virtual base classes;
1927 //
1928 // FIXME: This only applies to constructors and destructors, not arbitrary
1929 // member functions.
1930 const CXXRecordDecl *RD = MD->getParent();
1931 if (RD->getNumVBases()) {
1933 return false;
1934
1935 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1936 << isa<CXXConstructorDecl>(NewFD)
1938 for (const auto &I : RD->vbases())
1939 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1940 << I.getSourceRange();
1941 return false;
1942 }
1943 }
1944
1945 if (!isa<CXXConstructorDecl>(NewFD)) {
1946 // C++11 [dcl.constexpr]p3:
1947 // The definition of a constexpr function shall satisfy the following
1948 // constraints:
1949 // - it shall not be virtual; (removed in C++20)
1950 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1951 if (Method && Method->isVirtual()) {
1952 if (getLangOpts().CPlusPlus20) {
1953 if (Kind == CheckConstexprKind::Diagnose)
1954 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1955 } else {
1957 return false;
1958
1959 Method = Method->getCanonicalDecl();
1960 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1961
1962 // If it's not obvious why this function is virtual, find an overridden
1963 // function which uses the 'virtual' keyword.
1964 const CXXMethodDecl *WrittenVirtual = Method;
1965 while (!WrittenVirtual->isVirtualAsWritten())
1966 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1967 if (WrittenVirtual != Method)
1968 Diag(WrittenVirtual->getLocation(),
1969 diag::note_overridden_virtual_function);
1970 return false;
1971 }
1972 }
1973
1974 // - its return type shall be a literal type; (removed in C++23)
1975 if (!getLangOpts().CPlusPlus23 &&
1976 !CheckConstexprReturnType(*this, NewFD, Kind))
1977 return false;
1978 }
1979
1980 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1981 // A destructor can be constexpr only if the defaulted destructor could be;
1982 // we don't need to check the members and bases if we already know they all
1983 // have constexpr destructors. (removed in C++23)
1984 if (!getLangOpts().CPlusPlus23 &&
1985 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1987 return false;
1988 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1989 return false;
1990 }
1991 }
1992
1993 // - each of its parameter types shall be a literal type; (removed in C++23)
1994 if (!getLangOpts().CPlusPlus23 &&
1995 !CheckConstexprParameterTypes(*this, NewFD, Kind))
1996 return false;
1997
1998 Stmt *Body = NewFD->getBody();
1999 assert(Body &&
2000 "CheckConstexprFunctionDefinition called on function with no body");
2001 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
2002}
2003
2004/// Check the given declaration statement is legal within a constexpr function
2005/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2006///
2007/// \return true if the body is OK (maybe only as an extension), false if we
2008/// have diagnosed a problem.
2009static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2010 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2012 // C++11 [dcl.constexpr]p3 and p4:
2013 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2014 // contain only
2015 for (const auto *DclIt : DS->decls()) {
2016 switch (DclIt->getKind()) {
2017 case Decl::StaticAssert:
2018 case Decl::Using:
2019 case Decl::UsingShadow:
2020 case Decl::UsingDirective:
2021 case Decl::UnresolvedUsingTypename:
2022 case Decl::UnresolvedUsingValue:
2023 case Decl::UsingEnum:
2024 // - static_assert-declarations
2025 // - using-declarations,
2026 // - using-directives,
2027 // - using-enum-declaration
2028 continue;
2029
2030 case Decl::Typedef:
2031 case Decl::TypeAlias: {
2032 // - typedef declarations and alias-declarations that do not define
2033 // classes or enumerations,
2034 const auto *TN = cast<TypedefNameDecl>(DclIt);
2035 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2036 // Don't allow variably-modified types in constexpr functions.
2038 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2039 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
2040 << TL.getSourceRange() << TL.getType()
2042 }
2043 return false;
2044 }
2045 continue;
2046 }
2047
2048 case Decl::Enum:
2049 case Decl::CXXRecord:
2050 // C++1y allows types to be defined, not just declared.
2051 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
2053 SemaRef.DiagCompat(DS->getBeginLoc(),
2054 diag_compat::constexpr_type_definition)
2056 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2057 return false;
2058 }
2059 }
2060 continue;
2061
2062 case Decl::EnumConstant:
2063 case Decl::IndirectField:
2064 case Decl::ParmVar:
2065 // These can only appear with other declarations which are banned in
2066 // C++11 and permitted in C++1y, so ignore them.
2067 continue;
2068
2069 case Decl::Var:
2070 case Decl::Decomposition: {
2071 // C++1y [dcl.constexpr]p3 allows anything except:
2072 // a definition of a variable of non-literal type or of static or
2073 // thread storage duration or [before C++2a] for which no
2074 // initialization is performed.
2075 const auto *VD = cast<VarDecl>(DclIt);
2076 if (VD->isThisDeclarationADefinition()) {
2077 if (VD->isStaticLocal()) {
2079 SemaRef.DiagCompat(VD->getLocation(),
2080 diag_compat::constexpr_static_var)
2082 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2083 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2084 return false;
2085 }
2086 }
2087 if (SemaRef.LangOpts.CPlusPlus23) {
2088 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
2089 diag::warn_cxx20_compat_constexpr_var,
2091 } else if (CheckLiteralType(
2092 SemaRef, Kind, VD->getLocation(), VD->getType(),
2093 diag::err_constexpr_local_var_non_literal_type,
2095 return false;
2096 }
2097 if (!VD->getType()->isDependentType() &&
2098 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2100 SemaRef.DiagCompat(VD->getLocation(),
2101 diag_compat::constexpr_local_var_no_init)
2103 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2104 return false;
2105 }
2106 continue;
2107 }
2108 }
2110 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)
2112 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2113 return false;
2114 }
2115 continue;
2116 }
2117
2118 case Decl::NamespaceAlias:
2119 case Decl::Function:
2120 // These are disallowed in C++11 and permitted in C++1y. Allow them
2121 // everywhere as an extension.
2122 if (!Cxx1yLoc.isValid())
2123 Cxx1yLoc = DS->getBeginLoc();
2124 continue;
2125
2126 default:
2128 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2129 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2130 }
2131 return false;
2132 }
2133 }
2134
2135 return true;
2136}
2137
2138/// Check that the given field is initialized within a constexpr constructor.
2139///
2140/// \param Dcl The constexpr constructor being checked.
2141/// \param Field The field being checked. This may be a member of an anonymous
2142/// struct or union nested within the class being checked.
2143/// \param Inits All declarations, including anonymous struct/union members and
2144/// indirect members, for which any initialization was provided.
2145/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2146/// multiple notes for different members to the same error.
2147/// \param Kind Whether we're diagnosing a constructor as written or determining
2148/// whether the formal requirements are satisfied.
2149/// \return \c false if we're checking for validity and the constructor does
2150/// not satisfy the requirements on a constexpr constructor.
2152 const FunctionDecl *Dcl,
2153 FieldDecl *Field,
2155 bool &Diagnosed,
2157 // In C++20 onwards, there's nothing to check for validity.
2159 SemaRef.getLangOpts().CPlusPlus20)
2160 return true;
2161
2162 if (Field->isInvalidDecl())
2163 return true;
2164
2165 if (Field->isUnnamedBitField())
2166 return true;
2167
2168 // Anonymous unions with no variant members and empty anonymous structs do not
2169 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2170 // indirect fields don't need initializing.
2171 if (Field->isAnonymousStructOrUnion() &&
2172 (Field->getType()->isUnionType()
2173 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2174 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2175 return true;
2176
2177 if (!Inits.count(Field)) {
2179 if (!Diagnosed) {
2180 SemaRef.DiagCompat(Dcl->getLocation(),
2181 diag_compat::constexpr_ctor_missing_init);
2182 Diagnosed = true;
2183 }
2184 SemaRef.Diag(Field->getLocation(),
2185 diag::note_constexpr_ctor_missing_init);
2186 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2187 return false;
2188 }
2189 } else if (Field->isAnonymousStructOrUnion()) {
2190 const auto *RD = Field->getType()->castAsRecordDecl();
2191 for (auto *I : RD->fields())
2192 // If an anonymous union contains an anonymous struct of which any member
2193 // is initialized, all members must be initialized.
2194 if (!RD->isUnion() || Inits.count(I))
2195 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2196 Kind))
2197 return false;
2198 }
2199 return true;
2200}
2201
2202/// Check the provided statement is allowed in a constexpr function
2203/// definition.
2204static bool
2207 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2208 SourceLocation &Cxx2bLoc,
2210 // - its function-body shall be [...] a compound-statement that contains only
2211 switch (S->getStmtClass()) {
2212 case Stmt::NullStmtClass:
2213 // - null statements,
2214 return true;
2215
2216 case Stmt::DeclStmtClass:
2217 // - static_assert-declarations
2218 // - using-declarations,
2219 // - using-directives,
2220 // - typedef declarations and alias-declarations that do not define
2221 // classes or enumerations,
2222 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2223 return false;
2224 return true;
2225
2226 case Stmt::ReturnStmtClass:
2227 // - and exactly one return statement;
2228 if (isa<CXXConstructorDecl>(Dcl)) {
2229 // C++1y allows return statements in constexpr constructors.
2230 if (!Cxx1yLoc.isValid())
2231 Cxx1yLoc = S->getBeginLoc();
2232 return true;
2233 }
2234
2235 ReturnStmts.push_back(S->getBeginLoc());
2236 return true;
2237
2238 case Stmt::AttributedStmtClass:
2239 // Attributes on a statement don't affect its formal kind and hence don't
2240 // affect its validity in a constexpr function.
2242 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2243 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2244
2245 case Stmt::CompoundStmtClass: {
2246 // C++1y allows compound-statements.
2247 if (!Cxx1yLoc.isValid())
2248 Cxx1yLoc = S->getBeginLoc();
2249
2250 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2251 for (auto *BodyIt : CompStmt->body()) {
2252 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2253 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2254 return false;
2255 }
2256 return true;
2257 }
2258
2259 case Stmt::IfStmtClass: {
2260 // C++1y allows if-statements.
2261 if (!Cxx1yLoc.isValid())
2262 Cxx1yLoc = S->getBeginLoc();
2263
2264 IfStmt *If = cast<IfStmt>(S);
2265 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2266 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2267 return false;
2268 if (If->getElse() &&
2269 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2270 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2271 return false;
2272 return true;
2273 }
2274
2275 case Stmt::WhileStmtClass:
2276 case Stmt::DoStmtClass:
2277 case Stmt::ForStmtClass:
2278 case Stmt::CXXForRangeStmtClass:
2279 case Stmt::ContinueStmtClass:
2280 // C++1y allows all of these. We don't allow them as extensions in C++11,
2281 // because they don't make sense without variable mutation.
2282 if (!SemaRef.getLangOpts().CPlusPlus14)
2283 break;
2284 if (!Cxx1yLoc.isValid())
2285 Cxx1yLoc = S->getBeginLoc();
2286 for (Stmt *SubStmt : S->children()) {
2287 if (SubStmt &&
2288 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2289 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2290 return false;
2291 }
2292 return true;
2293
2294 case Stmt::SwitchStmtClass:
2295 case Stmt::CaseStmtClass:
2296 case Stmt::DefaultStmtClass:
2297 case Stmt::BreakStmtClass:
2298 // C++1y allows switch-statements, and since they don't need variable
2299 // mutation, we can reasonably allow them in C++11 as an extension.
2300 if (!Cxx1yLoc.isValid())
2301 Cxx1yLoc = S->getBeginLoc();
2302 for (Stmt *SubStmt : S->children()) {
2303 if (SubStmt &&
2304 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2305 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2306 return false;
2307 }
2308 return true;
2309
2310 case Stmt::LabelStmtClass:
2311 case Stmt::GotoStmtClass:
2312 if (Cxx2bLoc.isInvalid())
2313 Cxx2bLoc = S->getBeginLoc();
2314 for (Stmt *SubStmt : S->children()) {
2315 if (SubStmt &&
2316 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2317 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2318 return false;
2319 }
2320 return true;
2321
2322 case Stmt::GCCAsmStmtClass:
2323 case Stmt::MSAsmStmtClass:
2324 // C++2a allows inline assembly statements.
2325 case Stmt::CXXTryStmtClass:
2326 if (Cxx2aLoc.isInvalid())
2327 Cxx2aLoc = S->getBeginLoc();
2328 for (Stmt *SubStmt : S->children()) {
2329 if (SubStmt &&
2330 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2331 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2332 return false;
2333 }
2334 return true;
2335
2336 case Stmt::CXXCatchStmtClass:
2337 // Do not bother checking the language mode (already covered by the
2338 // try block check).
2340 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2341 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2342 return false;
2343 return true;
2344
2345 default:
2346 if (!isa<Expr>(S))
2347 break;
2348
2349 // C++1y allows expression-statements.
2350 if (!Cxx1yLoc.isValid())
2351 Cxx1yLoc = S->getBeginLoc();
2352 return true;
2353 }
2354
2356 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2357 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2358 }
2359 return false;
2360}
2361
2362/// Check the body for the given constexpr function declaration only contains
2363/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2364///
2365/// \return true if the body is OK, false if we have found or diagnosed a
2366/// problem.
2367static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2368 Stmt *Body,
2371
2372 if (isa<CXXTryStmt>(Body)) {
2373 // C++11 [dcl.constexpr]p3:
2374 // The definition of a constexpr function shall satisfy the following
2375 // constraints: [...]
2376 // - its function-body shall be = delete, = default, or a
2377 // compound-statement
2378 //
2379 // C++11 [dcl.constexpr]p4:
2380 // In the definition of a constexpr constructor, [...]
2381 // - its function-body shall not be a function-try-block;
2382 //
2383 // This restriction is lifted in C++2a, as long as inner statements also
2384 // apply the general constexpr rules.
2385 switch (Kind) {
2387 if (!SemaRef.getLangOpts().CPlusPlus20)
2388 return false;
2389 break;
2390
2392 SemaRef.DiagCompat(Body->getBeginLoc(),
2393 diag_compat::constexpr_function_try_block)
2395 break;
2396 }
2397 }
2398
2399 // - its function-body shall be [...] a compound-statement that contains only
2400 // [... list of cases ...]
2401 //
2402 // Note that walking the children here is enough to properly check for
2403 // CompoundStmt and CXXTryStmt body.
2404 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2405 for (Stmt *SubStmt : Body->children()) {
2406 if (SubStmt &&
2407 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2408 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2409 return false;
2410 }
2411
2413 // If this is only valid as an extension, report that we don't satisfy the
2414 // constraints of the current language.
2415 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2416 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2417 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2418 return false;
2419 } else if (Cxx2bLoc.isValid()) {
2420 SemaRef.DiagCompat(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)
2422 } else if (Cxx2aLoc.isValid()) {
2423 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)
2425 } else if (Cxx1yLoc.isValid()) {
2426 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)
2428 }
2429
2431 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2432 const CXXRecordDecl *RD = Constructor->getParent();
2433 // DR1359:
2434 // - every non-variant non-static data member and base class sub-object
2435 // shall be initialized;
2436 // DR1460:
2437 // - if the class is a union having variant members, exactly one of them
2438 // shall be initialized;
2439 if (RD->isUnion()) {
2440 if (Constructor->getNumCtorInitializers() == 0 &&
2441 RD->hasVariantMembers()) {
2443 SemaRef.DiagCompat(Dcl->getLocation(),
2444 diag_compat::constexpr_union_ctor_no_init);
2445 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2446 return false;
2447 }
2448 }
2449 } else if (!Constructor->isDependentContext() &&
2450 !Constructor->isDelegatingConstructor()) {
2451 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2452
2453 // Skip detailed checking if we have enough initializers, and we would
2454 // allow at most one initializer per member.
2455 bool AnyAnonStructUnionMembers = false;
2456 unsigned Fields = 0;
2458 E = RD->field_end(); I != E; ++I, ++Fields) {
2459 if (I->isAnonymousStructOrUnion()) {
2460 AnyAnonStructUnionMembers = true;
2461 break;
2462 }
2463 }
2464 // DR1460:
2465 // - if the class is a union-like class, but is not a union, for each of
2466 // its anonymous union members having variant members, exactly one of
2467 // them shall be initialized;
2468 if (AnyAnonStructUnionMembers ||
2469 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2470 // Check initialization of non-static data members. Base classes are
2471 // always initialized so do not need to be checked. Dependent bases
2472 // might not have initializers in the member initializer list.
2474 for (const auto *I: Constructor->inits()) {
2475 if (FieldDecl *FD = I->getMember())
2476 Inits.insert(FD);
2477 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2478 Inits.insert(ID->chain_begin(), ID->chain_end());
2479 }
2480
2481 bool Diagnosed = false;
2482 for (auto *I : RD->fields())
2483 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2484 Kind))
2485 return false;
2486 }
2487 }
2488 } else {
2489 if (ReturnStmts.empty()) {
2490 switch (Kind) {
2492 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2493 return false;
2494 break;
2495
2497 // The formal requirements don't include this rule in C++14, even
2498 // though the "must be able to produce a constant expression" rules
2499 // still imply it in some cases.
2500 if (!SemaRef.getLangOpts().CPlusPlus14)
2501 return false;
2502 break;
2503 }
2504 } else if (ReturnStmts.size() > 1) {
2505 switch (Kind) {
2507 SemaRef.DiagCompat(ReturnStmts.back(),
2508 diag_compat::constexpr_body_multiple_return);
2509 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2510 SemaRef.Diag(ReturnStmts[I],
2511 diag::note_constexpr_body_previous_return);
2512 break;
2513
2515 if (!SemaRef.getLangOpts().CPlusPlus14)
2516 return false;
2517 break;
2518 }
2519 }
2520 }
2521
2522 // C++11 [dcl.constexpr]p5:
2523 // if no function argument values exist such that the function invocation
2524 // substitution would produce a constant expression, the program is
2525 // ill-formed; no diagnostic required.
2526 // C++11 [dcl.constexpr]p3:
2527 // - every constructor call and implicit conversion used in initializing the
2528 // return value shall be one of those allowed in a constant expression.
2529 // C++11 [dcl.constexpr]p4:
2530 // - every constructor involved in initializing non-static data members and
2531 // base class sub-objects shall be a constexpr constructor.
2532 //
2533 // Note that this rule is distinct from the "requirements for a constexpr
2534 // function", so is not checked in CheckValid mode. Because the check for
2535 // constexpr potential is expensive, skip the check if the diagnostic is
2536 // disabled, the function is declared in a system header, or we're in C++23
2537 // or later mode (see https://wg21.link/P2448).
2538 bool SkipCheck =
2539 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2540 SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||
2541 SemaRef.getDiagnostics().isIgnored(
2542 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2544 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2545 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2546 SemaRef.Diag(Dcl->getLocation(),
2547 diag::ext_constexpr_function_never_constant_expr)
2548 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2549 << Dcl->getNameInfo().getSourceRange();
2550 for (const auto &Diag : Diags)
2551 SemaRef.Diag(Diag.first, Diag.second);
2552 // Don't return false here: we allow this for compatibility in
2553 // system headers.
2554 }
2555
2556 return true;
2557}
2558
2560 const FunctionDecl *Dcl) {
2561 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2563 // Skip emitting a missing return error diagnostic for non-void functions
2564 // since C++23 no longer mandates constexpr functions to yield constant
2565 // expressions.
2566 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2567 return true;
2568
2569 // C++14 doesn't require constexpr functions to contain a 'return'
2570 // statement. We still do, unless the return type might be void, because
2571 // otherwise if there's no return statement, the function cannot
2572 // be used in a core constant expression.
2573 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2574 SemaRef.Diag(Dcl->getLocation(),
2575 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2576 : diag::err_constexpr_body_no_return)
2577 << Dcl->isConsteval();
2578 return OK;
2579}
2580
2582 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2584 return true;
2588 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2589 if (it != UndefinedButUsed.end()) {
2590 Diag(it->second, diag::err_immediate_function_used_before_definition)
2591 << it->first;
2592 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2593 if (FD->isImmediateFunction() && !FD->isConsteval())
2595 return false;
2596 }
2597 }
2598 return true;
2599}
2600
2602 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2603 "expected an immediate function");
2604 assert(FD->hasBody() && "expected the function to have a body");
2605 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2606 Sema &SemaRef;
2607
2608 const FunctionDecl *ImmediateFn;
2609 bool ImmediateFnIsConstructor;
2610 CXXConstructorDecl *CurrentConstructor = nullptr;
2611 CXXCtorInitializer *CurrentInit = nullptr;
2612
2613 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2614 : SemaRef(SemaRef), ImmediateFn(FD),
2615 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {
2616 ShouldVisitImplicitCode = true;
2617 ShouldVisitLambdaBody = false;
2618 }
2619
2620 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2621 SourceLocation Loc = E->getBeginLoc();
2622 SourceRange Range = E->getSourceRange();
2623 if (CurrentConstructor && CurrentInit) {
2624 Loc = CurrentConstructor->getLocation();
2625 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2626 : SourceRange();
2627 }
2628
2629 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2630
2631 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2632 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2633 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2634 << (InitializedField != nullptr)
2635 << (CurrentInit && !CurrentInit->isWritten())
2636 << InitializedField << Range;
2637 }
2638 bool TraverseCallExpr(CallExpr *E) override {
2639 if (const auto *DR =
2640 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2641 DR && DR->isImmediateEscalating()) {
2642 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2643 return false;
2644 }
2645
2646 for (Expr *A : E->arguments())
2647 if (!TraverseStmt(A))
2648 return false;
2649
2650 return true;
2651 }
2652
2653 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2654 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2655 ReferencedFn && E->isImmediateEscalating()) {
2656 Diag(E, ReferencedFn, /*IsCall=*/false);
2657 return false;
2658 }
2659
2660 return true;
2661 }
2662
2663 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2665 if (E->isImmediateEscalating()) {
2666 Diag(E, D, /*IsCall=*/true);
2667 return false;
2668 }
2669 return true;
2670 }
2671
2672 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2673 llvm::SaveAndRestore RAII(CurrentInit, Init);
2675 }
2676
2677 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2678 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2679 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);
2680 }
2681
2682 bool TraverseType(QualType T, bool TraverseQualifier) override {
2683 return true;
2684 }
2685 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2686
2687 } Visitor(*this, FD);
2688 Visitor.TraverseDecl(FD);
2689}
2690
2692 assert(getLangOpts().CPlusPlus && "No class names in C!");
2693
2694 if (SS && SS->isInvalid())
2695 return nullptr;
2696
2697 if (SS && SS->isNotEmpty()) {
2698 DeclContext *DC = computeDeclContext(*SS, true);
2699 return dyn_cast_or_null<CXXRecordDecl>(DC);
2700 }
2701
2702 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2703}
2704
2706 const CXXScopeSpec *SS) {
2707 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2708 return CurDecl && &II == CurDecl->getIdentifier();
2709}
2710
2712 assert(getLangOpts().CPlusPlus && "No class names in C!");
2713
2714 if (!getLangOpts().SpellChecking)
2715 return false;
2716
2717 CXXRecordDecl *CurDecl;
2718 if (SS && SS->isSet() && !SS->isInvalid()) {
2719 DeclContext *DC = computeDeclContext(*SS, true);
2720 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2721 } else
2722 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2723
2724 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2725 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2726 < II->getLength()) {
2727 II = CurDecl->getIdentifier();
2728 return true;
2729 }
2730
2731 return false;
2732}
2733
2735 SourceRange SpecifierRange,
2736 bool Virtual, AccessSpecifier Access,
2737 TypeSourceInfo *TInfo,
2738 SourceLocation EllipsisLoc) {
2739 QualType BaseType = TInfo->getType();
2740 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2741 if (BaseType->containsErrors()) {
2742 // Already emitted a diagnostic when parsing the error type.
2743 return nullptr;
2744 }
2745
2746 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2747 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2748 << TInfo->getTypeLoc().getSourceRange();
2749 EllipsisLoc = SourceLocation();
2750 }
2751
2752 auto *BaseDecl =
2753 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2754 // C++ [class.derived.general]p2:
2755 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2756 // that is not an incompletely defined class; any cv-qualifiers are
2757 // ignored.
2758 if (BaseDecl) {
2759 // C++ [class.union.general]p4:
2760 // [...] A union shall not be used as a base class.
2761 if (BaseDecl->isUnion()) {
2762 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2763 return nullptr;
2764 }
2765
2766 if (BaseType.hasQualifiers()) {
2767 std::string Quals =
2768 BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
2769 Diag(BaseLoc, diag::warn_qual_base_type)
2770 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;
2771 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
2772 }
2773
2774 // For the MS ABI, propagate DLL attributes to base class templates.
2775 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2776 Context.getTargetInfo().getTriple().isPS()) {
2777 if (Attr *ClassAttr = getDLLAttr(Class)) {
2778 if (auto *BaseSpec =
2779 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2780 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2781 BaseLoc);
2782 }
2783 }
2784 }
2785
2786 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2787 SpecifierRange)) {
2788 Class->setInvalidDecl();
2789 return nullptr;
2790 }
2791
2792 BaseDecl = BaseDecl->getDefinition();
2793 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2794
2795 // Microsoft docs say:
2796 // "If a base-class has a code_seg attribute, derived classes must have the
2797 // same attribute."
2798 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2799 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2800 if ((DerivedCSA || BaseCSA) &&
2801 (!BaseCSA || !DerivedCSA ||
2802 BaseCSA->getName() != DerivedCSA->getName())) {
2803 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2804 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2805 << BaseDecl;
2806 return nullptr;
2807 }
2808
2809 // A class which contains a flexible array member is not suitable for use as
2810 // a base class:
2811 // - If the layout determines that a base comes before another base,
2812 // the flexible array member would index into the subsequent base.
2813 // - If the layout determines that base comes before the derived class,
2814 // the flexible array member would index into the derived class.
2815 if (BaseDecl->hasFlexibleArrayMember()) {
2816 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2817 << BaseDecl->getDeclName();
2818 return nullptr;
2819 }
2820
2821 // C++ [class]p3:
2822 // If a class is marked final and it appears as a base-type-specifier in
2823 // base-clause, the program is ill-formed.
2824 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2825 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2826 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2827 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2828 << BaseDecl->getDeclName() << FA->getRange();
2829 return nullptr;
2830 }
2831
2832 // If the base class is invalid the derived class is as well.
2833 if (BaseDecl->isInvalidDecl())
2834 Class->setInvalidDecl();
2835 } else if (BaseType->isDependentType()) {
2836 // Make sure that we don't make an ill-formed AST where the type of the
2837 // Class is non-dependent and its attached base class specifier is an
2838 // dependent type, which violates invariants in many clang code paths (e.g.
2839 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2840 // explicitly mark the Class decl invalid. The diagnostic was already
2841 // emitted.
2842 if (!Class->isDependentContext())
2843 Class->setInvalidDecl();
2844 } else {
2845 // The base class is some non-dependent non-class type.
2846 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2847 return nullptr;
2848 }
2849
2850 // In HLSL, unspecified class access is public rather than private.
2851 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2852 Access == AS_none)
2853 Access = AS_public;
2854
2855 // Create the base specifier.
2856 return new (Context) CXXBaseSpecifier(
2857 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2858 Access, TInfo, EllipsisLoc);
2859}
2860
2862 const ParsedAttributesView &Attributes,
2863 bool Virtual, AccessSpecifier Access,
2864 ParsedType basetype, SourceLocation BaseLoc,
2865 SourceLocation EllipsisLoc) {
2866 if (!classdecl)
2867 return true;
2868
2869 AdjustDeclIfTemplate(classdecl);
2870 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2871 if (!Class)
2872 return true;
2873
2874 // We haven't yet attached the base specifiers.
2875 Class->setIsParsingBaseSpecifiers();
2876
2877 // We do not support any C++11 attributes on base-specifiers yet.
2878 // Diagnose any attributes we see.
2879 for (const ParsedAttr &AL : Attributes) {
2880 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2881 continue;
2882 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2884 else
2885 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2886 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2887 }
2888
2889 TypeSourceInfo *TInfo = nullptr;
2890 GetTypeFromParser(basetype, &TInfo);
2891
2892 if (EllipsisLoc.isInvalid() &&
2893 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2895 return true;
2896
2897 // C++ [class.union.general]p4:
2898 // [...] A union shall not have base classes.
2899 if (Class->isUnion()) {
2900 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2901 << SpecifierRange;
2902 return true;
2903 }
2904
2905 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2906 Virtual, Access, TInfo,
2907 EllipsisLoc))
2908 return BaseSpec;
2909
2910 Class->setInvalidDecl();
2911 return true;
2912}
2913
2914/// Use small set to collect indirect bases. As this is only used
2915/// locally, there's no need to abstract the small size parameter.
2917
2918/// Recursively add the bases of Type. Don't add Type itself.
2919static void
2921 const QualType &Type)
2922{
2923 // Even though the incoming type is a base, it might not be
2924 // a class -- it could be a template parm, for instance.
2925 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2926 // Iterate over its bases.
2927 for (const auto &BaseSpec : Decl->bases()) {
2928 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2929 .getUnqualifiedType();
2930 if (Set.insert(Base).second)
2931 // If we've not already seen it, recurse.
2932 NoteIndirectBases(Context, Set, Base);
2933 }
2934 }
2935}
2936
2939 if (Bases.empty())
2940 return false;
2941
2942 // Used to keep track of which base types we have already seen, so
2943 // that we can properly diagnose redundant direct base types. Note
2944 // that the key is always the unqualified canonical type of the base
2945 // class.
2946 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2947
2948 // Used to track indirect bases so we can see if a direct base is
2949 // ambiguous.
2950 IndirectBaseSet IndirectBaseTypes;
2951
2952 // Copy non-redundant base specifiers into permanent storage.
2953 unsigned NumGoodBases = 0;
2954 bool Invalid = false;
2955 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2956 QualType NewBaseType
2957 = Context.getCanonicalType(Bases[idx]->getType());
2958 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2959
2960 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2961 if (KnownBase) {
2962 // C++ [class.mi]p3:
2963 // A class shall not be specified as a direct base class of a
2964 // derived class more than once.
2965 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2966 << KnownBase->getType() << Bases[idx]->getSourceRange();
2967
2968 // Delete the duplicate base class specifier; we're going to
2969 // overwrite its pointer later.
2970 Context.Deallocate(Bases[idx]);
2971
2972 Invalid = true;
2973 } else {
2974 // Okay, add this new base class.
2975 KnownBase = Bases[idx];
2976 Bases[NumGoodBases++] = Bases[idx];
2977
2978 if (NewBaseType->isDependentType())
2979 continue;
2980 // Note this base's direct & indirect bases, if there could be ambiguity.
2981 if (Bases.size() > 1)
2982 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2983
2984 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
2985 if (Class->isInterface() &&
2986 (!RD->isInterfaceLike() ||
2987 KnownBase->getAccessSpecifier() != AS_public)) {
2988 // The Microsoft extension __interface does not permit bases that
2989 // are not themselves public interfaces.
2990 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2991 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2992 << RD->getSourceRange();
2993 Invalid = true;
2994 }
2995 if (RD->hasAttr<WeakAttr>())
2996 Class->addAttr(WeakAttr::CreateImplicit(Context));
2997 }
2998 }
2999 }
3000
3001 // Attach the remaining base class specifiers to the derived class.
3002 Class->setBases(Bases.data(), NumGoodBases);
3003
3004 // Check that the only base classes that are duplicate are virtual.
3005 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3006 // Check whether this direct base is inaccessible due to ambiguity.
3007 QualType BaseType = Bases[idx]->getType();
3008
3009 // Skip all dependent types in templates being used as base specifiers.
3010 // Checks below assume that the base specifier is a CXXRecord.
3011 if (BaseType->isDependentType())
3012 continue;
3013
3014 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3015 .getUnqualifiedType();
3016
3017 if (IndirectBaseTypes.count(CanonicalBase)) {
3018 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3019 /*DetectVirtual=*/true);
3020 bool found
3021 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3022 assert(found);
3023 (void)found;
3024
3025 if (Paths.isAmbiguous(CanonicalBase))
3026 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3027 << BaseType << getAmbiguousPathsDisplayString(Paths)
3028 << Bases[idx]->getSourceRange();
3029 else
3030 assert(Bases[idx]->isVirtual());
3031 }
3032
3033 // Delete the base class specifier, since its data has been copied
3034 // into the CXXRecordDecl.
3035 Context.Deallocate(Bases[idx]);
3036 }
3037
3038 return Invalid;
3039}
3040
3043 if (!ClassDecl || Bases.empty())
3044 return;
3045
3046 AdjustDeclIfTemplate(ClassDecl);
3047 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3048}
3049
3051 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3052 if (!getLangOpts().CPlusPlus)
3053 return false;
3054
3055 if (!Base || !Derived)
3056 return false;
3057
3058 // If either the base or the derived type is invalid, don't try to
3059 // check whether one is derived from the other.
3060 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3061 return false;
3062
3063 // FIXME: In a modules build, do we need the entire path to be visible for us
3064 // to be able to use the inheritance relationship?
3065 if (!isCompleteType(Loc, Context.getCanonicalTagType(Derived)) &&
3066 !Derived->isBeingDefined())
3067 return false;
3068
3069 return Derived->isDerivedFrom(Base, Paths);
3070}
3071
3074 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3075 /*DetectVirtual=*/false);
3076 return IsDerivedFrom(Loc, Derived, Base, Paths);
3077}
3078
3080 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3081 /*DetectVirtual=*/false);
3082 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3083 Base->getAsCXXRecordDecl(), Paths);
3084}
3085
3087 CXXBasePaths &Paths) {
3088 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),
3089 Base->getAsCXXRecordDecl(), Paths);
3090}
3091
3092static void BuildBasePathArray(const CXXBasePath &Path,
3093 CXXCastPath &BasePathArray) {
3094 // We first go backward and check if we have a virtual base.
3095 // FIXME: It would be better if CXXBasePath had the base specifier for
3096 // the nearest virtual base.
3097 unsigned Start = 0;
3098 for (unsigned I = Path.size(); I != 0; --I) {
3099 if (Path[I - 1].Base->isVirtual()) {
3100 Start = I - 1;
3101 break;
3102 }
3103 }
3104
3105 // Now add all bases.
3106 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3107 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3108}
3109
3110
3112 CXXCastPath &BasePathArray) {
3113 assert(BasePathArray.empty() && "Base path array must be empty!");
3114 assert(Paths.isRecordingPaths() && "Must record paths!");
3115 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3116}
3117
3118bool
3120 unsigned InaccessibleBaseID,
3121 unsigned AmbiguousBaseConvID,
3122 SourceLocation Loc, SourceRange Range,
3123 DeclarationName Name,
3124 CXXCastPath *BasePath,
3125 bool IgnoreAccess) {
3126 // First, determine whether the path from Derived to Base is
3127 // ambiguous. This is slightly more expensive than checking whether
3128 // the Derived to Base conversion exists, because here we need to
3129 // explore multiple paths to determine if there is an ambiguity.
3130 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3131 /*DetectVirtual=*/false);
3132 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3133 if (!DerivationOkay)
3134 return true;
3135
3136 const CXXBasePath *Path = nullptr;
3137 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3138 Path = &Paths.front();
3139
3140 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3141 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3142 // user to access such bases.
3143 if (!Path && getLangOpts().MSVCCompat) {
3144 for (const CXXBasePath &PossiblePath : Paths) {
3145 if (PossiblePath.size() == 1) {
3146 Path = &PossiblePath;
3147 if (AmbiguousBaseConvID)
3148 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3149 << Base << Derived << Range;
3150 break;
3151 }
3152 }
3153 }
3154
3155 if (Path) {
3156 if (!IgnoreAccess) {
3157 // Check that the base class can be accessed.
3158 switch (
3159 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3160 case AR_inaccessible:
3161 return true;
3162 case AR_accessible:
3163 case AR_dependent:
3164 case AR_delayed:
3165 break;
3166 }
3167 }
3168
3169 // Build a base path if necessary.
3170 if (BasePath)
3171 ::BuildBasePathArray(*Path, *BasePath);
3172 return false;
3173 }
3174
3175 if (AmbiguousBaseConvID) {
3176 // We know that the derived-to-base conversion is ambiguous, and
3177 // we're going to produce a diagnostic. Perform the derived-to-base
3178 // search just one more time to compute all of the possible paths so
3179 // that we can print them out. This is more expensive than any of
3180 // the previous derived-to-base checks we've done, but at this point
3181 // performance isn't as much of an issue.
3182 Paths.clear();
3183 Paths.setRecordingPaths(true);
3184 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3185 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3186 (void)StillOkay;
3187
3188 // Build up a textual representation of the ambiguous paths, e.g.,
3189 // D -> B -> A, that will be used to illustrate the ambiguous
3190 // conversions in the diagnostic. We only print one of the paths
3191 // to each base class subobject.
3192 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3193
3194 Diag(Loc, AmbiguousBaseConvID)
3195 << Derived << Base << PathDisplayStr << Range << Name;
3196 }
3197 return true;
3198}
3199
3200bool
3202 SourceLocation Loc, SourceRange Range,
3203 CXXCastPath *BasePath,
3204 bool IgnoreAccess) {
3206 Derived, Base, diag::err_upcast_to_inaccessible_base,
3207 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3208 BasePath, IgnoreAccess);
3209}
3210
3212 std::string PathDisplayStr;
3213 std::set<unsigned> DisplayedPaths;
3214 for (const CXXBasePath &Path : Paths) {
3215 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
3216 // We haven't displayed a path to this particular base
3217 // class subobject yet.
3218 PathDisplayStr += "\n ";
3219 PathDisplayStr += QualType(Context.getCanonicalTagType(Paths.getOrigin()))
3220 .getAsString();
3221 for (const CXXBasePathElement &Element : Path)
3222 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3223 }
3224 }
3225
3226 return PathDisplayStr;
3227}
3228
3229//===----------------------------------------------------------------------===//
3230// C++ class member Handling
3231//===----------------------------------------------------------------------===//
3232
3234 SourceLocation ColonLoc,
3235 const ParsedAttributesView &Attrs) {
3236 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3238 ASLoc, ColonLoc);
3239 CurContext->addHiddenDecl(ASDecl);
3240 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3241}
3242
3244 if (D->isInvalidDecl())
3245 return;
3246
3247 // We only care about "override" and "final" declarations.
3248 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3249 return;
3250
3251 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3252
3253 // We can't check dependent instance methods.
3254 if (MD && MD->isInstance() &&
3255 (MD->getParent()->hasAnyDependentBases() ||
3256 MD->getType()->isDependentType()))
3257 return;
3258
3259 if (MD && !MD->isVirtual()) {
3260 // If we have a non-virtual method, check if it hides a virtual method.
3261 // (In that case, it's most likely the method has the wrong type.)
3262 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3263 FindHiddenVirtualMethods(MD, OverloadedMethods);
3264
3265 if (!OverloadedMethods.empty()) {
3266 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3267 Diag(OA->getLocation(),
3268 diag::override_keyword_hides_virtual_member_function)
3269 << "override" << (OverloadedMethods.size() > 1);
3270 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3271 Diag(FA->getLocation(),
3272 diag::override_keyword_hides_virtual_member_function)
3273 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3274 << (OverloadedMethods.size() > 1);
3275 }
3276 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3277 MD->setInvalidDecl();
3278 return;
3279 }
3280 // Fall through into the general case diagnostic.
3281 // FIXME: We might want to attempt typo correction here.
3282 }
3283
3284 if (!MD || !MD->isVirtual()) {
3285 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3286 Diag(OA->getLocation(),
3287 diag::override_keyword_only_allowed_on_virtual_member_functions)
3288 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3289 D->dropAttr<OverrideAttr>();
3290 }
3291 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3292 Diag(FA->getLocation(),
3293 diag::override_keyword_only_allowed_on_virtual_member_functions)
3294 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3295 << FixItHint::CreateRemoval(FA->getLocation());
3296 D->dropAttr<FinalAttr>();
3297 }
3298 return;
3299 }
3300
3301 // C++11 [class.virtual]p5:
3302 // If a function is marked with the virt-specifier override and
3303 // does not override a member function of a base class, the program is
3304 // ill-formed.
3305 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3306 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3307 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3308 << MD->getDeclName();
3309}
3310
3312 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3313 return;
3314 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3315 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3316 return;
3317
3318 SourceLocation Loc = MD->getLocation();
3319 SourceLocation SpellingLoc = Loc;
3320 if (getSourceManager().isMacroArgExpansion(Loc))
3321 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3322 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3323 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3324 return;
3325
3326 if (MD->size_overridden_methods() > 0) {
3327 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3328 unsigned DiagID =
3329 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3330 ? DiagInconsistent
3331 : DiagSuggest;
3332 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3333 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3334 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3335 };
3336 if (isa<CXXDestructorDecl>(MD))
3337 EmitDiag(
3338 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3339 diag::warn_suggest_destructor_marked_not_override_overriding);
3340 else
3341 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3342 diag::warn_suggest_function_marked_not_override_overriding);
3343 }
3344}
3345
3347 const CXXMethodDecl *Old) {
3348 FinalAttr *FA = Old->getAttr<FinalAttr>();
3349 if (!FA)
3350 return false;
3351
3352 Diag(New->getLocation(), diag::err_final_function_overridden)
3353 << New->getDeclName()
3354 << FA->isSpelledAsSealed();
3355 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3356 return true;
3357}
3358
3360 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3361 // FIXME: Destruction of ObjC lifetime types has side-effects.
3362 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3363 return !RD->isCompleteDefinition() ||
3364 !RD->hasTrivialDefaultConstructor() ||
3365 !RD->hasTrivialDestructor();
3366 return false;
3367}
3368
3369void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3370 DeclarationName FieldName,
3371 const CXXRecordDecl *RD,
3372 bool DeclIsField) {
3373 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3374 return;
3375
3376 // To record a shadowed field in a base
3377 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3378 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3379 CXXBasePath &Path) {
3380 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3381 // Record an ambiguous path directly
3382 if (Bases.find(Base) != Bases.end())
3383 return true;
3384 for (const auto Field : Base->lookup(FieldName)) {
3385 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3386 Field->getAccess() != AS_private) {
3387 assert(Field->getAccess() != AS_none);
3388 assert(Bases.find(Base) == Bases.end());
3389 Bases[Base] = Field;
3390 return true;
3391 }
3392 }
3393 return false;
3394 };
3395
3396 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3397 /*DetectVirtual=*/true);
3398 if (!RD->lookupInBases(FieldShadowed, Paths))
3399 return;
3400
3401 for (const auto &P : Paths) {
3402 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3403 auto It = Bases.find(Base);
3404 // Skip duplicated bases
3405 if (It == Bases.end())
3406 continue;
3407 auto BaseField = It->second;
3408 assert(BaseField->getAccess() != AS_private);
3409 if (AS_none !=
3410 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3411 Diag(Loc, diag::warn_shadow_field)
3412 << FieldName << RD << Base << DeclIsField;
3413 Diag(BaseField->getLocation(), diag::note_shadow_field);
3414 Bases.erase(It);
3415 }
3416 }
3417}
3418
3419template <typename AttrType>
3420inline static bool HasAttribute(const QualType &T) {
3421 if (const TagDecl *TD = T->getAsTagDecl())
3422 return TD->hasAttr<AttrType>();
3423 if (const TypedefType *TDT = T->getAs<TypedefType>())
3424 return TDT->getDecl()->hasAttr<AttrType>();
3425 return false;
3426}
3427
3428static bool IsUnusedPrivateField(const FieldDecl *FD) {
3429 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3430 QualType FieldType = FD->getType();
3431 if (HasAttribute<WarnUnusedAttr>(FieldType))
3432 return true;
3433
3434 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3435 !FD->getParent()->isDependentContext() &&
3436 !HasAttribute<UnusedAttr>(FieldType) &&
3438 }
3439 return false;
3440}
3441
3442NamedDecl *
3444 MultiTemplateParamsArg TemplateParameterLists,
3445 Expr *BitWidth, const VirtSpecifiers &VS,
3446 InClassInitStyle InitStyle) {
3447 const DeclSpec &DS = D.getDeclSpec();
3449 DeclarationName Name = NameInfo.getName();
3450 SourceLocation Loc = NameInfo.getLoc();
3451
3452 // For anonymous bitfields, the location should point to the type.
3453 if (Loc.isInvalid())
3454 Loc = D.getBeginLoc();
3455
3457 assert(!DS.isFriendSpecified());
3458
3459 bool isFunc = D.isDeclarationOfFunction();
3460 const ParsedAttr *MSPropertyAttr =
3462
3463 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3464 // The Microsoft extension __interface only permits public member functions
3465 // and prohibits constructors, destructors, operators, non-public member
3466 // functions, static methods and data members.
3467 unsigned InvalidDecl;
3468 bool ShowDeclName = true;
3469 if (!isFunc &&
3470 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3471 InvalidDecl = 0;
3472 else if (!isFunc)
3473 InvalidDecl = 1;
3474 else if (AS != AS_public)
3475 InvalidDecl = 2;
3477 InvalidDecl = 3;
3478 else switch (Name.getNameKind()) {
3480 InvalidDecl = 4;
3481 ShowDeclName = false;
3482 break;
3483
3485 InvalidDecl = 5;
3486 ShowDeclName = false;
3487 break;
3488
3491 InvalidDecl = 6;
3492 break;
3493
3494 default:
3495 InvalidDecl = 0;
3496 break;
3497 }
3498
3499 if (InvalidDecl) {
3500 if (ShowDeclName)
3501 Diag(Loc, diag::err_invalid_member_in_interface)
3502 << (InvalidDecl-1) << Name;
3503 else
3504 Diag(Loc, diag::err_invalid_member_in_interface)
3505 << (InvalidDecl-1) << "";
3506 return nullptr;
3507 }
3508 }
3509
3510 // C++ 9.2p6: A member shall not be declared to have automatic storage
3511 // duration (auto, register) or with the extern storage-class-specifier.
3512 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3513 // data members and cannot be applied to names declared const or static,
3514 // and cannot be applied to reference members.
3515 switch (DS.getStorageClassSpec()) {
3519 break;
3521 if (isFunc) {
3522 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3523
3524 // FIXME: It would be nicer if the keyword was ignored only for this
3525 // declarator. Otherwise we could get follow-up errors.
3527 }
3528 break;
3529 default:
3531 diag::err_storageclass_invalid_for_member);
3533 break;
3534 }
3535
3536 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3538 !isFunc && TemplateParameterLists.empty();
3539
3540 if (DS.hasConstexprSpecifier() && isInstField) {
3542 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3543 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3544 if (InitStyle == ICIS_NoInit) {
3545 B << 0 << 0;
3547 B << FixItHint::CreateRemoval(ConstexprLoc);
3548 else {
3549 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3551 const char *PrevSpec;
3552 unsigned DiagID;
3553 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3554 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3555 (void)Failed;
3556 assert(!Failed && "Making a constexpr member const shouldn't fail");
3557 }
3558 } else {
3559 B << 1;
3560 const char *PrevSpec;
3561 unsigned DiagID;
3563 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3564 Context.getPrintingPolicy())) {
3566 "This is the only DeclSpec that should fail to be applied");
3567 B << 1;
3568 } else {
3569 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3570 isInstField = false;
3571 }
3572 }
3573 }
3574
3576 if (isInstField) {
3577 CXXScopeSpec &SS = D.getCXXScopeSpec();
3578
3579 // Data members must have identifiers for names.
3580 if (!Name.isIdentifier()) {
3581 Diag(Loc, diag::err_bad_variable_name)
3582 << Name;
3583 return nullptr;
3584 }
3585
3588 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3589 << II
3593 D.SetIdentifier(II, Loc);
3594 }
3595
3596 if (SS.isSet() && !SS.isInvalid()) {
3597 // The user provided a superfluous scope specifier inside a class
3598 // definition:
3599 //
3600 // class X {
3601 // int X::member;
3602 // };
3603 if (DeclContext *DC = computeDeclContext(SS, false)) {
3604 TemplateIdAnnotation *TemplateId =
3606 ? D.getName().TemplateId
3607 : nullptr;
3609 TemplateId,
3610 /*IsMemberSpecialization=*/false);
3611 } else {
3612 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3613 << Name << SS.getRange();
3614 }
3615 SS.clear();
3616 }
3617
3618 if (MSPropertyAttr) {
3620 BitWidth, InitStyle, AS, *MSPropertyAttr);
3621 if (!Member)
3622 return nullptr;
3623 isInstField = false;
3624 } else {
3626 BitWidth, InitStyle, AS);
3627 if (!Member)
3628 return nullptr;
3629 }
3630
3631 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3632 } else {
3633 Member = HandleDeclarator(S, D, TemplateParameterLists);
3634 if (!Member)
3635 return nullptr;
3636
3637 // Non-instance-fields can't have a bitfield.
3638 if (BitWidth) {
3639 if (Member->isInvalidDecl()) {
3640 // don't emit another diagnostic.
3642 // C++ 9.6p3: A bit-field shall not be a static member.
3643 // "static member 'A' cannot be a bit-field"
3644 Diag(Loc, diag::err_static_not_bitfield)
3645 << Name << BitWidth->getSourceRange();
3646 } else if (isa<TypedefDecl>(Member)) {
3647 // "typedef member 'x' cannot be a bit-field"
3648 Diag(Loc, diag::err_typedef_not_bitfield)
3649 << Name << BitWidth->getSourceRange();
3650 } else {
3651 // A function typedef ("typedef int f(); f a;").
3652 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3653 Diag(Loc, diag::err_not_integral_type_bitfield)
3654 << Name << cast<ValueDecl>(Member)->getType()
3655 << BitWidth->getSourceRange();
3656 }
3657
3658 BitWidth = nullptr;
3659 Member->setInvalidDecl();
3660 }
3661
3662 NamedDecl *NonTemplateMember = Member;
3663 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3664 NonTemplateMember = FunTmpl->getTemplatedDecl();
3665 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3666 NonTemplateMember = VarTmpl->getTemplatedDecl();
3667
3668 Member->setAccess(AS);
3669
3670 // If we have declared a member function template or static data member
3671 // template, set the access of the templated declaration as well.
3672 if (NonTemplateMember != Member)
3673 NonTemplateMember->setAccess(AS);
3674
3675 // C++ [temp.deduct.guide]p3:
3676 // A deduction guide [...] for a member class template [shall be
3677 // declared] with the same access [as the template].
3678 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3679 auto *TD = DG->getDeducedTemplate();
3680 // Access specifiers are only meaningful if both the template and the
3681 // deduction guide are from the same scope.
3682 if (AS != TD->getAccess() &&
3683 TD->getDeclContext()->getRedeclContext()->Equals(
3684 DG->getDeclContext()->getRedeclContext())) {
3685 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3686 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3687 << TD->getAccess();
3688 const AccessSpecDecl *LastAccessSpec = nullptr;
3689 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3690 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3691 LastAccessSpec = AccessSpec;
3692 }
3693 assert(LastAccessSpec && "differing access with no access specifier");
3694 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3695 << AS;
3696 }
3697 }
3698 }
3699
3700 if (VS.isOverrideSpecified())
3701 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3702 if (VS.isFinalSpecified())
3703 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3705 ? FinalAttr::Keyword_sealed
3706 : FinalAttr::Keyword_final));
3707
3708 if (VS.getLastLocation().isValid()) {
3709 // Update the end location of a method that has a virt-specifiers.
3710 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3711 MD->setRangeEnd(VS.getLastLocation());
3712 }
3713
3715
3716 assert((Name || isInstField) && "No identifier for non-field ?");
3717
3718 if (isInstField) {
3720 FieldCollector->Add(FD);
3721
3722 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
3724 // Remember all explicit private FieldDecls that have a name, no side
3725 // effects and are not part of a dependent type declaration.
3726 UnusedPrivateFields.insert(FD);
3727 }
3728 }
3729
3730 return Member;
3731}
3732
3733namespace {
3734 class UninitializedFieldVisitor
3735 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3736 Sema &S;
3737 // List of Decls to generate a warning on. Also remove Decls that become
3738 // initialized.
3739 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3740 // List of base classes of the record. Classes are removed after their
3741 // initializers.
3742 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3743 // Vector of decls to be removed from the Decl set prior to visiting the
3744 // nodes. These Decls may have been initialized in the prior initializer.
3746 // If non-null, add a note to the warning pointing back to the constructor.
3748 // Variables to hold state when processing an initializer list. When
3749 // InitList is true, special case initialization of FieldDecls matching
3750 // InitListFieldDecl.
3751 bool InitList;
3752 FieldDecl *InitListFieldDecl;
3753 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3754
3755 public:
3757 UninitializedFieldVisitor(Sema &S,
3758 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3759 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3760 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3761 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3762
3763 // Returns true if the use of ME is not an uninitialized use.
3764 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3765 bool CheckReferenceOnly) {
3767 bool ReferenceField = false;
3768 while (ME) {
3769 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3770 if (!FD)
3771 return false;
3772 Fields.push_back(FD);
3773 if (FD->getType()->isReferenceType())
3774 ReferenceField = true;
3775 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3776 }
3777
3778 // Binding a reference to an uninitialized field is not an
3779 // uninitialized use.
3780 if (CheckReferenceOnly && !ReferenceField)
3781 return true;
3782
3783 // Discard the first field since it is the field decl that is being
3784 // initialized.
3785 auto UsedFields = llvm::drop_begin(llvm::reverse(Fields));
3786 auto UsedIter = UsedFields.begin();
3787 const auto UsedEnd = UsedFields.end();
3788
3789 for (const unsigned Orig : InitFieldIndex) {
3790 if (UsedIter == UsedEnd)
3791 break;
3792 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3793 if (UsedIndex < Orig)
3794 return true;
3795 if (UsedIndex > Orig)
3796 break;
3797 ++UsedIter;
3798 }
3799
3800 return false;
3801 }
3802
3803 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3804 bool AddressOf) {
3806 return;
3807
3808 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3809 // or union.
3810 MemberExpr *FieldME = ME;
3811
3812 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3813
3814 Expr *Base = ME;
3815 while (MemberExpr *SubME =
3816 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3817
3818 if (isa<VarDecl>(SubME->getMemberDecl()))
3819 return;
3820
3821 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3822 if (!FD->isAnonymousStructOrUnion())
3823 FieldME = SubME;
3824
3825 if (!FieldME->getType().isPODType(S.Context))
3826 AllPODFields = false;
3827
3828 Base = SubME->getBase();
3829 }
3830
3831 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3832 Visit(Base);
3833 return;
3834 }
3835
3836 if (AddressOf && AllPODFields)
3837 return;
3838
3839 ValueDecl* FoundVD = FieldME->getMemberDecl();
3840
3841 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3842 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3843 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3844 }
3845
3846 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3847 QualType T = BaseCast->getType();
3848 if (T->isPointerType() &&
3849 BaseClasses.count(T->getPointeeType())) {
3850 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3851 << T->getPointeeType() << FoundVD;
3852 }
3853 }
3854 }
3855
3856 if (!Decls.count(FoundVD))
3857 return;
3858
3859 const bool IsReference = FoundVD->getType()->isReferenceType();
3860
3861 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3862 // Special checking for initializer lists.
3863 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3864 return;
3865 }
3866 } else {
3867 // Prevent double warnings on use of unbounded references.
3868 if (CheckReferenceOnly && !IsReference)
3869 return;
3870 }
3871
3872 unsigned diag = IsReference
3873 ? diag::warn_reference_field_is_uninit
3874 : diag::warn_field_is_uninit;
3875 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3876 if (Constructor)
3877 S.Diag(Constructor->getLocation(),
3878 diag::note_uninit_in_this_constructor)
3879 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3880
3881 }
3882
3883 void HandleValue(Expr *E, bool AddressOf) {
3884 E = E->IgnoreParens();
3885
3886 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3887 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3888 AddressOf /*AddressOf*/);
3889 return;
3890 }
3891
3892 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3893 Visit(CO->getCond());
3894 HandleValue(CO->getTrueExpr(), AddressOf);
3895 HandleValue(CO->getFalseExpr(), AddressOf);
3896 return;
3897 }
3898
3899 if (BinaryConditionalOperator *BCO =
3900 dyn_cast<BinaryConditionalOperator>(E)) {
3901 Visit(BCO->getCond());
3902 HandleValue(BCO->getFalseExpr(), AddressOf);
3903 return;
3904 }
3905
3906 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3907 HandleValue(OVE->getSourceExpr(), AddressOf);
3908 return;
3909 }
3910
3911 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3912 switch (BO->getOpcode()) {
3913 default:
3914 break;
3915 case(BO_PtrMemD):
3916 case(BO_PtrMemI):
3917 HandleValue(BO->getLHS(), AddressOf);
3918 Visit(BO->getRHS());
3919 return;
3920 case(BO_Comma):
3921 Visit(BO->getLHS());
3922 HandleValue(BO->getRHS(), AddressOf);
3923 return;
3924 }
3925 }
3926
3927 Visit(E);
3928 }
3929
3930 void CheckInitListExpr(InitListExpr *ILE) {
3931 InitFieldIndex.push_back(0);
3932 for (auto *Child : ILE->children()) {
3933 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3934 CheckInitListExpr(SubList);
3935 } else {
3936 Visit(Child);
3937 }
3938 ++InitFieldIndex.back();
3939 }
3940 InitFieldIndex.pop_back();
3941 }
3942
3943 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3944 FieldDecl *Field, const Type *BaseClass) {
3945 // Remove Decls that may have been initialized in the previous
3946 // initializer.
3947 for (ValueDecl* VD : DeclsToRemove)
3948 Decls.erase(VD);
3949 DeclsToRemove.clear();
3950
3951 Constructor = FieldConstructor;
3952 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3953
3954 if (ILE && Field) {
3955 InitList = true;
3956 InitListFieldDecl = Field;
3957 InitFieldIndex.clear();
3958 CheckInitListExpr(ILE);
3959 } else {
3960 InitList = false;
3961 Visit(E);
3962 }
3963
3964 if (Field)
3965 Decls.erase(Field);
3966 if (BaseClass)
3967 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3968 }
3969
3970 void VisitMemberExpr(MemberExpr *ME) {
3971 // All uses of unbounded reference fields will warn.
3972 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3973 }
3974
3975 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3976 if (E->getCastKind() == CK_LValueToRValue) {
3977 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3978 return;
3979 }
3980
3981 Inherited::VisitImplicitCastExpr(E);
3982 }
3983
3984 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3985 if (E->getConstructor()->isCopyConstructor()) {
3986 Expr *ArgExpr = E->getArg(0);
3987 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3988 if (ILE->getNumInits() == 1)
3989 ArgExpr = ILE->getInit(0);
3990 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3991 if (ICE->getCastKind() == CK_NoOp)
3992 ArgExpr = ICE->getSubExpr();
3993 HandleValue(ArgExpr, false /*AddressOf*/);
3994 return;
3995 }
3996 Inherited::VisitCXXConstructExpr(E);
3997 }
3998
3999 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4000 Expr *Callee = E->getCallee();
4001 if (isa<MemberExpr>(Callee)) {
4002 HandleValue(Callee, false /*AddressOf*/);
4003 for (auto *Arg : E->arguments())
4004 Visit(Arg);
4005 return;
4006 }
4007
4008 Inherited::VisitCXXMemberCallExpr(E);
4009 }
4010
4011 void VisitCallExpr(CallExpr *E) {
4012 // Treat std::move as a use.
4013 if (E->isCallToStdMove()) {
4014 HandleValue(E->getArg(0), /*AddressOf=*/false);
4015 return;
4016 }
4017
4018 Inherited::VisitCallExpr(E);
4019 }
4020
4021 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4022 Expr *Callee = E->getCallee();
4023
4024 if (isa<UnresolvedLookupExpr>(Callee))
4025 return Inherited::VisitCXXOperatorCallExpr(E);
4026
4027 Visit(Callee);
4028 for (auto *Arg : E->arguments())
4029 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4030 }
4031
4032 void VisitBinaryOperator(BinaryOperator *E) {
4033 // If a field assignment is detected, remove the field from the
4034 // uninitiailized field set.
4035 if (E->getOpcode() == BO_Assign)
4036 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4037 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4038 if (!FD->getType()->isReferenceType())
4039 DeclsToRemove.push_back(FD);
4040
4041 if (E->isCompoundAssignmentOp()) {
4042 HandleValue(E->getLHS(), false /*AddressOf*/);
4043 Visit(E->getRHS());
4044 return;
4045 }
4046
4047 Inherited::VisitBinaryOperator(E);
4048 }
4049
4050 void VisitUnaryOperator(UnaryOperator *E) {
4051 if (E->isIncrementDecrementOp()) {
4052 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4053 return;
4054 }
4055 if (E->getOpcode() == UO_AddrOf) {
4056 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4057 HandleValue(ME->getBase(), true /*AddressOf*/);
4058 return;
4059 }
4060 }
4061
4062 Inherited::VisitUnaryOperator(E);
4063 }
4064 };
4065
4066 // Diagnose value-uses of fields to initialize themselves, e.g.
4067 // foo(foo)
4068 // where foo is not also a parameter to the constructor.
4069 // Also diagnose across field uninitialized use such as
4070 // x(y), y(x)
4071 // TODO: implement -Wuninitialized and fold this into that framework.
4072 static void DiagnoseUninitializedFields(
4073 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4074
4075 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4076 Constructor->getLocation())) {
4077 return;
4078 }
4079
4080 if (Constructor->isInvalidDecl())
4081 return;
4082
4083 const CXXRecordDecl *RD = Constructor->getParent();
4084
4085 if (RD->isDependentContext())
4086 return;
4087
4088 // Holds fields that are uninitialized.
4089 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4090
4091 // At the beginning, all fields are uninitialized.
4092 for (auto *I : RD->decls()) {
4093 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4094 UninitializedFields.insert(FD);
4095 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4096 UninitializedFields.insert(IFD->getAnonField());
4097 }
4098 }
4099
4100 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4101 for (const auto &I : RD->bases())
4102 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4103
4104 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4105 return;
4106
4107 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4108 UninitializedFields,
4109 UninitializedBaseClasses);
4110
4111 for (const auto *FieldInit : Constructor->inits()) {
4112 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4113 break;
4114
4115 Expr *InitExpr = FieldInit->getInit();
4116 if (!InitExpr)
4117 continue;
4118
4119 if (CXXDefaultInitExpr *Default =
4120 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4121 InitExpr = Default->getExpr();
4122 if (!InitExpr)
4123 continue;
4124 // In class initializers will point to the constructor.
4125 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4126 FieldInit->getAnyMember(),
4127 FieldInit->getBaseClass());
4128 } else {
4129 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4130 FieldInit->getAnyMember(),
4131 FieldInit->getBaseClass());
4132 }
4133 }
4134 }
4135} // namespace
4136
4138 // Create a synthetic function scope to represent the call to the constructor
4139 // that notionally surrounds a use of this initializer.
4141}
4142
4144 if (!D.isFunctionDeclarator())
4145 return;
4146 auto &FTI = D.getFunctionTypeInfo();
4147 if (!FTI.Params)
4148 return;
4149 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4150 FTI.NumParams)) {
4151 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4152 if (ParamDecl->getDeclName())
4153 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4154 }
4155}
4156
4158 return ActOnRequiresClause(ConstraintExpr);
4159}
4160
4162 if (ConstraintExpr.isInvalid())
4163 return ExprError();
4164
4165 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4167 return ExprError();
4168
4169 return ConstraintExpr;
4170}
4171
4173 Expr *InitExpr,
4174 SourceLocation InitLoc) {
4175 InitializedEntity Entity =
4177 InitializationKind Kind =
4180 InitExpr->getBeginLoc(),
4181 InitExpr->getEndLoc())
4182 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4183 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4184 return Seq.Perform(*this, Entity, Kind, InitExpr);
4185}
4186
4188 SourceLocation InitLoc,
4189 ExprResult InitExpr) {
4190 // Pop the notional constructor scope we created earlier.
4191 PopFunctionScopeInfo(nullptr, D);
4192
4193 // Microsoft C++'s property declaration cannot have a default member
4194 // initializer.
4195 if (isa<MSPropertyDecl>(D)) {
4196 D->setInvalidDecl();
4197 return;
4198 }
4199
4200 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4201 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4202 "must set init style when field is created");
4203
4204 if (!InitExpr.isUsable() ||
4206 FD->setInvalidDecl();
4207 ExprResult RecoveryInit =
4208 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());
4209 if (RecoveryInit.isUsable())
4210 FD->setInClassInitializer(RecoveryInit.get());
4211 return;
4212 }
4213
4214 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4215 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr.get(), InitLoc);
4216 // C++11 [class.base.init]p7:
4217 // The initialization of each base and member constitutes a
4218 // full-expression.
4219 if (!InitExpr.isInvalid())
4220 InitExpr = ActOnFinishFullExpr(InitExpr.get(), /*DiscarededValue=*/false);
4221 if (InitExpr.isInvalid()) {
4222 FD->setInvalidDecl();
4223 return;
4224 }
4225 }
4226
4227 FD->setInClassInitializer(InitExpr.get());
4228}
4229
4230/// Find the direct and/or virtual base specifiers that
4231/// correspond to the given base type, for use in base initialization
4232/// within a constructor.
4233static bool FindBaseInitializer(Sema &SemaRef,
4234 CXXRecordDecl *ClassDecl,
4235 QualType BaseType,
4236 const CXXBaseSpecifier *&DirectBaseSpec,
4237 const CXXBaseSpecifier *&VirtualBaseSpec) {
4238 // First, check for a direct base class.
4239 DirectBaseSpec = nullptr;
4240 for (const auto &Base : ClassDecl->bases()) {
4241 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4242 // We found a direct base of this type. That's what we're
4243 // initializing.
4244 DirectBaseSpec = &Base;
4245 break;
4246 }
4247 }
4248
4249 // Check for a virtual base class.
4250 // FIXME: We might be able to short-circuit this if we know in advance that
4251 // there are no virtual bases.
4252 VirtualBaseSpec = nullptr;
4253 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4254 // We haven't found a base yet; search the class hierarchy for a
4255 // virtual base class.
4256 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4257 /*DetectVirtual=*/false);
4258 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4259 SemaRef.Context.getCanonicalTagType(ClassDecl),
4260 BaseType, Paths)) {
4261 for (const CXXBasePath &Path : Paths) {
4262 if (Path.back().Base->isVirtual()) {
4263 VirtualBaseSpec = Path.back().Base;
4264 break;
4265 }
4266 }
4267 }
4268 }
4269
4270 return DirectBaseSpec || VirtualBaseSpec;
4271}
4272
4275 Scope *S,
4276 CXXScopeSpec &SS,
4277 IdentifierInfo *MemberOrBase,
4278 ParsedType TemplateTypeTy,
4279 const DeclSpec &DS,
4280 SourceLocation IdLoc,
4281 Expr *InitList,
4282 SourceLocation EllipsisLoc) {
4283 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4284 DS, IdLoc, InitList,
4285 EllipsisLoc);
4286}
4287
4290 Scope *S,
4291 CXXScopeSpec &SS,
4292 IdentifierInfo *MemberOrBase,
4293 ParsedType TemplateTypeTy,
4294 const DeclSpec &DS,
4295 SourceLocation IdLoc,
4296 SourceLocation LParenLoc,
4297 ArrayRef<Expr *> Args,
4298 SourceLocation RParenLoc,
4299 SourceLocation EllipsisLoc) {
4300 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4301 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4302 DS, IdLoc, List, EllipsisLoc);
4303}
4304
4305namespace {
4306
4307// Callback to only accept typo corrections that can be a valid C++ member
4308// initializer: either a non-static field member or a base class.
4309class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4310public:
4311 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4312 : ClassDecl(ClassDecl) {}
4313
4314 bool ValidateCandidate(const TypoCorrection &candidate) override {
4315 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4316 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4317 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4318 return isa<TypeDecl>(ND);
4319 }
4320 return false;
4321 }
4322
4323 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4324 return std::make_unique<MemInitializerValidatorCCC>(*this);
4325 }
4326
4327private:
4328 CXXRecordDecl *ClassDecl;
4329};
4330
4331}
4332
4334 RecordDecl *ClassDecl,
4335 const IdentifierInfo *Name) {
4336 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4338 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4339 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4341 });
4342 // We did not find a placeholder variable
4343 if (Found == Result.end())
4344 return false;
4345 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4346 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4347 const NamedDecl *ND = *It;
4348 if (ND->getDeclContext() != ND->getDeclContext())
4349 break;
4352 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4353 }
4354 return true;
4355}
4356
4357ValueDecl *
4359 const IdentifierInfo *MemberOrBase) {
4360 ValueDecl *ND = nullptr;
4361 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4363 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4364 if (ND) {
4365 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4366 return nullptr;
4367 break;
4368 }
4369 if (!IsPlaceholder)
4370 return cast<ValueDecl>(D);
4371 ND = cast<ValueDecl>(D);
4372 }
4373 }
4374 return ND;
4375}
4376
4378 CXXScopeSpec &SS,
4379 ParsedType TemplateTypeTy,
4380 IdentifierInfo *MemberOrBase) {
4381 if (SS.getScopeRep() || TemplateTypeTy)
4382 return nullptr;
4383 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4384}
4385
4388 Scope *S,
4389 CXXScopeSpec &SS,
4390 IdentifierInfo *MemberOrBase,
4391 ParsedType TemplateTypeTy,
4392 const DeclSpec &DS,
4393 SourceLocation IdLoc,
4394 Expr *Init,
4395 SourceLocation EllipsisLoc) {
4396 if (!ConstructorD || !Init)
4397 return true;
4398
4399 AdjustDeclIfTemplate(ConstructorD);
4400
4402 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4403 if (!Constructor) {
4404 // The user wrote a constructor initializer on a function that is
4405 // not a C++ constructor. Ignore the error for now, because we may
4406 // have more member initializers coming; we'll diagnose it just
4407 // once in ActOnMemInitializers.
4408 return true;
4409 }
4410
4411 CXXRecordDecl *ClassDecl = Constructor->getParent();
4412
4413 // C++ [class.base.init]p2:
4414 // Names in a mem-initializer-id are looked up in the scope of the
4415 // constructor's class and, if not found in that scope, are looked
4416 // up in the scope containing the constructor's definition.
4417 // [Note: if the constructor's class contains a member with the
4418 // same name as a direct or virtual base class of the class, a
4419 // mem-initializer-id naming the member or base class and composed
4420 // of a single identifier refers to the class member. A
4421 // mem-initializer-id for the hidden base class may be specified
4422 // using a qualified name. ]
4423
4424 // Look for a member, first.
4426 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4427 if (EllipsisLoc.isValid())
4428 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4429 << MemberOrBase
4430 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4431
4432 return BuildMemberInitializer(Member, Init, IdLoc);
4433 }
4434 // It didn't name a member, so see if it names a class.
4435 QualType BaseType;
4436 TypeSourceInfo *TInfo = nullptr;
4437
4438 if (TemplateTypeTy) {
4439 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4440 if (BaseType.isNull())
4441 return true;
4442 } else if (DS.getTypeSpecType() == TST_decltype) {
4443 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4444 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4445 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4446 return true;
4447 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4448 BaseType =
4450 DS.getBeginLoc(), DS.getEllipsisLoc());
4451 } else {
4452 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4453 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4454
4455 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4456 if (!TyD) {
4457 if (R.isAmbiguous()) return true;
4458
4459 // We don't want access-control diagnostics here.
4460 R.suppressDiagnostics();
4461
4462 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4463 bool NotUnknownSpecialization = false;
4464 DeclContext *DC = computeDeclContext(SS, false);
4465 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4466 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4467
4468 if (!NotUnknownSpecialization) {
4469 // When the scope specifier can refer to a member of an unknown
4470 // specialization, we take it as a type name.
4471 BaseType = CheckTypenameType(
4473 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4474 if (BaseType.isNull())
4475 return true;
4476
4477 TInfo = Context.CreateTypeSourceInfo(BaseType);
4480 if (!TL.isNull()) {
4481 TL.setNameLoc(IdLoc);
4484 }
4485
4486 R.clear();
4487 R.setLookupName(MemberOrBase);
4488 }
4489 }
4490
4491 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4492 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4493 auto *TempSpec = cast<TemplateSpecializationType>(
4494 UnqualifiedBase->getCanonicalInjectedSpecializationType(Context));
4495 TemplateName TN = TempSpec->getTemplateName();
4496 for (auto const &Base : ClassDecl->bases()) {
4497 auto BaseTemplate =
4498 Base.getType()->getAs<TemplateSpecializationType>();
4499 if (BaseTemplate &&
4500 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,
4501 /*IgnoreDeduced=*/true)) {
4502 Diag(IdLoc, diag::ext_unqualified_base_class)
4503 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4504 BaseType = Base.getType();
4505 break;
4506 }
4507 }
4508 }
4509 }
4510
4511 // If no results were found, try to correct typos.
4512 TypoCorrection Corr;
4513 MemInitializerValidatorCCC CCC(ClassDecl);
4514 if (R.empty() && BaseType.isNull() &&
4515 (Corr =
4516 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4517 CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {
4519 // We have found a non-static data member with a similar
4520 // name to what was typed; complain and initialize that
4521 // member.
4522 diagnoseTypo(Corr,
4523 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4524 << MemberOrBase << true);
4525 return BuildMemberInitializer(Member, Init, IdLoc);
4526 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4527 const CXXBaseSpecifier *DirectBaseSpec;
4528 const CXXBaseSpecifier *VirtualBaseSpec;
4529 if (FindBaseInitializer(*this, ClassDecl,
4530 Context.getTypeDeclType(Type),
4531 DirectBaseSpec, VirtualBaseSpec)) {
4532 // We have found a direct or virtual base class with a
4533 // similar name to what was typed; complain and initialize
4534 // that base class.
4535 diagnoseTypo(Corr,
4536 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4537 << MemberOrBase << false,
4538 PDiag() /*Suppress note, we provide our own.*/);
4539
4540 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4541 : VirtualBaseSpec;
4542 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4543 << BaseSpec->getType() << BaseSpec->getSourceRange();
4544
4545 TyD = Type;
4546 }
4547 }
4548 }
4549
4550 if (!TyD && BaseType.isNull()) {
4551 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4552 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4553 return true;
4554 }
4555 }
4556
4557 if (BaseType.isNull()) {
4558 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4559
4560 TypeLocBuilder TLB;
4561 // FIXME: This is missing building the UsingType for TyD, if any.
4562 if (const auto *TD = dyn_cast<TagDecl>(TyD)) {
4563 BaseType = Context.getTagType(ElaboratedTypeKeyword::None,
4564 SS.getScopeRep(), TD, /*OwnsTag=*/false);
4565 auto TL = TLB.push<TagTypeLoc>(BaseType);
4567 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4568 TL.setNameLoc(IdLoc);
4569 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TyD)) {
4570 BaseType = Context.getTypedefType(ElaboratedTypeKeyword::None,
4571 SS.getScopeRep(), TN);
4572 TLB.push<TypedefTypeLoc>(BaseType).set(
4573 /*ElaboratedKeywordLoc=*/SourceLocation(),
4574 SS.getWithLocInContext(Context), IdLoc);
4575 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TyD)) {
4576 BaseType = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
4577 SS.getScopeRep(), UD);
4578 TLB.push<UnresolvedUsingTypeLoc>(BaseType).set(
4579 /*ElaboratedKeywordLoc=*/SourceLocation(),
4580 SS.getWithLocInContext(Context), IdLoc);
4581 } else {
4582 // FIXME: What else can appear here?
4583 assert(SS.isEmpty());
4584 BaseType = Context.getTypeDeclType(TyD);
4585 TLB.pushTypeSpec(BaseType).setNameLoc(IdLoc);
4586 }
4587 TInfo = TLB.getTypeSourceInfo(Context, BaseType);
4588 }
4589 }
4590
4591 if (!TInfo)
4592 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4593
4594 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4595}
4596
4599 SourceLocation IdLoc) {
4600 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4601 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4602 assert((DirectMember || IndirectMember) &&
4603 "Member must be a FieldDecl or IndirectFieldDecl");
4604
4606 return true;
4607
4608 if (Member->isInvalidDecl())
4609 return true;
4610
4611 MultiExprArg Args;
4612 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4613 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4614 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4615 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4616 } else {
4617 // Template instantiation doesn't reconstruct ParenListExprs for us.
4618 Args = Init;
4619 }
4620
4621 SourceRange InitRange = Init->getSourceRange();
4622
4623 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4624 // Can't check initialization for a member of dependent type or when
4625 // any of the arguments are type-dependent expressions.
4627 } else {
4628 bool InitList = false;
4629 if (isa<InitListExpr>(Init)) {
4630 InitList = true;
4631 Args = Init;
4632 }
4633
4634 // Initialize the member.
4635 InitializedEntity MemberEntity =
4636 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4637 : InitializedEntity::InitializeMember(IndirectMember,
4638 nullptr);
4639 InitializationKind Kind =
4641 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4642 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4643 InitRange.getEnd());
4644
4645 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4646 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4647 nullptr);
4648 if (!MemberInit.isInvalid()) {
4649 // C++11 [class.base.init]p7:
4650 // The initialization of each base and member constitutes a
4651 // full-expression.
4652 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4653 /*DiscardedValue*/ false);
4654 }
4655
4656 if (MemberInit.isInvalid()) {
4657 // Args were sensible expressions but we couldn't initialize the member
4658 // from them. Preserve them in a RecoveryExpr instead.
4659 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4660 Member->getType())
4661 .get();
4662 if (!Init)
4663 return true;
4664 } else {
4665 Init = MemberInit.get();
4666 }
4667 }
4668
4669 if (DirectMember) {
4670 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4671 InitRange.getBegin(), Init,
4672 InitRange.getEnd());
4673 } else {
4674 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4675 InitRange.getBegin(), Init,
4676 InitRange.getEnd());
4677 }
4678}
4679
4682 CXXRecordDecl *ClassDecl) {
4683 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4684 if (!LangOpts.CPlusPlus11)
4685 return Diag(NameLoc, diag::err_delegating_ctor)
4686 << TInfo->getTypeLoc().getSourceRange();
4687 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4688
4689 bool InitList = true;
4690 MultiExprArg Args = Init;
4691 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4692 InitList = false;
4693 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4694 }
4695
4696 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
4697
4698 SourceRange InitRange = Init->getSourceRange();
4699 // Initialize the object.
4700 InitializedEntity DelegationEntity =
4702 InitializationKind Kind =
4704 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4705 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4706 InitRange.getEnd());
4707 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4708 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4709 Args, nullptr);
4710 if (!DelegationInit.isInvalid()) {
4711 assert((DelegationInit.get()->containsErrors() ||
4712 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4713 "Delegating constructor with no target?");
4714
4715 // C++11 [class.base.init]p7:
4716 // The initialization of each base and member constitutes a
4717 // full-expression.
4718 DelegationInit = ActOnFinishFullExpr(
4719 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4720 }
4721
4722 if (DelegationInit.isInvalid()) {
4723 DelegationInit = CreateRecoveryExpr(InitRange.getBegin(),
4724 InitRange.getEnd(), Args, ClassType);
4725 if (DelegationInit.isInvalid())
4726 return true;
4727 } else {
4728 // If we are in a dependent context, template instantiation will
4729 // perform this type-checking again. Just save the arguments that we
4730 // received in a ParenListExpr.
4731 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4732 // of the information that we have about the base
4733 // initializer. However, deconstructing the ASTs is a dicey process,
4734 // and this approach is far more likely to get the corner cases right.
4735 if (CurContext->isDependentContext())
4736 DelegationInit = Init;
4737 }
4738
4739 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4740 DelegationInit.getAs<Expr>(),
4741 InitRange.getEnd());
4742}
4743
4746 Expr *Init, CXXRecordDecl *ClassDecl,
4747 SourceLocation EllipsisLoc) {
4748 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4749
4750 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4751 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4752 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4753
4754 // C++ [class.base.init]p2:
4755 // [...] Unless the mem-initializer-id names a nonstatic data
4756 // member of the constructor's class or a direct or virtual base
4757 // of that class, the mem-initializer is ill-formed. A
4758 // mem-initializer-list can initialize a base class using any
4759 // name that denotes that base class type.
4760
4761 // We can store the initializers in "as-written" form and delay analysis until
4762 // instantiation if the constructor is dependent. But not for dependent
4763 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4764 bool Dependent = CurContext->isDependentContext() &&
4765 (BaseType->isDependentType() || Init->isTypeDependent());
4766
4767 SourceRange InitRange = Init->getSourceRange();
4768 if (EllipsisLoc.isValid()) {
4769 // This is a pack expansion.
4770 if (!BaseType->containsUnexpandedParameterPack()) {
4771 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4772 << SourceRange(BaseLoc, InitRange.getEnd());
4773
4774 EllipsisLoc = SourceLocation();
4775 }
4776 } else {
4777 // Check for any unexpanded parameter packs.
4778 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4779 return true;
4780
4782 return true;
4783 }
4784
4785 // Check for direct and virtual base classes.
4786 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4787 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4788 if (!Dependent) {
4789 if (declaresSameEntity(ClassDecl, BaseType->getAsCXXRecordDecl()))
4790 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4791
4792 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4793 VirtualBaseSpec);
4794
4795 // C++ [base.class.init]p2:
4796 // Unless the mem-initializer-id names a nonstatic data member of the
4797 // constructor's class or a direct or virtual base of that class, the
4798 // mem-initializer is ill-formed.
4799 if (!DirectBaseSpec && !VirtualBaseSpec) {
4800 // If the class has any dependent bases, then it's possible that
4801 // one of those types will resolve to the same type as
4802 // BaseType. Therefore, just treat this as a dependent base
4803 // class initialization. FIXME: Should we try to check the
4804 // initialization anyway? It seems odd.
4805 if (ClassDecl->hasAnyDependentBases())
4806 Dependent = true;
4807 else
4808 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4809 << BaseType << Context.getCanonicalTagType(ClassDecl)
4810 << BaseTInfo->getTypeLoc().getSourceRange();
4811 }
4812 }
4813
4814 if (Dependent) {
4816
4817 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4818 /*IsVirtual=*/false,
4819 InitRange.getBegin(), Init,
4820 InitRange.getEnd(), EllipsisLoc);
4821 }
4822
4823 // C++ [base.class.init]p2:
4824 // If a mem-initializer-id is ambiguous because it designates both
4825 // a direct non-virtual base class and an inherited virtual base
4826 // class, the mem-initializer is ill-formed.
4827 if (DirectBaseSpec && VirtualBaseSpec)
4828 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4829 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4830
4831 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4832 if (!BaseSpec)
4833 BaseSpec = VirtualBaseSpec;
4834
4835 // Initialize the base.
4836 bool InitList = true;
4837 MultiExprArg Args = Init;
4838 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4839 InitList = false;
4840 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4841 }
4842
4843 InitializedEntity BaseEntity =
4844 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4845 InitializationKind Kind =
4846 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4847 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4848 InitRange.getEnd());
4849 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4850 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4851 if (!BaseInit.isInvalid()) {
4852 // C++11 [class.base.init]p7:
4853 // The initialization of each base and member constitutes a
4854 // full-expression.
4855 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4856 /*DiscardedValue*/ false);
4857 }
4858
4859 if (BaseInit.isInvalid()) {
4860 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4861 Args, BaseType);
4862 if (BaseInit.isInvalid())
4863 return true;
4864 } else {
4865 // If we are in a dependent context, template instantiation will
4866 // perform this type-checking again. Just save the arguments that we
4867 // received in a ParenListExpr.
4868 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4869 // of the information that we have about the base
4870 // initializer. However, deconstructing the ASTs is a dicey process,
4871 // and this approach is far more likely to get the corner cases right.
4872 if (CurContext->isDependentContext())
4873 BaseInit = Init;
4874 }
4875
4876 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4877 BaseSpec->isVirtual(),
4878 InitRange.getBegin(),
4879 BaseInit.getAs<Expr>(),
4880 InitRange.getEnd(), EllipsisLoc);
4881}
4882
4883// Create a static_cast<T&&>(expr).
4884static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4885 QualType TargetType =
4886 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4888 SourceLocation ExprLoc = E->getBeginLoc();
4889 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4890 TargetType, ExprLoc);
4891
4892 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4893 SourceRange(ExprLoc, ExprLoc),
4894 E->getSourceRange()).get();
4895}
4896
4897/// ImplicitInitializerKind - How an implicit base or member initializer should
4898/// initialize its base or member.
4905
4906static bool
4908 ImplicitInitializerKind ImplicitInitKind,
4909 CXXBaseSpecifier *BaseSpec,
4910 bool IsInheritedVirtualBase,
4911 CXXCtorInitializer *&CXXBaseInit) {
4912 InitializedEntity InitEntity
4913 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4914 IsInheritedVirtualBase);
4915
4916 ExprResult BaseInit;
4917
4918 switch (ImplicitInitKind) {
4919 case IIK_Inherit:
4920 case IIK_Default: {
4921 InitializationKind InitKind
4923 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4924 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
4925 break;
4926 }
4927
4928 case IIK_Move:
4929 case IIK_Copy: {
4930 bool Moving = ImplicitInitKind == IIK_Move;
4931 ParmVarDecl *Param = Constructor->getParamDecl(0);
4932 QualType ParamType = Param->getType().getNonReferenceType();
4933
4934 Expr *CopyCtorArg =
4936 SourceLocation(), Param, false,
4937 Constructor->getLocation(), ParamType,
4938 VK_LValue, nullptr);
4939
4940 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4941
4942 // Cast to the base class to avoid ambiguities.
4943 QualType ArgTy =
4944 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4945 ParamType.getQualifiers());
4946
4947 if (Moving) {
4948 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4949 }
4950
4951 CXXCastPath BasePath;
4952 BasePath.push_back(BaseSpec);
4953 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4954 CK_UncheckedDerivedToBase,
4955 Moving ? VK_XValue : VK_LValue,
4956 &BasePath).get();
4957
4958 InitializationKind InitKind
4961 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4962 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4963 break;
4964 }
4965 }
4966
4967 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4968 if (BaseInit.isInvalid())
4969 return true;
4970
4971 CXXBaseInit =
4972 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4973 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4974 SourceLocation()),
4975 BaseSpec->isVirtual(),
4977 BaseInit.getAs<Expr>(),
4979 SourceLocation());
4980
4981 return false;
4982}
4983
4984static bool RefersToRValueRef(Expr *MemRef) {
4985 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4986 return Referenced->getType()->isRValueReferenceType();
4987}
4988
4989static bool
4991 ImplicitInitializerKind ImplicitInitKind,
4992 FieldDecl *Field, IndirectFieldDecl *Indirect,
4993 CXXCtorInitializer *&CXXMemberInit) {
4994 if (Field->isInvalidDecl())
4995 return true;
4996
4997 SourceLocation Loc = Constructor->getLocation();
4998
4999 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5000 bool Moving = ImplicitInitKind == IIK_Move;
5001 ParmVarDecl *Param = Constructor->getParamDecl(0);
5002 QualType ParamType = Param->getType().getNonReferenceType();
5003
5004 // Suppress copying zero-width bitfields.
5005 if (Field->isZeroLengthBitField())
5006 return false;
5007
5008 Expr *MemberExprBase =
5010 SourceLocation(), Param, false,
5011 Loc, ParamType, VK_LValue, nullptr);
5012
5013 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5014
5015 if (Moving) {
5016 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5017 }
5018
5019 // Build a reference to this field within the parameter.
5020 CXXScopeSpec SS;
5021 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5023 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5024 : cast<ValueDecl>(Field), AS_public);
5025 MemberLookup.resolveKind();
5026 ExprResult CtorArg
5027 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5028 ParamType, Loc,
5029 /*IsArrow=*/false,
5030 SS,
5031 /*TemplateKWLoc=*/SourceLocation(),
5032 /*FirstQualifierInScope=*/nullptr,
5033 MemberLookup,
5034 /*TemplateArgs=*/nullptr,
5035 /*S*/nullptr);
5036 if (CtorArg.isInvalid())
5037 return true;
5038
5039 // C++11 [class.copy]p15:
5040 // - if a member m has rvalue reference type T&&, it is direct-initialized
5041 // with static_cast<T&&>(x.m);
5042 if (RefersToRValueRef(CtorArg.get())) {
5043 CtorArg = CastForMoving(SemaRef, CtorArg.get());
5044 }
5045
5046 InitializedEntity Entity =
5047 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5048 /*Implicit*/ true)
5049 : InitializedEntity::InitializeMember(Field, nullptr,
5050 /*Implicit*/ true);
5051
5052 // Direct-initialize to use the copy constructor.
5053 InitializationKind InitKind =
5055
5056 Expr *CtorArgE = CtorArg.getAs<Expr>();
5057 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5058 ExprResult MemberInit =
5059 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5060 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5061 if (MemberInit.isInvalid())
5062 return true;
5063
5064 if (Indirect)
5065 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5066 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5067 else
5068 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5069 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5070 return false;
5071 }
5072
5073 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5074 "Unhandled implicit init kind!");
5075
5076 QualType FieldBaseElementType =
5077 SemaRef.Context.getBaseElementType(Field->getType());
5078
5079 if (FieldBaseElementType->isRecordType()) {
5080 InitializedEntity InitEntity =
5081 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5082 /*Implicit*/ true)
5083 : InitializedEntity::InitializeMember(Field, nullptr,
5084 /*Implicit*/ true);
5085 InitializationKind InitKind =
5087
5088 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5089 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5090
5091 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5092 if (MemberInit.isInvalid())
5093 return true;
5094
5095 if (Indirect)
5096 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5097 Indirect, Loc,
5098 Loc,
5099 MemberInit.get(),
5100 Loc);
5101 else
5102 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5103 Field, Loc, Loc,
5104 MemberInit.get(),
5105 Loc);
5106 return false;
5107 }
5108
5109 if (!Field->getParent()->isUnion()) {
5110 if (FieldBaseElementType->isReferenceType()) {
5111 SemaRef.Diag(Constructor->getLocation(),
5112 diag::err_uninitialized_member_in_ctor)
5113 << (int)Constructor->isImplicit()
5114 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 0
5115 << Field->getDeclName();
5116 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5117 return true;
5118 }
5119
5120 if (FieldBaseElementType.isConstQualified()) {
5121 SemaRef.Diag(Constructor->getLocation(),
5122 diag::err_uninitialized_member_in_ctor)
5123 << (int)Constructor->isImplicit()
5124 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 1
5125 << Field->getDeclName();
5126 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5127 return true;
5128 }
5129 }
5130
5131 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5132 // ARC and Weak:
5133 // Default-initialize Objective-C pointers to NULL.
5134 CXXMemberInit
5135 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5136 Loc, Loc,
5137 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5138 Loc);
5139 return false;
5140 }
5141
5142 // Nothing to initialize.
5143 CXXMemberInit = nullptr;
5144 return false;
5145}
5146
5147namespace {
5148struct BaseAndFieldInfo {
5149 Sema &S;
5150 CXXConstructorDecl *Ctor;
5151 bool AnyErrorsInInits;
5153 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5154 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5155 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5156
5157 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5158 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5159 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5160 if (Ctor->getInheritedConstructor())
5161 IIK = IIK_Inherit;
5162 else if (Generated && Ctor->isCopyConstructor())
5163 IIK = IIK_Copy;
5164 else if (Generated && Ctor->isMoveConstructor())
5165 IIK = IIK_Move;
5166 else
5167 IIK = IIK_Default;
5168 }
5169
5170 bool isImplicitCopyOrMove() const {
5171 switch (IIK) {
5172 case IIK_Copy:
5173 case IIK_Move:
5174 return true;
5175
5176 case IIK_Default:
5177 case IIK_Inherit:
5178 return false;
5179 }
5180
5181 llvm_unreachable("Invalid ImplicitInitializerKind!");
5182 }
5183
5184 bool addFieldInitializer(CXXCtorInitializer *Init) {
5185 AllToInit.push_back(Init);
5186
5187 // Check whether this initializer makes the field "used".
5188 if (Init->getInit()->HasSideEffects(S.Context))
5189 S.UnusedPrivateFields.remove(Init->getAnyMember());
5190
5191 return false;
5192 }
5193
5194 bool isInactiveUnionMember(FieldDecl *Field) {
5195 RecordDecl *Record = Field->getParent();
5196 if (!Record->isUnion())
5197 return false;
5198
5199 if (FieldDecl *Active =
5200 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5201 return Active != Field->getCanonicalDecl();
5202
5203 // In an implicit copy or move constructor, ignore any in-class initializer.
5204 if (isImplicitCopyOrMove())
5205 return true;
5206
5207 // If there's no explicit initialization, the field is active only if it
5208 // has an in-class initializer...
5209 if (Field->hasInClassInitializer())
5210 return false;
5211 // ... or it's an anonymous struct or union whose class has an in-class
5212 // initializer.
5213 if (!Field->isAnonymousStructOrUnion())
5214 return true;
5215 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5216 return !FieldRD->hasInClassInitializer();
5217 }
5218
5219 /// Determine whether the given field is, or is within, a union member
5220 /// that is inactive (because there was an initializer given for a different
5221 /// member of the union, or because the union was not initialized at all).
5222 bool isWithinInactiveUnionMember(FieldDecl *Field,
5223 IndirectFieldDecl *Indirect) {
5224 if (!Indirect)
5225 return isInactiveUnionMember(Field);
5226
5227 for (auto *C : Indirect->chain()) {
5228 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5229 if (Field && isInactiveUnionMember(Field))
5230 return true;
5231 }
5232 return false;
5233 }
5234};
5235}
5236
5237/// Determine whether the given type is an incomplete or zero-lenfgth
5238/// array type.
5240 if (T->isIncompleteArrayType())
5241 return true;
5242
5243 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5244 if (ArrayT->isZeroSize())
5245 return true;
5246
5247 T = ArrayT->getElementType();
5248 }
5249
5250 return false;
5251}
5252
5253static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5254 FieldDecl *Field,
5255 IndirectFieldDecl *Indirect = nullptr) {
5256 if (Field->isInvalidDecl())
5257 return false;
5258
5259 // Overwhelmingly common case: we have a direct initializer for this field.
5261 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5262 return Info.addFieldInitializer(Init);
5263
5264 // C++11 [class.base.init]p8:
5265 // if the entity is a non-static data member that has a
5266 // brace-or-equal-initializer and either
5267 // -- the constructor's class is a union and no other variant member of that
5268 // union is designated by a mem-initializer-id or
5269 // -- the constructor's class is not a union, and, if the entity is a member
5270 // of an anonymous union, no other member of that union is designated by
5271 // a mem-initializer-id,
5272 // the entity is initialized as specified in [dcl.init].
5273 //
5274 // We also apply the same rules to handle anonymous structs within anonymous
5275 // unions.
5276 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5277 return false;
5278
5279 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5280 ExprResult DIE =
5281 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5282 if (DIE.isInvalid())
5283 return true;
5284
5285 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5286 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5287
5289 if (Indirect)
5290 Init = new (SemaRef.Context)
5291 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5292 SourceLocation(), DIE.get(), SourceLocation());
5293 else
5294 Init = new (SemaRef.Context)
5295 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5296 SourceLocation(), DIE.get(), SourceLocation());
5297 return Info.addFieldInitializer(Init);
5298 }
5299
5300 // Don't initialize incomplete or zero-length arrays.
5301 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5302 return false;
5303
5304 // Don't try to build an implicit initializer if there were semantic
5305 // errors in any of the initializers (and therefore we might be
5306 // missing some that the user actually wrote).
5307 if (Info.AnyErrorsInInits)
5308 return false;
5309
5310 CXXCtorInitializer *Init = nullptr;
5311 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5312 Indirect, Init))
5313 return true;
5314
5315 if (!Init)
5316 return false;
5317
5318 return Info.addFieldInitializer(Init);
5319}
5320
5321bool
5324 assert(Initializer->isDelegatingInitializer());
5325 Constructor->setNumCtorInitializers(1);
5326 CXXCtorInitializer **initializer =
5327 new (Context) CXXCtorInitializer*[1];
5328 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5329 Constructor->setCtorInitializers(initializer);
5330
5331 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5332 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5333 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5334 }
5335
5337
5338 DiagnoseUninitializedFields(*this, Constructor);
5339
5340 return false;
5341}
5342
5344 CXXRecordDecl *Class) {
5345 if (Class->isInvalidDecl())
5346 return nullptr;
5347 if (Class->hasIrrelevantDestructor())
5348 return nullptr;
5349
5350 // Dtor might still be missing, e.g because it's invalid.
5351 return S.LookupDestructor(Class);
5352}
5353
5355 FieldDecl *Field) {
5356 if (Field->isInvalidDecl())
5357 return;
5358
5359 // Don't destroy incomplete or zero-length arrays.
5360 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))
5361 return;
5362
5363 QualType FieldType = S.Context.getBaseElementType(Field->getType());
5364
5365 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5366 if (!FieldClassDecl)
5367 return;
5368
5369 // The destructor for an implicit anonymous union member is never invoked.
5370 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5371 return;
5372
5373 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);
5374 if (!Dtor)
5375 return;
5376
5377 S.CheckDestructorAccess(Field->getLocation(), Dtor,
5378 S.PDiag(diag::err_access_dtor_field)
5379 << Field->getDeclName() << FieldType);
5380
5381 S.MarkFunctionReferenced(Location, Dtor);
5382 S.DiagnoseUseOfDecl(Dtor, Location);
5383}
5384
5386 CXXRecordDecl *ClassDecl) {
5387 if (ClassDecl->isDependentContext())
5388 return;
5389
5390 // We only potentially invoke the destructors of potentially constructed
5391 // subobjects.
5392 bool VisitVirtualBases = !ClassDecl->isAbstract();
5393
5394 // If the destructor exists and has already been marked used in the MS ABI,
5395 // then virtual base destructors have already been checked and marked used.
5396 // Skip checking them again to avoid duplicate diagnostics.
5398 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5399 if (Dtor && Dtor->isUsed())
5400 VisitVirtualBases = false;
5401 }
5402
5404
5405 // Bases.
5406 for (const auto &Base : ClassDecl->bases()) {
5407 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5408 if (!BaseClassDecl)
5409 continue;
5410
5411 // Remember direct virtual bases.
5412 if (Base.isVirtual()) {
5413 if (!VisitVirtualBases)
5414 continue;
5415 DirectVirtualBases.insert(BaseClassDecl);
5416 }
5417
5418 auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);
5419 if (!Dtor)
5420 continue;
5421
5422 // FIXME: caret should be on the start of the class name
5423 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5424 S.PDiag(diag::err_access_dtor_base)
5425 << Base.getType() << Base.getSourceRange(),
5426 S.Context.getCanonicalTagType(ClassDecl));
5427
5428 S.MarkFunctionReferenced(Location, Dtor);
5429 S.DiagnoseUseOfDecl(Dtor, Location);
5430 }
5431
5432 if (VisitVirtualBases)
5433 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5434 &DirectVirtualBases);
5435}
5436
5438 ArrayRef<CXXCtorInitializer *> Initializers) {
5439 if (Constructor->isDependentContext()) {
5440 // Just store the initializers as written, they will be checked during
5441 // instantiation.
5442 if (!Initializers.empty()) {
5443 Constructor->setNumCtorInitializers(Initializers.size());
5444 CXXCtorInitializer **baseOrMemberInitializers =
5445 new (Context) CXXCtorInitializer*[Initializers.size()];
5446 memcpy(baseOrMemberInitializers, Initializers.data(),
5447 Initializers.size() * sizeof(CXXCtorInitializer*));
5448 Constructor->setCtorInitializers(baseOrMemberInitializers);
5449 }
5450
5451 // Let template instantiation know whether we had errors.
5452 if (AnyErrors)
5453 Constructor->setInvalidDecl();
5454
5455 return false;
5456 }
5457
5458 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5459
5460 // We need to build the initializer AST according to order of construction
5461 // and not what user specified in the Initializers list.
5462 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5463 if (!ClassDecl)
5464 return true;
5465
5466 bool HadError = false;
5467
5468 for (CXXCtorInitializer *Member : Initializers) {
5469 if (Member->isBaseInitializer())
5470 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5471 Member;
5472 else {
5473 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5474
5475 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5476 for (auto *C : F->chain()) {
5477 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5478 if (FD && FD->getParent()->isUnion())
5479 Info.ActiveUnionMember.insert(std::make_pair(
5481 }
5482 } else if (FieldDecl *FD = Member->getMember()) {
5483 if (FD->getParent()->isUnion())
5484 Info.ActiveUnionMember.insert(std::make_pair(
5486 }
5487 }
5488 }
5489
5490 // Keep track of the direct virtual bases.
5492 for (auto &I : ClassDecl->bases()) {
5493 if (I.isVirtual())
5494 DirectVBases.insert(&I);
5495 }
5496
5497 // Push virtual bases before others.
5498 for (auto &VBase : ClassDecl->vbases()) {
5499 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5500 VBase.getType()->getAsCanonical<RecordType>())) {
5501 // [class.base.init]p7, per DR257:
5502 // A mem-initializer where the mem-initializer-id names a virtual base
5503 // class is ignored during execution of a constructor of any class that
5504 // is not the most derived class.
5505 if (ClassDecl->isAbstract()) {
5506 // FIXME: Provide a fixit to remove the base specifier. This requires
5507 // tracking the location of the associated comma for a base specifier.
5508 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5509 << VBase.getType() << ClassDecl;
5510 DiagnoseAbstractType(ClassDecl);
5511 }
5512
5513 Info.AllToInit.push_back(Value);
5514 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5515 // [class.base.init]p8, per DR257:
5516 // If a given [...] base class is not named by a mem-initializer-id
5517 // [...] and the entity is not a virtual base class of an abstract
5518 // class, then [...] the entity is default-initialized.
5519 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5520 CXXCtorInitializer *CXXBaseInit;
5521 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5522 &VBase, IsInheritedVirtualBase,
5523 CXXBaseInit)) {
5524 HadError = true;
5525 continue;
5526 }
5527
5528 Info.AllToInit.push_back(CXXBaseInit);
5529 }
5530 }
5531
5532 // Non-virtual bases.
5533 for (auto &Base : ClassDecl->bases()) {
5534 // Virtuals are in the virtual base list and already constructed.
5535 if (Base.isVirtual())
5536 continue;
5537
5538 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5539 Base.getType()->getAsCanonical<RecordType>())) {
5540 Info.AllToInit.push_back(Value);
5541 } else if (!AnyErrors) {
5542 CXXCtorInitializer *CXXBaseInit;
5543 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5544 &Base, /*IsInheritedVirtualBase=*/false,
5545 CXXBaseInit)) {
5546 HadError = true;
5547 continue;
5548 }
5549
5550 Info.AllToInit.push_back(CXXBaseInit);
5551 }
5552 }
5553
5554 // Fields.
5555 for (auto *Mem : ClassDecl->decls()) {
5556 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5557 // C++ [class.bit]p2:
5558 // A declaration for a bit-field that omits the identifier declares an
5559 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5560 // initialized.
5561 if (F->isUnnamedBitField())
5562 continue;
5563
5564 // If we're not generating the implicit copy/move constructor, then we'll
5565 // handle anonymous struct/union fields based on their individual
5566 // indirect fields.
5567 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5568 continue;
5569
5570 if (CollectFieldInitializer(*this, Info, F))
5571 HadError = true;
5572 continue;
5573 }
5574
5575 // Beyond this point, we only consider default initialization.
5576 if (Info.isImplicitCopyOrMove())
5577 continue;
5578
5579 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5580 if (F->getType()->isIncompleteArrayType()) {
5581 assert(ClassDecl->hasFlexibleArrayMember() &&
5582 "Incomplete array type is not valid");
5583 continue;
5584 }
5585
5586 // Initialize each field of an anonymous struct individually.
5587 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5588 HadError = true;
5589
5590 continue;
5591 }
5592 }
5593
5594 unsigned NumInitializers = Info.AllToInit.size();
5595 if (NumInitializers > 0) {
5596 Constructor->setNumCtorInitializers(NumInitializers);
5597 CXXCtorInitializer **baseOrMemberInitializers =
5598 new (Context) CXXCtorInitializer*[NumInitializers];
5599 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5600 NumInitializers * sizeof(CXXCtorInitializer*));
5601 Constructor->setCtorInitializers(baseOrMemberInitializers);
5602
5603 SourceLocation Location = Constructor->getLocation();
5604
5605 // Constructors implicitly reference the base and member
5606 // destructors.
5607
5608 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5609 FieldDecl *Field = Initializer->getAnyMember();
5610 if (!Field)
5611 continue;
5612
5613 // C++ [class.base.init]p12:
5614 // In a non-delegating constructor, the destructor for each
5615 // potentially constructed subobject of class type is potentially
5616 // invoked.
5617 MarkFieldDestructorReferenced(*this, Location, Field);
5618 }
5619
5620 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());
5621 }
5622
5623 return HadError;
5624}
5625
5627 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5628 const RecordDecl *RD = RT->getDecl();
5629 if (RD->isAnonymousStructOrUnion()) {
5630 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5631 PopulateKeysForFields(Field, IdealInits);
5632 return;
5633 }
5634 }
5635 IdealInits.push_back(Field->getCanonicalDecl());
5636}
5637
5638static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5639 return Context.getCanonicalType(BaseType).getTypePtr();
5640}
5641
5642static const void *GetKeyForMember(ASTContext &Context,
5644 if (!Member->isAnyMemberInitializer())
5645 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5646
5647 return Member->getAnyMember()->getCanonicalDecl();
5648}
5649
5652 const CXXCtorInitializer *Current) {
5653 if (Previous->isAnyMemberInitializer())
5654 Diag << 0 << Previous->getAnyMember();
5655 else
5656 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5657
5658 if (Current->isAnyMemberInitializer())
5659 Diag << 0 << Current->getAnyMember();
5660 else
5661 Diag << 1 << Current->getTypeSourceInfo()->getType();
5662}
5663
5665 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5667 if (Constructor->getDeclContext()->isDependentContext())
5668 return;
5669
5670 // Don't check initializers order unless the warning is enabled at the
5671 // location of at least one initializer.
5672 bool ShouldCheckOrder = false;
5673 for (const CXXCtorInitializer *Init : Inits) {
5674 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5675 Init->getSourceLocation())) {
5676 ShouldCheckOrder = true;
5677 break;
5678 }
5679 }
5680 if (!ShouldCheckOrder)
5681 return;
5682
5683 // Build the list of bases and members in the order that they'll
5684 // actually be initialized. The explicit initializers should be in
5685 // this same order but may be missing things.
5686 SmallVector<const void*, 32> IdealInitKeys;
5687
5688 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5689
5690 // 1. Virtual bases.
5691 for (const auto &VBase : ClassDecl->vbases())
5692 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5693
5694 // 2. Non-virtual bases.
5695 for (const auto &Base : ClassDecl->bases()) {
5696 if (Base.isVirtual())
5697 continue;
5698 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5699 }
5700
5701 // 3. Direct fields.
5702 for (auto *Field : ClassDecl->fields()) {
5703 if (Field->isUnnamedBitField())
5704 continue;
5705
5706 PopulateKeysForFields(Field, IdealInitKeys);
5707 }
5708
5709 unsigned NumIdealInits = IdealInitKeys.size();
5710 unsigned IdealIndex = 0;
5711
5712 // Track initializers that are in an incorrect order for either a warning or
5713 // note if multiple ones occur.
5714 SmallVector<unsigned> WarnIndexes;
5715 // Correlates the index of an initializer in the init-list to the index of
5716 // the field/base in the class.
5717 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5718
5719 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5720 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5721
5722 // Scan forward to try to find this initializer in the idealized
5723 // initializers list.
5724 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5725 if (InitKey == IdealInitKeys[IdealIndex])
5726 break;
5727
5728 // If we didn't find this initializer, it must be because we
5729 // scanned past it on a previous iteration. That can only
5730 // happen if we're out of order; emit a warning.
5731 if (IdealIndex == NumIdealInits && InitIndex) {
5732 WarnIndexes.push_back(InitIndex);
5733
5734 // Move back to the initializer's location in the ideal list.
5735 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5736 if (InitKey == IdealInitKeys[IdealIndex])
5737 break;
5738
5739 assert(IdealIndex < NumIdealInits &&
5740 "initializer not found in initializer list");
5741 }
5742 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5743 }
5744
5745 if (WarnIndexes.empty())
5746 return;
5747
5748 // Sort based on the ideal order, first in the pair.
5749 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5750
5751 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5752 // emit the diagnostic before we can try adding notes.
5753 {
5755 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5756 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5757 : diag::warn_some_initializers_out_of_order);
5758
5759 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5760 if (CorrelatedInitOrder[I].second == I)
5761 continue;
5762 // Ideally we would be using InsertFromRange here, but clang doesn't
5763 // appear to handle InsertFromRange correctly when the source range is
5764 // modified by another fix-it.
5766 Inits[I]->getSourceRange(),
5769 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5770 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5771 }
5772
5773 // If there is only 1 item out of order, the warning expects the name and
5774 // type of each being added to it.
5775 if (WarnIndexes.size() == 1) {
5776 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5777 Inits[WarnIndexes.front()]);
5778 return;
5779 }
5780 }
5781 // More than 1 item to warn, create notes letting the user know which ones
5782 // are bad.
5783 for (unsigned WarnIndex : WarnIndexes) {
5784 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5785 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5786 diag::note_initializer_out_of_order);
5787 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5788 D << PrevInit->getSourceRange();
5789 }
5790}
5791
5792namespace {
5793bool CheckRedundantInit(Sema &S,
5794 CXXCtorInitializer *Init,
5795 CXXCtorInitializer *&PrevInit) {
5796 if (!PrevInit) {
5797 PrevInit = Init;
5798 return false;
5799 }
5800
5801 if (FieldDecl *Field = Init->getAnyMember())
5802 S.Diag(Init->getSourceLocation(),
5803 diag::err_multiple_mem_initialization)
5804 << Field->getDeclName()
5805 << Init->getSourceRange();
5806 else {
5807 const Type *BaseClass = Init->getBaseClass();
5808 assert(BaseClass && "neither field nor base");
5809 S.Diag(Init->getSourceLocation(),
5810 diag::err_multiple_base_initialization)
5811 << QualType(BaseClass, 0)
5812 << Init->getSourceRange();
5813 }
5814 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5815 << 0 << PrevInit->getSourceRange();
5816
5817 return true;
5818}
5819
5820typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5821typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5822
5823bool CheckRedundantUnionInit(Sema &S,
5824 CXXCtorInitializer *Init,
5825 RedundantUnionMap &Unions) {
5826 FieldDecl *Field = Init->getAnyMember();
5827 RecordDecl *Parent = Field->getParent();
5828 NamedDecl *Child = Field;
5829
5830 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5831 if (Parent->isUnion()) {
5832 UnionEntry &En = Unions[Parent];
5833 if (En.first && En.first != Child) {
5834 S.Diag(Init->getSourceLocation(),
5835 diag::err_multiple_mem_union_initialization)
5836 << Field->getDeclName()
5837 << Init->getSourceRange();
5838 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5839 << 0 << En.second->getSourceRange();
5840 return true;
5841 }
5842 if (!En.first) {
5843 En.first = Child;
5844 En.second = Init;
5845 }
5846 if (!Parent->isAnonymousStructOrUnion())
5847 return false;
5848 }
5849
5850 Child = Parent;
5851 Parent = cast<RecordDecl>(Parent->getDeclContext());
5852 }
5853
5854 return false;
5855}
5856} // namespace
5857
5858void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5859 SourceLocation ColonLoc,
5861 bool AnyErrors) {
5862 if (!ConstructorDecl)
5863 return;
5864
5865 AdjustDeclIfTemplate(ConstructorDecl);
5866
5868 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5869
5870 if (!Constructor) {
5871 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5872 return;
5873 }
5874
5875 // Mapping for the duplicate initializers check.
5876 // For member initializers, this is keyed with a FieldDecl*.
5877 // For base initializers, this is keyed with a Type*.
5878 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5879
5880 // Mapping for the inconsistent anonymous-union initializers check.
5881 RedundantUnionMap MemberUnions;
5882
5883 bool HadError = false;
5884 for (unsigned i = 0; i < MemInits.size(); i++) {
5885 CXXCtorInitializer *Init = MemInits[i];
5886
5887 // Set the source order index.
5888 Init->setSourceOrder(i);
5889
5890 if (Init->isAnyMemberInitializer()) {
5891 const void *Key = GetKeyForMember(Context, Init);
5892 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5893 CheckRedundantUnionInit(*this, Init, MemberUnions))
5894 HadError = true;
5895 } else if (Init->isBaseInitializer()) {
5896 const void *Key = GetKeyForMember(Context, Init);
5897 if (CheckRedundantInit(*this, Init, Members[Key]))
5898 HadError = true;
5899 } else {
5900 assert(Init->isDelegatingInitializer());
5901 // This must be the only initializer
5902 if (MemInits.size() != 1) {
5903 Diag(Init->getSourceLocation(),
5904 diag::err_delegating_initializer_alone)
5905 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5906 // We will treat this as being the only initializer.
5907 }
5909 // Return immediately as the initializer is set.
5910 return;
5911 }
5912 }
5913
5914 if (HadError)
5915 return;
5916
5918
5919 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5920
5921 DiagnoseUninitializedFields(*this, Constructor);
5922}
5923
5925 CXXRecordDecl *ClassDecl) {
5926 // Ignore dependent contexts. Also ignore unions, since their members never
5927 // have destructors implicitly called.
5928 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5929 return;
5930
5931 // FIXME: all the access-control diagnostics are positioned on the
5932 // field/base declaration. That's probably good; that said, the
5933 // user might reasonably want to know why the destructor is being
5934 // emitted, and we currently don't say.
5935
5936 // Non-static data members.
5937 for (auto *Field : ClassDecl->fields()) {
5938 MarkFieldDestructorReferenced(*this, Location, Field);
5939 }
5940
5941 MarkBaseDestructorsReferenced(*this, Location, ClassDecl);
5942}
5943
5945 SourceLocation Location, CXXRecordDecl *ClassDecl,
5946 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5947 // Virtual bases.
5948 for (const auto &VBase : ClassDecl->vbases()) {
5949 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5950 if (!BaseClassDecl)
5951 continue;
5952
5953 // Ignore already visited direct virtual bases.
5954 if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))
5955 continue;
5956
5957 auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);
5958 if (!Dtor)
5959 continue;
5960
5961 CanQualType CT = Context.getCanonicalTagType(ClassDecl);
5962 if (CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
5963 PDiag(diag::err_access_dtor_vbase)
5964 << CT << VBase.getType(),
5965 CT) == AR_accessible) {
5967 CT, VBase.getType(), diag::err_access_dtor_vbase, 0,
5968 ClassDecl->getLocation(), SourceRange(), DeclarationName(), nullptr);
5969 }
5970
5971 MarkFunctionReferenced(Location, Dtor);
5972 DiagnoseUseOfDecl(Dtor, Location);
5973 }
5974}
5975
5977 if (!CDtorDecl)
5978 return;
5979
5981 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5982 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5983 !ClassDecl || ClassDecl->isInvalidDecl()) {
5984 return;
5985 }
5986 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5987 DiagnoseUninitializedFields(*this, Constructor);
5988 }
5989}
5990
5992 if (!getLangOpts().CPlusPlus)
5993 return false;
5994
5995 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5996 if (!RD)
5997 return false;
5998
5999 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6000 // class template specialization here, but doing so breaks a lot of code.
6001
6002 // We can't answer whether something is abstract until it has a
6003 // definition. If it's currently being defined, we'll walk back
6004 // over all the declarations when we have a full definition.
6005 const CXXRecordDecl *Def = RD->getDefinition();
6006 if (!Def || Def->isBeingDefined())
6007 return false;
6008
6009 return RD->isAbstract();
6010}
6011
6013 TypeDiagnoser &Diagnoser) {
6014 if (!isAbstractType(Loc, T))
6015 return false;
6016
6017 T = Context.getBaseElementType(T);
6018 Diagnoser.diagnose(*this, Loc, T);
6019 DiagnoseAbstractType(T->getAsCXXRecordDecl());
6020 return true;
6021}
6022
6024 // Check if we've already emitted the list of pure virtual functions
6025 // for this class.
6027 return;
6028
6029 // If the diagnostic is suppressed, don't emit the notes. We're only
6030 // going to emit them once, so try to attach them to a diagnostic we're
6031 // actually going to show.
6032 if (Diags.isLastDiagnosticIgnored())
6033 return;
6034
6035 CXXFinalOverriderMap FinalOverriders;
6036 RD->getFinalOverriders(FinalOverriders);
6037
6038 // Keep a set of seen pure methods so we won't diagnose the same method
6039 // more than once.
6041
6042 for (const auto &M : FinalOverriders) {
6043 for (const auto &SO : M.second) {
6044 // C++ [class.abstract]p4:
6045 // A class is abstract if it contains or inherits at least one
6046 // pure virtual function for which the final overrider is pure
6047 // virtual.
6048
6049 if (SO.second.size() != 1)
6050 continue;
6051 const CXXMethodDecl *Method = SO.second.front().Method;
6052
6053 if (!Method->isPureVirtual())
6054 continue;
6055
6056 if (!SeenPureMethods.insert(Method).second)
6057 continue;
6058
6059 Diag(Method->getLocation(), diag::note_pure_virtual_function)
6060 << Method->getDeclName() << RD->getDeclName();
6061 }
6062 }
6063
6066 PureVirtualClassDiagSet->insert(RD);
6067}
6068
6069namespace {
6070struct AbstractUsageInfo {
6071 Sema &S;
6073 CanQualType AbstractType;
6074 bool Invalid;
6075
6076 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6077 : S(S), Record(Record),
6078 AbstractType(S.Context.getCanonicalTagType(Record)), Invalid(false) {}
6079
6080 void DiagnoseAbstractType() {
6081 if (Invalid) return;
6083 Invalid = true;
6084 }
6085
6086 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6087};
6088
6089struct CheckAbstractUsage {
6090 AbstractUsageInfo &Info;
6091 const NamedDecl *Ctx;
6092
6093 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6094 : Info(Info), Ctx(Ctx) {}
6095
6096 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6097 switch (TL.getTypeLocClass()) {
6098#define ABSTRACT_TYPELOC(CLASS, PARENT)
6099#define TYPELOC(CLASS, PARENT) \
6100 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6101#include "clang/AST/TypeLocNodes.def"
6102 }
6103 }
6104
6105 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6107 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6108 if (!TL.getParam(I))
6109 continue;
6110
6111 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6112 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6113 }
6114 }
6115
6116 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6118 }
6119
6120 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6121 // Visit the type parameters from a permissive context.
6122 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6123 TemplateArgumentLoc TAL = TL.getArgLoc(I);
6125 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6126 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6127 // TODO: other template argument types?
6128 }
6129 }
6130
6131 // Visit pointee types from a permissive context.
6132#define CheckPolymorphic(Type) \
6133 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6134 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6135 }
6141
6142 /// Handle all the types we haven't given a more specific
6143 /// implementation for above.
6144 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6145 // Every other kind of type that we haven't called out already
6146 // that has an inner type is either (1) sugar or (2) contains that
6147 // inner type in some way as a subobject.
6148 if (TypeLoc Next = TL.getNextTypeLoc())
6149 return Visit(Next, Sel);
6150
6151 // If there's no inner type and we're in a permissive context,
6152 // don't diagnose.
6153 if (Sel == Sema::AbstractNone) return;
6154
6155 // Check whether the type matches the abstract type.
6156 QualType T = TL.getType();
6157 if (T->isArrayType()) {
6159 T = Info.S.Context.getBaseElementType(T);
6160 }
6161 CanQualType CT = T->getCanonicalTypeUnqualified();
6162 if (CT != Info.AbstractType) return;
6163
6164 // It matched; do some magic.
6165 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6166 if (Sel == Sema::AbstractArrayType) {
6167 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6168 << T << TL.getSourceRange();
6169 } else {
6170 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6171 << Sel << T << TL.getSourceRange();
6172 }
6173 Info.DiagnoseAbstractType();
6174 }
6175};
6176
6177void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6179 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6180}
6181
6182}
6183
6184/// Check for invalid uses of an abstract type in a function declaration.
6185static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6186 FunctionDecl *FD) {
6187 // Only definitions are required to refer to complete and
6188 // non-abstract types.
6190 return;
6191
6192 // For safety's sake, just ignore it if we don't have type source
6193 // information. This should never happen for non-implicit methods,
6194 // but...
6195 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6196 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6197}
6198
6199/// Check for invalid uses of an abstract type in a variable0 declaration.
6200static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6201 VarDecl *VD) {
6202 // No need to do the check on definitions, which require that
6203 // the type is complete.
6205 return;
6206
6207 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6209}
6210
6211/// Check for invalid uses of an abstract type within a class definition.
6212static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6213 CXXRecordDecl *RD) {
6214 for (auto *D : RD->decls()) {
6215 if (D->isImplicit()) continue;
6216
6217 // Step through friends to the befriended declaration.
6218 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6219 D = FD->getFriendDecl();
6220 if (!D) continue;
6221 }
6222
6223 // Functions and function templates.
6224 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6225 CheckAbstractClassUsage(Info, FD);
6226 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6227 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6228
6229 // Fields and static variables.
6230 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6231 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6232 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6233 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6234 CheckAbstractClassUsage(Info, VD);
6235 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6236 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6237
6238 // Nested classes and class templates.
6239 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6240 CheckAbstractClassUsage(Info, RD);
6241 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6242 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6243 }
6244 }
6245}
6246
6248 Attr *ClassAttr = getDLLAttr(Class);
6249 if (!ClassAttr)
6250 return;
6251
6252 assert(ClassAttr->getKind() == attr::DLLExport);
6253
6254 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6255
6257 // Don't go any further if this is just an explicit instantiation
6258 // declaration.
6259 return;
6260
6261 // Add a context note to explain how we got to any diagnostics produced below.
6262 struct MarkingClassDllexported {
6263 Sema &S;
6264 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6265 SourceLocation AttrLoc)
6266 : S(S) {
6269 Ctx.PointOfInstantiation = AttrLoc;
6270 Ctx.Entity = Class;
6272 }
6273 ~MarkingClassDllexported() {
6275 }
6276 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6277
6278 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6279 S.MarkVTableUsed(Class->getLocation(), Class, true);
6280
6281 for (Decl *Member : Class->decls()) {
6282 // Skip members that were not marked exported.
6283 if (!Member->hasAttr<DLLExportAttr>())
6284 continue;
6285
6286 // Defined static variables that are members of an exported base
6287 // class must be marked export too.
6288 auto *VD = dyn_cast<VarDecl>(Member);
6289 if (VD && VD->getStorageClass() == SC_Static &&
6291 S.MarkVariableReferenced(VD->getLocation(), VD);
6292
6293 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6294 if (!MD)
6295 continue;
6296
6297 if (MD->isUserProvided()) {
6298 // Instantiate non-default class member functions ...
6299
6300 // .. except for certain kinds of template specializations.
6301 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6302 continue;
6303
6304 // If this is an MS ABI dllexport default constructor, instantiate any
6305 // default arguments.
6307 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6308 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6310 }
6311 }
6312
6313 S.MarkFunctionReferenced(Class->getLocation(), MD);
6314
6315 // The function will be passed to the consumer when its definition is
6316 // encountered.
6317 } else if (MD->isExplicitlyDefaulted()) {
6318 // Synthesize and instantiate explicitly defaulted methods.
6319 S.MarkFunctionReferenced(Class->getLocation(), MD);
6320
6322 // Except for explicit instantiation defs, we will not see the
6323 // definition again later, so pass it to the consumer now.
6325 }
6326 } else if (!MD->isTrivial() ||
6327 MD->isCopyAssignmentOperator() ||
6328 MD->isMoveAssignmentOperator()) {
6329 // Synthesize and instantiate non-trivial implicit methods, and the copy
6330 // and move assignment operators. The latter are exported even if they
6331 // are trivial, because the address of an operator can be taken and
6332 // should compare equal across libraries.
6333 S.MarkFunctionReferenced(Class->getLocation(), MD);
6334
6335 // There is no later point when we will see the definition of this
6336 // function, so pass it to the consumer now.
6338 }
6339 }
6340}
6341
6343 CXXRecordDecl *Class) {
6344 // Only the MS ABI has default constructor closures, so we don't need to do
6345 // this semantic checking anywhere else.
6347 return;
6348
6349 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6350 for (Decl *Member : Class->decls()) {
6351 // Look for exported default constructors.
6352 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6353 if (!CD || !CD->isDefaultConstructor())
6354 continue;
6355 auto *Attr = CD->getAttr<DLLExportAttr>();
6356 if (!Attr)
6357 continue;
6358
6359 // If the class is non-dependent, mark the default arguments as ODR-used so
6360 // that we can properly codegen the constructor closure.
6361 if (!Class->isDependentContext()) {
6362 for (ParmVarDecl *PD : CD->parameters()) {
6363 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6365 }
6366 }
6367
6368 if (LastExportedDefaultCtor) {
6369 S.Diag(LastExportedDefaultCtor->getLocation(),
6370 diag::err_attribute_dll_ambiguous_default_ctor)
6371 << Class;
6372 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6373 << CD->getDeclName();
6374 return;
6375 }
6376 LastExportedDefaultCtor = CD;
6377 }
6378}
6379
6381 CXXRecordDecl *Class) {
6382 bool ErrorReported = false;
6383 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6384 ClassTemplateDecl *TD) {
6385 if (ErrorReported)
6386 return;
6387 S.Diag(TD->getLocation(),
6388 diag::err_cuda_device_builtin_surftex_cls_template)
6389 << /*surface*/ 0 << TD;
6390 ErrorReported = true;
6391 };
6392
6393 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6394 if (!TD) {
6395 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6396 if (!SD) {
6397 S.Diag(Class->getLocation(),
6398 diag::err_cuda_device_builtin_surftex_ref_decl)
6399 << /*surface*/ 0 << Class;
6400 S.Diag(Class->getLocation(),
6401 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6402 << Class;
6403 return;
6404 }
6405 TD = SD->getSpecializedTemplate();
6406 }
6407
6409 unsigned N = Params->size();
6410
6411 if (N != 2) {
6412 reportIllegalClassTemplate(S, TD);
6413 S.Diag(TD->getLocation(),
6414 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6415 << TD << 2;
6416 }
6417 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6418 reportIllegalClassTemplate(S, TD);
6419 S.Diag(TD->getLocation(),
6420 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6421 << TD << /*1st*/ 0 << /*type*/ 0;
6422 }
6423 if (N > 1) {
6424 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6425 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6426 reportIllegalClassTemplate(S, TD);
6427 S.Diag(TD->getLocation(),
6428 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6429 << TD << /*2nd*/ 1 << /*integer*/ 1;
6430 }
6431 }
6432}
6433
6435 CXXRecordDecl *Class) {
6436 bool ErrorReported = false;
6437 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6438 ClassTemplateDecl *TD) {
6439 if (ErrorReported)
6440 return;
6441 S.Diag(TD->getLocation(),
6442 diag::err_cuda_device_builtin_surftex_cls_template)
6443 << /*texture*/ 1 << TD;
6444 ErrorReported = true;
6445 };
6446
6447 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6448 if (!TD) {
6449 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6450 if (!SD) {
6451 S.Diag(Class->getLocation(),
6452 diag::err_cuda_device_builtin_surftex_ref_decl)
6453 << /*texture*/ 1 << Class;
6454 S.Diag(Class->getLocation(),
6455 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6456 << Class;
6457 return;
6458 }
6459 TD = SD->getSpecializedTemplate();
6460 }
6461
6463 unsigned N = Params->size();
6464
6465 if (N != 3) {
6466 reportIllegalClassTemplate(S, TD);
6467 S.Diag(TD->getLocation(),
6468 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6469 << TD << 3;
6470 }
6471 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6472 reportIllegalClassTemplate(S, TD);
6473 S.Diag(TD->getLocation(),
6474 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6475 << TD << /*1st*/ 0 << /*type*/ 0;
6476 }
6477 if (N > 1) {
6478 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6479 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6480 reportIllegalClassTemplate(S, TD);
6481 S.Diag(TD->getLocation(),
6482 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6483 << TD << /*2nd*/ 1 << /*integer*/ 1;
6484 }
6485 }
6486 if (N > 2) {
6487 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6488 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6489 reportIllegalClassTemplate(S, TD);
6490 S.Diag(TD->getLocation(),
6491 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6492 << TD << /*3rd*/ 2 << /*integer*/ 1;
6493 }
6494 }
6495}
6496
6498 // Mark any compiler-generated routines with the implicit code_seg attribute.
6499 for (auto *Method : Class->methods()) {
6500 if (Method->isUserProvided())
6501 continue;
6502 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6503 Method->addAttr(A);
6504 }
6505}
6506
6508 Attr *ClassAttr = getDLLAttr(Class);
6509
6510 // MSVC inherits DLL attributes to partial class template specializations.
6511 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6512 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6513 if (Attr *TemplateAttr =
6514 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6515 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6516 A->setInherited(true);
6517 ClassAttr = A;
6518 }
6519 }
6520 }
6521
6522 if (!ClassAttr)
6523 return;
6524
6525 // MSVC allows imported or exported template classes that have UniqueExternal
6526 // linkage. This occurs when the template class has been instantiated with
6527 // a template parameter which itself has internal linkage.
6528 // We drop the attribute to avoid exporting or importing any members.
6529 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6530 Context.getTargetInfo().getTriple().isPS()) &&
6531 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6532 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6533 return;
6534 }
6535
6536 if (!Class->isExternallyVisible()) {
6537 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6538 << Class << ClassAttr;
6539 return;
6540 }
6541
6542 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6543 !ClassAttr->isInherited()) {
6544 // Diagnose dll attributes on members of class with dll attribute.
6545 for (Decl *Member : Class->decls()) {
6547 continue;
6548 InheritableAttr *MemberAttr = getDLLAttr(Member);
6549 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6550 continue;
6551
6552 Diag(MemberAttr->getLocation(),
6553 diag::err_attribute_dll_member_of_dll_class)
6554 << MemberAttr << ClassAttr;
6555 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6556 Member->setInvalidDecl();
6557 }
6558 }
6559
6560 if (Class->getDescribedClassTemplate())
6561 // Don't inherit dll attribute until the template is instantiated.
6562 return;
6563
6564 // The class is either imported or exported.
6565 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6566
6567 // Check if this was a dllimport attribute propagated from a derived class to
6568 // a base class template specialization. We don't apply these attributes to
6569 // static data members.
6570 const bool PropagatedImport =
6571 !ClassExported &&
6572 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6573
6574 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6575
6576 // Ignore explicit dllexport on explicit class template instantiation
6577 // declarations, except in MinGW mode.
6578 if (ClassExported && !ClassAttr->isInherited() &&
6580 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6581 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6582 Class->addAttr(DLLExportOnDeclAttr::Create(Context, DEA->getLoc()));
6583 Class->dropAttr<DLLExportAttr>();
6584 }
6585 return;
6586 }
6587
6588 // Force declaration of implicit members so they can inherit the attribute.
6590
6591 // Inherited constructors are created lazily; force their creation now so the
6592 // loop below can propagate the DLL attribute to them.
6593 if (ClassExported) {
6595 for (Decl *D : Class->decls())
6596 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(D))
6597 Shadows.push_back(S);
6598 for (ConstructorUsingShadowDecl *S : Shadows) {
6599 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(S->getTargetDecl());
6600 if (!BC || BC->isDeleted())
6601 continue;
6602 // Skip constructors whose requires clause is not satisfied.
6603 // Normally overload resolution filters these, but we are bypassing
6604 // it to eagerly create inherited constructors for dllexport.
6605 if (BC->getTrailingRequiresClause()) {
6606 ConstraintSatisfaction Satisfaction;
6607 if (CheckFunctionConstraints(BC, Satisfaction) ||
6608 !Satisfaction.IsSatisfied)
6609 continue;
6610 }
6611 findInheritingConstructor(Class->getLocation(), BC, S);
6612 }
6613 }
6614
6615 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6616 // seem to be true in practice?
6617
6618 for (Decl *Member : Class->decls()) {
6619 if (isTemplateInstantiation(TSK) &&
6620 Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6621 continue;
6622
6623 VarDecl *VD = dyn_cast<VarDecl>(Member);
6624 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6625
6626 // Only methods and static fields inherit the attributes.
6627 if (!VD && !MD)
6628 continue;
6629
6630 if (MD) {
6631 // Don't process deleted methods.
6632 if (MD->isDeleted())
6633 continue;
6634
6635 if (ClassExported) {
6636 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(MD);
6637 if (CD && CD->getInheritedConstructor()) {
6638 // Inherited constructors already had their base constructor's
6639 // constraints checked before creation via
6640 // findInheritingConstructor, so only ABI-compatibility checks
6641 // are needed here.
6642 //
6643 // Don't export inherited constructors whose parameters prevent
6644 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6645 // CodeGen) returns false, Clang inlines the constructor body
6646 // instead of emitting a forwarding thunk, producing code that
6647 // is not ABI-compatible with MSVC. Suppress the export and warn
6648 // so the user gets a linker error rather than a silent runtime
6649 // mismatch.
6650 if (CD->isVariadic()) {
6651 Diag(CD->getLocation(),
6652 diag::warn_dllexport_inherited_ctor_unsupported)
6653 << /*variadic=*/0;
6654 continue;
6655 }
6656 if (Context.getTargetInfo()
6657 .getCXXABI()
6658 .areArgsDestroyedLeftToRightInCallee()) {
6659 bool HasCalleeCleanupParam = false;
6660 for (const ParmVarDecl *P : CD->parameters())
6661 if (P->needsDestruction(Context)) {
6662 HasCalleeCleanupParam = true;
6663 break;
6664 }
6665 if (HasCalleeCleanupParam) {
6666 Diag(CD->getLocation(),
6667 diag::warn_dllexport_inherited_ctor_unsupported)
6668 << /*callee-cleanup=*/1;
6669 continue;
6670 }
6671 }
6672 } else if (MD->getTrailingRequiresClause()) {
6673 // Don't export methods whose requires clause is not satisfied.
6674 // For class template specializations, member constraints may
6675 // depend on template arguments and an unsatisfied constraint
6676 // means the member should not be available in this
6677 // specialization.
6678 ConstraintSatisfaction Satisfaction;
6679 if (CheckFunctionConstraints(MD, Satisfaction) ||
6680 !Satisfaction.IsSatisfied)
6681 continue;
6682 }
6683 }
6684
6685 if (MD->isInlined()) {
6686 // MinGW does not import or export inline methods. But do it for
6687 // template instantiations and inherited constructors (which are
6688 // marked inline but must be exported to match MSVC behavior).
6689 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6692 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6693 !CD || !CD->getInheritedConstructor())
6694 continue;
6695 }
6696
6697 // MSVC versions before 2015 don't export the move assignment operators
6698 // and move constructor, so don't attempt to import/export them if
6699 // we have a definition.
6700 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6701 if ((MD->isMoveAssignmentOperator() ||
6702 (Ctor && Ctor->isMoveConstructor())) &&
6703 getLangOpts().isCompatibleWithMSVC() &&
6704 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6705 continue;
6706
6707 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6708 // operator is exported anyway.
6709 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6710 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6711 continue;
6712 }
6713 }
6714
6715 // Don't apply dllimport attributes to static data members of class template
6716 // instantiations when the attribute is propagated from a derived class.
6717 if (VD && PropagatedImport)
6718 continue;
6719
6721 continue;
6722
6723 if (!getDLLAttr(Member)) {
6724 InheritableAttr *NewAttr = nullptr;
6725
6726 // Do not export/import inline function when -fno-dllexport-inlines is
6727 // passed. But add attribute for later local static var check.
6728 // Inherited constructors are marked inline but must still be exported
6729 // to match MSVC behavior, so exclude them from this override.
6730 bool IsInheritedCtor = false;
6731 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(MD))
6732 IsInheritedCtor = (bool)CD->getInheritedConstructor();
6733 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6734 !IsInheritedCtor && TSK != TSK_ExplicitInstantiationDeclaration &&
6736 if (ClassExported) {
6737 NewAttr = ::new (getASTContext())
6738 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6739 } else {
6740 NewAttr = ::new (getASTContext())
6741 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6742 }
6743 } else {
6744 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6745 }
6746
6747 NewAttr->setInherited(true);
6748 Member->addAttr(NewAttr);
6749
6750 if (MD) {
6751 // Propagate DLLAttr to friend re-declarations of MD that have already
6752 // been constructed.
6753 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6754 FD = FD->getPreviousDecl()) {
6756 continue;
6757 assert(!getDLLAttr(FD) &&
6758 "friend re-decl should not already have a DLLAttr");
6759 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6760 NewAttr->setInherited(true);
6761 FD->addAttr(NewAttr);
6762 }
6763 }
6764 }
6765 }
6766
6767 if (ClassExported)
6768 DelayedDllExportClasses.push_back(Class);
6769}
6770
6772 CXXRecordDecl *Class, Attr *ClassAttr,
6773 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6774 if (getDLLAttr(
6775 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6776 // If the base class template has a DLL attribute, don't try to change it.
6777 return;
6778 }
6779
6780 auto TSK = BaseTemplateSpec->getSpecializationKind();
6781 if (!getDLLAttr(BaseTemplateSpec) &&
6783 TSK == TSK_ImplicitInstantiation)) {
6784 // The template hasn't been instantiated yet (or it has, but only as an
6785 // explicit instantiation declaration or implicit instantiation, which means
6786 // we haven't codegenned any members yet), so propagate the attribute.
6787 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6788 NewAttr->setInherited(true);
6789 BaseTemplateSpec->addAttr(NewAttr);
6790
6791 // If this was an import, mark that we propagated it from a derived class to
6792 // a base class template specialization.
6793 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6794 ImportAttr->setPropagatedToBaseTemplate();
6795
6796 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6797 // needs to be run again to work see the new attribute. Otherwise this will
6798 // get run whenever the template is instantiated.
6799 if (TSK != TSK_Undeclared)
6800 checkClassLevelDLLAttribute(BaseTemplateSpec);
6801
6802 return;
6803 }
6804
6805 if (getDLLAttr(BaseTemplateSpec)) {
6806 // The template has already been specialized or instantiated with an
6807 // attribute, explicitly or through propagation. We should not try to change
6808 // it.
6809 return;
6810 }
6811
6812 // The template was previously instantiated or explicitly specialized without
6813 // a dll attribute, It's too late for us to add an attribute, so warn that
6814 // this is unsupported.
6815 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6816 << BaseTemplateSpec->isExplicitSpecialization();
6817 Diag(ClassAttr->getLocation(), diag::note_attribute);
6818 if (BaseTemplateSpec->isExplicitSpecialization()) {
6819 Diag(BaseTemplateSpec->getLocation(),
6820 diag::note_template_class_explicit_specialization_was_here)
6821 << BaseTemplateSpec;
6822 } else {
6823 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6824 diag::note_template_class_instantiation_was_here)
6825 << BaseTemplateSpec;
6826 }
6827}
6828
6831 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6832 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6833 if (Ctor->isDefaultConstructor())
6835
6836 if (Ctor->isCopyConstructor())
6838
6839 if (Ctor->isMoveConstructor())
6841 }
6842
6843 if (MD->isCopyAssignmentOperator())
6845
6846 if (MD->isMoveAssignmentOperator())
6848
6849 if (isa<CXXDestructorDecl>(FD))
6851 }
6852
6853 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6854 case OO_EqualEqual:
6856
6857 case OO_ExclaimEqual:
6859
6860 case OO_Spaceship:
6861 // No point allowing this if <=> doesn't exist in the current language mode.
6862 if (!getLangOpts().CPlusPlus20)
6863 break;
6865
6866 case OO_Less:
6867 case OO_LessEqual:
6868 case OO_Greater:
6869 case OO_GreaterEqual:
6870 // No point allowing this if <=> doesn't exist in the current language mode.
6871 if (!getLangOpts().CPlusPlus20)
6872 break;
6874
6875 default:
6876 break;
6877 }
6878
6879 // Not defaultable.
6880 return DefaultedFunctionKind();
6881}
6882
6884 SourceLocation DefaultLoc) {
6886 if (DFK.isComparison())
6887 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6888
6889 switch (DFK.asSpecialMember()) {
6893 break;
6896 break;
6899 break;
6902 break;
6905 break;
6908 break;
6910 llvm_unreachable("Invalid special member.");
6911 }
6912}
6913
6914/// Determine whether a type is permitted to be passed or returned in
6915/// registers, per C++ [class.temporary]p3.
6918 if (D->isDependentType() || D->isInvalidDecl())
6919 return false;
6920
6921 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6922 // The PS4 platform ABI follows the behavior of Clang 3.2.
6924 return !D->hasNonTrivialDestructorForCall() &&
6926
6927 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6928 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6929 bool DtorIsTrivialForCall = false;
6930
6931 // If a class has at least one eligible, trivial copy constructor, it
6932 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6933 //
6934 // Note: This permits classes with non-trivial copy or move ctors to be
6935 // passed in registers, so long as they *also* have a trivial copy ctor,
6936 // which is non-conforming.
6940 CopyCtorIsTrivial = true;
6942 CopyCtorIsTrivialForCall = true;
6943 }
6944 } else {
6945 for (const CXXConstructorDecl *CD : D->ctors()) {
6946 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6947 !CD->isIneligibleOrNotSelected()) {
6948 if (CD->isTrivial())
6949 CopyCtorIsTrivial = true;
6950 if (CD->isTrivialForCall())
6951 CopyCtorIsTrivialForCall = true;
6952 }
6953 }
6954 }
6955
6956 if (D->needsImplicitDestructor()) {
6957 if (!D->defaultedDestructorIsDeleted() &&
6959 DtorIsTrivialForCall = true;
6960 } else if (const auto *DD = D->getDestructor()) {
6961 if (!DD->isDeleted() && DD->isTrivialForCall())
6962 DtorIsTrivialForCall = true;
6963 }
6964
6965 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6966 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6967 return true;
6968
6969 // If a class has a destructor, we'd really like to pass it indirectly
6970 // because it allows us to elide copies. Unfortunately, MSVC makes that
6971 // impossible for small types, which it will pass in a single register or
6972 // stack slot. Most objects with dtors are large-ish, so handle that early.
6973 // We can't call out all large objects as being indirect because there are
6974 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6975 // how we pass large POD types.
6976
6977 // Note: This permits small classes with nontrivial destructors to be
6978 // passed in registers, which is non-conforming.
6979 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6980 uint64_t TypeSize = isAArch64 ? 128 : 64;
6981
6982 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
6983 S.Context.getCanonicalTagType(D)) <= TypeSize)
6984 return true;
6985 return false;
6986 }
6987
6988 // Per C++ [class.temporary]p3, the relevant condition is:
6989 // each copy constructor, move constructor, and destructor of X is
6990 // either trivial or deleted, and X has at least one non-deleted copy
6991 // or move constructor
6992 bool HasNonDeletedCopyOrMove = false;
6993
6997 return false;
6998 HasNonDeletedCopyOrMove = true;
6999 }
7000
7001 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7004 return false;
7005 HasNonDeletedCopyOrMove = true;
7006 }
7007
7010 return false;
7011
7012 for (const CXXMethodDecl *MD : D->methods()) {
7013 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7014 continue;
7015
7016 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
7017 if (CD && CD->isCopyOrMoveConstructor())
7018 HasNonDeletedCopyOrMove = true;
7019 else if (!isa<CXXDestructorDecl>(MD))
7020 continue;
7021
7022 if (!MD->isTrivialForCall())
7023 return false;
7024 }
7025
7026 return HasNonDeletedCopyOrMove;
7027}
7028
7029/// Report an error regarding overriding, along with any relevant
7030/// overridden methods.
7031///
7032/// \param DiagID the primary error to report.
7033/// \param MD the overriding method.
7034static bool
7035ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7036 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7037 bool IssuedDiagnostic = false;
7038 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7039 if (Report(O)) {
7040 if (!IssuedDiagnostic) {
7041 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7042 IssuedDiagnostic = true;
7043 }
7044 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7045 }
7046 }
7047 return IssuedDiagnostic;
7048}
7049
7051 if (!Record)
7052 return;
7053
7054 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7055 AbstractUsageInfo Info(*this, Record);
7057 }
7058
7059 // If this is not an aggregate type and has no user-declared constructor,
7060 // complain about any non-static data members of reference or const scalar
7061 // type, since they will never get initializers.
7062 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7063 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7064 !Record->isLambda()) {
7065 bool Complained = false;
7066 for (const auto *F : Record->fields()) {
7067 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7068 continue;
7069
7070 if (F->getType()->isReferenceType() ||
7071 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7072 if (!Complained) {
7073 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7074 << Record->getTagKind() << Record;
7075 Complained = true;
7076 }
7077
7078 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7079 << F->getType()->isReferenceType()
7080 << F->getDeclName();
7081 }
7082 }
7083 }
7084
7085 if (Record->getIdentifier()) {
7086 // C++ [class.mem]p13:
7087 // If T is the name of a class, then each of the following shall have a
7088 // name different from T:
7089 // - every member of every anonymous union that is a member of class T.
7090 //
7091 // C++ [class.mem]p14:
7092 // In addition, if class T has a user-declared constructor (12.1), every
7093 // non-static data member of class T shall have a name different from T.
7094 for (const NamedDecl *Element : Record->lookup(Record->getDeclName())) {
7095 const NamedDecl *D = Element->getUnderlyingDecl();
7096 // Invalid IndirectFieldDecls have already been diagnosed with
7097 // err_anonymous_record_member_redecl in
7098 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7100 Record->hasUserDeclaredConstructor()) ||
7101 (isa<IndirectFieldDecl>(D) && !D->isInvalidDecl())) {
7102 Diag(Element->getLocation(), diag::err_member_name_of_class)
7103 << D->getDeclName();
7104 break;
7105 }
7106 }
7107 }
7108
7109 // Warn if the class has virtual methods but non-virtual public destructor.
7110 if (Record->isPolymorphic() && !Record->isDependentType()) {
7111 CXXDestructorDecl *dtor = Record->getDestructor();
7112 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7113 !Record->hasAttr<FinalAttr>())
7114 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7115 diag::warn_non_virtual_dtor)
7116 << Context.getCanonicalTagType(Record);
7117 }
7118
7119 if (Record->isAbstract()) {
7120 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7121 Diag(Record->getLocation(), diag::warn_abstract_final_class)
7122 << FA->isSpelledAsSealed();
7124 }
7125 }
7126
7127 // Warn if the class has a final destructor but is not itself marked final.
7128 if (!Record->hasAttr<FinalAttr>()) {
7129 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7130 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7131 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7132 << FA->isSpelledAsSealed()
7134 getLocForEndOfToken(Record->getLocation()),
7135 (FA->isSpelledAsSealed() ? " sealed" : " final"));
7136 Diag(Record->getLocation(),
7137 diag::note_final_dtor_non_final_class_silence)
7138 << Context.getCanonicalTagType(Record) << FA->isSpelledAsSealed();
7139 }
7140 }
7141 }
7142
7143 // See if trivial_abi has to be dropped.
7144 if (Record->hasAttr<TrivialABIAttr>())
7146
7147 // Set HasTrivialSpecialMemberForCall if the record has attribute
7148 // "trivial_abi".
7149 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7150
7151 if (HasTrivialABI)
7152 Record->setHasTrivialSpecialMemberForCall();
7153
7154 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7155 // We check these last because they can depend on the properties of the
7156 // primary comparison functions (==, <=>).
7157 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7158
7159 // Perform checks that can't be done until we know all the properties of a
7160 // member function (whether it's defaulted, deleted, virtual, overriding,
7161 // ...).
7162 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7163 // A static function cannot override anything.
7164 if (MD->getStorageClass() == SC_Static) {
7165 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7166 [](const CXXMethodDecl *) { return true; }))
7167 return;
7168 }
7169
7170 // A deleted function cannot override a non-deleted function and vice
7171 // versa.
7172 if (ReportOverrides(*this,
7173 MD->isDeleted() ? diag::err_deleted_override
7174 : diag::err_non_deleted_override,
7175 MD, [&](const CXXMethodDecl *V) {
7176 return MD->isDeleted() != V->isDeleted();
7177 })) {
7178 if (MD->isDefaulted() && MD->isDeleted())
7179 // Explain why this defaulted function was deleted.
7181 return;
7182 }
7183
7184 // A consteval function cannot override a non-consteval function and vice
7185 // versa.
7186 if (ReportOverrides(*this,
7187 MD->isConsteval() ? diag::err_consteval_override
7188 : diag::err_non_consteval_override,
7189 MD, [&](const CXXMethodDecl *V) {
7190 return MD->isConsteval() != V->isConsteval();
7191 })) {
7192 if (MD->isDefaulted() && MD->isDeleted())
7193 // Explain why this defaulted function was deleted.
7195 return;
7196 }
7197 };
7198
7199 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7200 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7201 return false;
7202
7206 DefaultedSecondaryComparisons.push_back(FD);
7207 return true;
7208 }
7209
7211 return false;
7212 };
7213
7214 if (!Record->isInvalidDecl() &&
7215 Record->hasAttr<VTablePointerAuthenticationAttr>())
7217
7218 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7219 // Check whether the explicitly-defaulted members are valid.
7220 bool Incomplete = CheckForDefaultedFunction(M);
7221
7222 // Skip the rest of the checks for a member of a dependent class.
7223 if (Record->isDependentType())
7224 return;
7225
7226 // For an explicitly defaulted or deleted special member, we defer
7227 // determining triviality until the class is complete. That time is now!
7229 if (!M->isImplicit() && !M->isUserProvided()) {
7230 if (CSM != CXXSpecialMemberKind::Invalid) {
7231 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7232 // Inform the class that we've finished declaring this member.
7233 Record->finishedDefaultedOrDeletedMember(M);
7234 M->setTrivialForCall(
7235 HasTrivialABI ||
7238 Record->setTrivialForCallFlags(M);
7239 }
7240 }
7241
7242 // Set triviality for the purpose of calls if this is a user-provided
7243 // copy/move constructor or destructor.
7247 M->isUserProvided()) {
7248 M->setTrivialForCall(HasTrivialABI);
7249 Record->setTrivialForCallFlags(M);
7250 }
7251
7252 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7253 M->hasAttr<DLLExportAttr>()) {
7254 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7255 M->isTrivial() &&
7259 M->dropAttr<DLLExportAttr>();
7260
7261 if (M->hasAttr<DLLExportAttr>()) {
7262 // Define after any fields with in-class initializers have been parsed.
7264 }
7265 }
7266
7267 bool EffectivelyConstexprDestructor = true;
7268 // Avoid triggering vtable instantiation due to a dtor that is not
7269 // "effectively constexpr" for better compatibility.
7270 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7271 if (isa<CXXDestructorDecl>(M)) {
7272 llvm::SmallDenseSet<QualType> Visited;
7273 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7274 if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)
7275 return false;
7276 const CXXRecordDecl *RD =
7277 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7278 if (!RD || !RD->isCompleteDefinition())
7279 return true;
7280
7281 if (!RD->hasConstexprDestructor())
7282 return false;
7283
7284 for (const CXXBaseSpecifier &B : RD->bases())
7285 if (!Check(B.getType(), Check))
7286 return false;
7287 for (const FieldDecl *FD : RD->fields())
7288 if (!Check(FD->getType(), Check))
7289 return false;
7290 return true;
7291 };
7292 EffectivelyConstexprDestructor =
7293 Check(Context.getCanonicalTagType(Record), Check);
7294 }
7295
7296 // Define defaulted constexpr virtual functions that override a base class
7297 // function right away.
7298 // FIXME: We can defer doing this until the vtable is marked as used.
7299 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7300 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7301 EffectivelyConstexprDestructor)
7302 DefineDefaultedFunction(*this, M, M->getLocation());
7303
7304 if (!Incomplete)
7305 CheckCompletedMemberFunction(M);
7306 };
7307
7308 // Check the destructor before any other member function. We need to
7309 // determine whether it's trivial in order to determine whether the claas
7310 // type is a literal type, which is a prerequisite for determining whether
7311 // other special member functions are valid and whether they're implicitly
7312 // 'constexpr'.
7313 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7314 CompleteMemberFunction(Dtor);
7315
7316 bool HasMethodWithOverrideControl = false,
7317 HasOverridingMethodWithoutOverrideControl = false;
7318 for (auto *D : Record->decls()) {
7319 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7320 // FIXME: We could do this check for dependent types with non-dependent
7321 // bases.
7322 if (!Record->isDependentType()) {
7323 // See if a method overloads virtual methods in a base
7324 // class without overriding any.
7325 if (!M->isStatic())
7327
7328 if (M->hasAttr<OverrideAttr>()) {
7329 HasMethodWithOverrideControl = true;
7330 } else if (M->size_overridden_methods() > 0) {
7331 HasOverridingMethodWithoutOverrideControl = true;
7332 } else {
7333 // Warn on newly-declared virtual methods in `final` classes
7334 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7335 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)
7336 << M;
7337 }
7338 }
7339 }
7340
7341 if (!isa<CXXDestructorDecl>(M))
7342 CompleteMemberFunction(M);
7343 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7344 CheckForDefaultedFunction(
7345 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7346 }
7347 }
7348
7349 if (HasOverridingMethodWithoutOverrideControl) {
7350 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7351 for (auto *M : Record->methods())
7352 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7353 }
7354
7355 // Check the defaulted secondary comparisons after any other member functions.
7356 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7358
7359 // If this is a member function, we deferred checking it until now.
7360 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7361 CheckCompletedMemberFunction(MD);
7362 }
7363
7364 // {ms,gcc}_struct is a request to change ABI rules to either follow
7365 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7366 // present, we do not layout classes following foreign ABI rules, but
7367 // instead enter a special "compatibility mode", which only changes
7368 // alignments of fundamental types and layout of bit fields.
7369 // Check whether this class uses any C++ features that are implemented
7370 // completely differently in the requested ABI, and if so, emit a
7371 // diagnostic. That diagnostic defaults to an error, but we allow
7372 // projects to map it down to a warning (or ignore it). It's a fairly
7373 // common practice among users of the ms_struct pragma to
7374 // mass-annotate headers, sweeping up a bunch of types that the
7375 // project doesn't really rely on MSVC-compatible layout for. We must
7376 // therefore support "ms_struct except for C++ stuff" as a secondary
7377 // ABI.
7378 // Don't emit this diagnostic if the feature was enabled as a
7379 // language option (as opposed to via a pragma or attribute), as
7380 // the option -mms-bitfields otherwise essentially makes it impossible
7381 // to build C++ code, unless this diagnostic is turned off.
7382 if (Context.getLangOpts().getLayoutCompatibility() ==
7384 Record->isMsStruct(Context) != Context.defaultsToMsStruct() &&
7385 (Record->isPolymorphic() || Record->getNumBases())) {
7386 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7387 }
7388
7391
7392 bool ClangABICompat4 =
7393 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7395 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7396 bool CanPass = canPassInRegisters(*this, Record, CCK);
7397
7398 // Do not change ArgPassingRestrictions if it has already been set to
7399 // RecordArgPassingKind::CanNeverPassInRegs.
7400 if (Record->getArgPassingRestrictions() !=
7402 Record->setArgPassingRestrictions(
7405
7406 // If canPassInRegisters returns true despite the record having a non-trivial
7407 // destructor, the record is destructed in the callee. This happens only when
7408 // the record or one of its subobjects has a field annotated with trivial_abi
7409 // or a field qualified with ObjC __strong/__weak.
7410 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7411 Record->setParamDestroyedInCallee(true);
7412 else if (Record->hasNonTrivialDestructor())
7413 Record->setParamDestroyedInCallee(CanPass);
7414
7415 if (getLangOpts().ForceEmitVTables) {
7416 // If we want to emit all the vtables, we need to mark it as used. This
7417 // is especially required for cases like vtable assumption loads.
7418 MarkVTableUsed(Record->getInnerLocStart(), Record);
7419 }
7420
7421 if (getLangOpts().CUDA) {
7422 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7424 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7426 }
7427
7428 llvm::SmallDenseMap<OverloadedOperatorKind,
7430 TypeAwareDecls{{OO_New, {}},
7431 {OO_Array_New, {}},
7432 {OO_Delete, {}},
7433 {OO_Array_New, {}}};
7434 for (auto *D : Record->decls()) {
7435 const FunctionDecl *FnDecl = D->getAsFunction();
7436 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7437 continue;
7438 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7439 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);
7440 }
7441 auto CheckMismatchedTypeAwareAllocators =
7442 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7443 OverloadedOperatorKind DeleteKind) {
7444 auto &NewDecls = TypeAwareDecls[NewKind];
7445 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7446 if (NewDecls.empty() == DeleteDecls.empty())
7447 return;
7448 DeclarationName FoundOperator =
7449 Context.DeclarationNames.getCXXOperatorName(
7450 NewDecls.empty() ? DeleteKind : NewKind);
7451 DeclarationName MissingOperator =
7452 Context.DeclarationNames.getCXXOperatorName(
7453 NewDecls.empty() ? NewKind : DeleteKind);
7454 Diag(Record->getLocation(),
7455 diag::err_type_aware_allocator_missing_matching_operator)
7456 << FoundOperator << Context.getCanonicalTagType(Record)
7457 << MissingOperator;
7458 for (auto MD : NewDecls)
7459 Diag(MD->getLocation(),
7460 diag::note_unmatched_type_aware_allocator_declared)
7461 << MD;
7462 for (auto MD : DeleteDecls)
7463 Diag(MD->getLocation(),
7464 diag::note_unmatched_type_aware_allocator_declared)
7465 << MD;
7466 };
7467 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7468 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7469}
7470
7471/// Look up the special member function that would be called by a special
7472/// member function for a subobject of class type.
7473///
7474/// \param Class The class type of the subobject.
7475/// \param CSM The kind of special member function.
7476/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7477/// \param ConstRHS True if this is a copy operation with a const object
7478/// on its RHS, that is, if the argument to the outer special member
7479/// function is 'const' and this is not a field marked 'mutable'.
7482 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7483 bool ConstRHS) {
7484 unsigned LHSQuals = 0;
7487 LHSQuals = FieldQuals;
7488
7489 unsigned RHSQuals = FieldQuals;
7492 RHSQuals = 0;
7493 else if (ConstRHS)
7494 RHSQuals |= Qualifiers::Const;
7495
7496 return S.LookupSpecialMember(Class, CSM,
7497 RHSQuals & Qualifiers::Const,
7498 RHSQuals & Qualifiers::Volatile,
7499 false,
7500 LHSQuals & Qualifiers::Const,
7501 LHSQuals & Qualifiers::Volatile);
7502}
7503
7505 Sema &S;
7506 SourceLocation UseLoc;
7507
7508 /// A mapping from the base classes through which the constructor was
7509 /// inherited to the using shadow declaration in that base class (or a null
7510 /// pointer if the constructor was declared in that base class).
7511 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7512 InheritedFromBases;
7513
7514public:
7517 : S(S), UseLoc(UseLoc) {
7518 bool DiagnosedMultipleConstructedBases = false;
7519 CXXRecordDecl *ConstructedBase = nullptr;
7520 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7521
7522 // Find the set of such base class subobjects and check that there's a
7523 // unique constructed subobject.
7524 for (auto *D : Shadow->redecls()) {
7525 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7526 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7527 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7528
7529 InheritedFromBases.insert(
7530 std::make_pair(DNominatedBase->getCanonicalDecl(),
7531 DShadow->getNominatedBaseClassShadowDecl()));
7532 if (DShadow->constructsVirtualBase())
7533 InheritedFromBases.insert(
7534 std::make_pair(DConstructedBase->getCanonicalDecl(),
7535 DShadow->getConstructedBaseClassShadowDecl()));
7536 else
7537 assert(DNominatedBase == DConstructedBase);
7538
7539 // [class.inhctor.init]p2:
7540 // If the constructor was inherited from multiple base class subobjects
7541 // of type B, the program is ill-formed.
7542 if (!ConstructedBase) {
7543 ConstructedBase = DConstructedBase;
7544 ConstructedBaseIntroducer = D->getIntroducer();
7545 } else if (ConstructedBase != DConstructedBase &&
7546 !Shadow->isInvalidDecl()) {
7547 if (!DiagnosedMultipleConstructedBases) {
7548 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7549 << Shadow->getTargetDecl();
7550 S.Diag(ConstructedBaseIntroducer->getLocation(),
7551 diag::note_ambiguous_inherited_constructor_using)
7552 << ConstructedBase;
7553 DiagnosedMultipleConstructedBases = true;
7554 }
7555 S.Diag(D->getIntroducer()->getLocation(),
7556 diag::note_ambiguous_inherited_constructor_using)
7557 << DConstructedBase;
7558 }
7559 }
7560
7561 if (DiagnosedMultipleConstructedBases)
7562 Shadow->setInvalidDecl();
7563 }
7564
7565 /// Find the constructor to use for inherited construction of a base class,
7566 /// and whether that base class constructor inherits the constructor from a
7567 /// virtual base class (in which case it won't actually invoke it).
7568 std::pair<CXXConstructorDecl *, bool>
7570 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7571 if (It == InheritedFromBases.end())
7572 return std::make_pair(nullptr, false);
7573
7574 // This is an intermediary class.
7575 if (It->second)
7576 return std::make_pair(
7577 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7578 It->second->constructsVirtualBase());
7579
7580 // This is the base class from which the constructor was inherited.
7581 return std::make_pair(Ctor, false);
7582 }
7583};
7584
7585/// Is the special member function which would be selected to perform the
7586/// specified operation on the specified class type a constexpr constructor?
7588 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7589 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7590 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7591 // Suppress duplicate constraint checking here, in case a constraint check
7592 // caused us to decide to do this. Any truely recursive checks will get
7593 // caught during these checks anyway.
7595
7596 // If we're inheriting a constructor, see if we need to call it for this base
7597 // class.
7598 if (InheritedCtor) {
7600 auto BaseCtor =
7601 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7602 if (BaseCtor)
7603 return BaseCtor->isConstexpr();
7604 }
7605
7607 return ClassDecl->hasConstexprDefaultConstructor();
7609 return ClassDecl->hasConstexprDestructor();
7610
7612 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7613 if (!SMOR.getMethod())
7614 // A constructor we wouldn't select can't be "involved in initializing"
7615 // anything.
7616 return true;
7617 return SMOR.getMethod()->isConstexpr();
7618}
7619
7620/// Determine whether the specified special member function would be constexpr
7621/// if it were implicitly defined.
7623 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7624 CXXConstructorDecl *InheritedCtor = nullptr,
7625 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7626 if (!S.getLangOpts().CPlusPlus11)
7627 return false;
7628
7629 // C++11 [dcl.constexpr]p4:
7630 // In the definition of a constexpr constructor [...]
7631 bool Ctor = true;
7632 switch (CSM) {
7634 if (Inherited)
7635 break;
7636 // Since default constructor lookup is essentially trivial (and cannot
7637 // involve, for instance, template instantiation), we compute whether a
7638 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7639 //
7640 // This is important for performance; we need to know whether the default
7641 // constructor is constexpr to determine whether the type is a literal type.
7642 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7643
7646 // For copy or move constructors, we need to perform overload resolution.
7647 break;
7648
7651 if (!S.getLangOpts().CPlusPlus14)
7652 return false;
7653 // In C++1y, we need to perform overload resolution.
7654 Ctor = false;
7655 break;
7656
7658 return ClassDecl->defaultedDestructorIsConstexpr();
7659
7661 return false;
7662 }
7663
7664 // -- if the class is a non-empty union, or for each non-empty anonymous
7665 // union member of a non-union class, exactly one non-static data member
7666 // shall be initialized; [DR1359]
7667 //
7668 // If we squint, this is guaranteed, since exactly one non-static data member
7669 // will be initialized (if the constructor isn't deleted), we just don't know
7670 // which one.
7671 if (Ctor && ClassDecl->isUnion())
7673 ? ClassDecl->hasInClassInitializer() ||
7674 !ClassDecl->hasVariantMembers()
7675 : true;
7676
7677 // -- the class shall not have any virtual base classes;
7678 if (Ctor && ClassDecl->getNumVBases())
7679 return false;
7680
7681 // C++1y [class.copy]p26:
7682 // -- [the class] is a literal type, and
7683 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7684 return false;
7685
7686 // -- every constructor involved in initializing [...] base class
7687 // sub-objects shall be a constexpr constructor;
7688 // -- the assignment operator selected to copy/move each direct base
7689 // class is a constexpr function, and
7690 if (!S.getLangOpts().CPlusPlus23) {
7691 for (const auto &B : ClassDecl->bases()) {
7692 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7693 if (!BaseClassDecl)
7694 continue;
7695 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7696 InheritedCtor, Inherited))
7697 return false;
7698 }
7699 }
7700
7701 // -- every constructor involved in initializing non-static data members
7702 // [...] shall be a constexpr constructor;
7703 // -- every non-static data member and base class sub-object shall be
7704 // initialized
7705 // -- for each non-static data member of X that is of class type (or array
7706 // thereof), the assignment operator selected to copy/move that member is
7707 // a constexpr function
7708 if (!S.getLangOpts().CPlusPlus23) {
7709 for (const auto *F : ClassDecl->fields()) {
7710 if (F->isInvalidDecl())
7711 continue;
7713 F->hasInClassInitializer())
7714 continue;
7715 QualType BaseType = S.Context.getBaseElementType(F->getType());
7716 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7717 auto *FieldRecDecl =
7718 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();
7719 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7720 BaseType.getCVRQualifiers(),
7721 ConstArg && !F->isMutable()))
7722 return false;
7723 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7724 return false;
7725 }
7726 }
7727 }
7728
7729 // All OK, it's constexpr!
7730 return true;
7731}
7732
7733namespace {
7734/// RAII object to register a defaulted function as having its exception
7735/// specification computed.
7736struct ComputingExceptionSpec {
7737 Sema &S;
7738
7739 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7740 : S(S) {
7741 Sema::CodeSynthesisContext Ctx;
7743 Ctx.PointOfInstantiation = Loc;
7744 Ctx.Entity = FD;
7746 }
7747 ~ComputingExceptionSpec() {
7749 }
7750};
7751}
7752
7753static Sema::ImplicitExceptionSpecification
7754ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7755 CXXMethodDecl *MD,
7757 Sema::InheritedConstructorInfo *ICI);
7758
7759static Sema::ImplicitExceptionSpecification
7760ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7761 FunctionDecl *FD,
7763
7764static Sema::ImplicitExceptionSpecification
7766 auto DFK = S.getDefaultedFunctionKind(FD);
7767 if (DFK.isSpecialMember())
7769 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7770 if (DFK.isComparison())
7772 DFK.asComparison());
7773
7774 auto *CD = cast<CXXConstructorDecl>(FD);
7775 assert(CD->getInheritedConstructor() &&
7776 "only defaulted functions and inherited constructors have implicit "
7777 "exception specs");
7779 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7782}
7783
7785 CXXMethodDecl *MD) {
7787
7788 // Build an exception specification pointing back at this member.
7790 EPI.ExceptionSpec.SourceDecl = MD;
7791
7792 // Set the calling convention to the default for C++ instance methods.
7794 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7795 /*IsCXXMethod=*/true));
7796 return EPI;
7797}
7798
7800 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7802 return;
7803
7804 // Evaluate the exception specification.
7805 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7806 auto ESI = IES.getExceptionSpec();
7807
7808 // Update the type of the special member to use it.
7809 UpdateExceptionSpec(FD, ESI);
7810}
7811
7813 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7814
7816 if (!DefKind) {
7817 assert(FD->getDeclContext()->isDependentContext());
7818 return;
7819 }
7820
7821 if (DefKind.isComparison()) {
7822 auto PT = FD->getParamDecl(0)->getType();
7823 if (const CXXRecordDecl *RD =
7824 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7825 for (FieldDecl *Field : RD->fields()) {
7826 UnusedPrivateFields.remove(Field);
7827 }
7828 }
7829 }
7830
7831 if (DefKind.isSpecialMember()
7833 DefKind.asSpecialMember(),
7834 FD->getDefaultLoc())
7836 FD->setInvalidDecl();
7837}
7838
7841 SourceLocation DefaultLoc) {
7842 CXXRecordDecl *RD = MD->getParent();
7843
7845 "not an explicitly-defaulted special member");
7846
7847 // Defer all checking for special members of a dependent type.
7848 if (RD->isDependentType())
7849 return false;
7850
7851 // Whether this was the first-declared instance of the constructor.
7852 // This affects whether we implicitly add an exception spec and constexpr.
7853 bool First = MD == MD->getCanonicalDecl();
7854
7855 bool HadError = false;
7856
7857 // C++11 [dcl.fct.def.default]p1:
7858 // A function that is explicitly defaulted shall
7859 // -- be a special member function [...] (checked elsewhere),
7860 // -- have the same type (except for ref-qualifiers, and except that a
7861 // copy operation can take a non-const reference) as an implicit
7862 // declaration, and
7863 // -- not have default arguments.
7864 // C++2a changes the second bullet to instead delete the function if it's
7865 // defaulted on its first declaration, unless it's "an assignment operator,
7866 // and its return type differs or its parameter type is not a reference".
7867 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7868 bool ShouldDeleteForTypeMismatch = false;
7869 unsigned ExpectedParams = 1;
7872 ExpectedParams = 0;
7873 if (MD->getNumExplicitParams() != ExpectedParams) {
7874 // This checks for default arguments: a copy or move constructor with a
7875 // default argument is classified as a default constructor, and assignment
7876 // operations and destructors can't have default arguments.
7877 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7878 << CSM << MD->getSourceRange();
7879 HadError = true;
7880 } else if (MD->isVariadic()) {
7881 if (DeleteOnTypeMismatch)
7882 ShouldDeleteForTypeMismatch = true;
7883 else {
7884 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7885 << CSM << MD->getSourceRange();
7886 HadError = true;
7887 }
7888 }
7889
7891
7892 bool CanHaveConstParam = false;
7894 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7896 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7897
7898 QualType ReturnType = Context.VoidTy;
7901 // Check for return type matching.
7902 ReturnType = Type->getReturnType();
7904
7905 QualType DeclType =
7907 /*Qualifier=*/std::nullopt, RD, /*OwnsTag=*/false);
7908 DeclType = Context.getAddrSpaceQualType(
7909 DeclType, ThisType.getQualifiers().getAddressSpace());
7910 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7911
7912 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7913 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7915 << ExpectedReturnType;
7916 HadError = true;
7917 }
7918
7919 // A defaulted special member cannot have cv-qualifiers.
7920 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7921 if (DeleteOnTypeMismatch)
7922 ShouldDeleteForTypeMismatch = true;
7923 else {
7924 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7926 << getLangOpts().CPlusPlus14;
7927 HadError = true;
7928 }
7929 }
7930 // [C++23][dcl.fct.def.default]/p2.2
7931 // if F2 has an implicit object parameter of type “reference to C”,
7932 // F1 may be an explicit object member function whose explicit object
7933 // parameter is of (possibly different) type “reference to C”,
7934 // in which case the type of F1 would differ from the type of F2
7935 // in that the type of F1 has an additional parameter;
7936 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7937 ? MD->getParamDecl(0)->getType()
7938 : QualType();
7939 if (!ExplicitObjectParameter.isNull() &&
7940 (!ExplicitObjectParameter->isReferenceType() ||
7941 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),
7942 Context.getCanonicalTagType(RD)))) {
7943 if (DeleteOnTypeMismatch)
7944 ShouldDeleteForTypeMismatch = true;
7945 else {
7946 Diag(MD->getLocation(),
7947 diag::err_defaulted_special_member_explicit_object_mismatch)
7948 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7949 << MD->getSourceRange();
7950 HadError = true;
7951 }
7952 }
7953 }
7954
7955 // Check for parameter type matching.
7957 ExpectedParams
7958 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7959 : QualType();
7960 bool HasConstParam = false;
7961 if (ExpectedParams && ArgType->isReferenceType()) {
7962 // Argument must be reference to possibly-const T.
7963 QualType ReferentType = ArgType->getPointeeType();
7964 HasConstParam = ReferentType.isConstQualified();
7965
7966 if (ReferentType.isVolatileQualified()) {
7967 if (DeleteOnTypeMismatch)
7968 ShouldDeleteForTypeMismatch = true;
7969 else {
7970 Diag(MD->getLocation(),
7971 diag::err_defaulted_special_member_volatile_param)
7972 << CSM;
7973 HadError = true;
7974 }
7975 }
7976
7977 if (HasConstParam && !CanHaveConstParam) {
7978 if (DeleteOnTypeMismatch)
7979 ShouldDeleteForTypeMismatch = true;
7980 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7982 Diag(MD->getLocation(),
7983 diag::err_defaulted_special_member_copy_const_param)
7985 // FIXME: Explain why this special member can't be const.
7986 HadError = true;
7987 } else {
7988 Diag(MD->getLocation(),
7989 diag::err_defaulted_special_member_move_const_param)
7991 HadError = true;
7992 }
7993 }
7994 } else if (ExpectedParams) {
7995 // A copy assignment operator can take its argument by value, but a
7996 // defaulted one cannot.
7998 "unexpected non-ref argument");
7999 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
8000 HadError = true;
8001 }
8002
8003 // C++11 [dcl.fct.def.default]p2:
8004 // An explicitly-defaulted function may be declared constexpr only if it
8005 // would have been implicitly declared as constexpr,
8006 // Do not apply this rule to members of class templates, since core issue 1358
8007 // makes such functions always instantiate to constexpr functions. For
8008 // functions which cannot be constexpr (for non-constructors in C++11 and for
8009 // destructors in C++14 and C++17), this is checked elsewhere.
8010 //
8011 // FIXME: This should not apply if the member is deleted.
8012 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
8013 HasConstParam);
8014
8015 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8016 // If the instantiated template specialization of a constexpr function
8017 // template or member function of a class template would fail to satisfy
8018 // the requirements for a constexpr function or constexpr constructor, that
8019 // specialization is still a constexpr function or constexpr constructor,
8020 // even though a call to such a function cannot appear in a constant
8021 // expression.
8022 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8023 Constexpr = true;
8024
8025 if ((getLangOpts().CPlusPlus20 ||
8027 : isa<CXXConstructorDecl>(MD))) &&
8028 MD->isConstexpr() && !Constexpr &&
8030 if (!MD->isConsteval() && RD->getNumVBases()) {
8031 Diag(MD->getBeginLoc(),
8032 diag::err_incorrect_defaulted_constexpr_with_vb)
8033 << CSM;
8034 for (const auto &I : RD->vbases())
8035 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
8036 } else {
8037 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
8038 << CSM << MD->isConsteval();
8039 }
8040 HadError = true;
8041 // FIXME: Explain why the special member can't be constexpr.
8042 }
8043
8044 if (First) {
8045 // C++2a [dcl.fct.def.default]p3:
8046 // If a function is explicitly defaulted on its first declaration, it is
8047 // implicitly considered to be constexpr if the implicit declaration
8048 // would be.
8053
8054 if (!Type->hasExceptionSpec()) {
8055 // C++2a [except.spec]p3:
8056 // If a declaration of a function does not have a noexcept-specifier
8057 // [and] is defaulted on its first declaration, [...] the exception
8058 // specification is as specified below
8059 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8061 EPI.ExceptionSpec.SourceDecl = MD;
8062 MD->setType(
8063 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
8064 }
8065 }
8066
8067 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8068 if (First) {
8069 SetDeclDeleted(MD, MD->getLocation());
8070 if (!inTemplateInstantiation() && !HadError) {
8071 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
8072 if (ShouldDeleteForTypeMismatch) {
8073 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
8074 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
8075 /*Diagnose*/ true) &&
8076 DefaultLoc.isValid()) {
8077 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
8078 << FixItHint::CreateReplacement(DefaultLoc, "delete");
8079 }
8080 }
8081 if (ShouldDeleteForTypeMismatch && !HadError) {
8082 Diag(MD->getLocation(),
8083 diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8084 << CSM;
8085 }
8086 } else {
8087 // C++11 [dcl.fct.def.default]p4:
8088 // [For a] user-provided explicitly-defaulted function [...] if such a
8089 // function is implicitly defined as deleted, the program is ill-formed.
8090 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
8091 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8092 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
8093 HadError = true;
8094 }
8095 }
8096
8097 return HadError;
8098}
8099
8100namespace {
8101/// Helper class for building and checking a defaulted comparison.
8102///
8103/// Defaulted functions are built in two phases:
8104///
8105/// * First, the set of operations that the function will perform are
8106/// identified, and some of them are checked. If any of the checked
8107/// operations is invalid in certain ways, the comparison function is
8108/// defined as deleted and no body is built.
8109/// * Then, if the function is not defined as deleted, the body is built.
8110///
8111/// This is accomplished by performing two visitation steps over the eventual
8112/// body of the function.
8113template<typename Derived, typename ResultList, typename Result,
8114 typename Subobject>
8115class DefaultedComparisonVisitor {
8116public:
8117 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
8118
8119 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8120 DefaultedComparisonKind DCK)
8121 : S(S), RD(RD), FD(FD), DCK(DCK) {
8122 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8123 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8124 // UnresolvedSet to avoid this copy.
8125 Fns.assign(Info->getUnqualifiedLookups().begin(),
8126 Info->getUnqualifiedLookups().end());
8127 }
8128 }
8129
8130 ResultList visit() {
8131 // The type of an lvalue naming a parameter of this function.
8132 QualType ParamLvalType =
8134
8135 ResultList Results;
8136
8137 switch (DCK) {
8138 case DefaultedComparisonKind::None:
8139 llvm_unreachable("not a defaulted comparison");
8140
8141 case DefaultedComparisonKind::Equal:
8142 case DefaultedComparisonKind::ThreeWay:
8143 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8144 return Results;
8145
8146 case DefaultedComparisonKind::NotEqual:
8147 case DefaultedComparisonKind::Relational:
8148 Results.add(getDerived().visitExpandedSubobject(
8149 ParamLvalType, getDerived().getCompleteObject()));
8150 return Results;
8151 }
8152 llvm_unreachable("");
8153 }
8154
8155protected:
8156 Derived &getDerived() { return static_cast<Derived&>(*this); }
8157
8158 /// Visit the expanded list of subobjects of the given type, as specified in
8159 /// C++2a [class.compare.default].
8160 ///
8161 /// \return \c true if the ResultList object said we're done, \c false if not.
8162 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8163 Qualifiers Quals) {
8164 // C++2a [class.compare.default]p4:
8165 // The direct base class subobjects of C
8166 for (CXXBaseSpecifier &Base : Record->bases())
8167 if (Results.add(getDerived().visitSubobject(
8168 S.Context.getQualifiedType(Base.getType(), Quals),
8169 getDerived().getBase(&Base))))
8170 return true;
8171
8172 // followed by the non-static data members of C
8173 for (FieldDecl *Field : Record->fields()) {
8174 // C++23 [class.bit]p2:
8175 // Unnamed bit-fields are not members ...
8176 if (Field->isUnnamedBitField())
8177 continue;
8178 // Recursively expand anonymous structs.
8179 if (Field->isAnonymousStructOrUnion()) {
8180 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8181 Quals))
8182 return true;
8183 continue;
8184 }
8185
8186 // Figure out the type of an lvalue denoting this field.
8187 Qualifiers FieldQuals = Quals;
8188 if (Field->isMutable())
8189 FieldQuals.removeConst();
8190 QualType FieldType =
8191 S.Context.getQualifiedType(Field->getType(), FieldQuals);
8192
8193 if (Results.add(getDerived().visitSubobject(
8194 FieldType, getDerived().getField(Field))))
8195 return true;
8196 }
8197
8198 // form a list of subobjects.
8199 return false;
8200 }
8201
8202 Result visitSubobject(QualType Type, Subobject Subobj) {
8203 // In that list, any subobject of array type is recursively expanded
8204 const ArrayType *AT = S.Context.getAsArrayType(Type);
8205 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8206 return getDerived().visitSubobjectArray(CAT->getElementType(),
8207 CAT->getSize(), Subobj);
8208 return getDerived().visitExpandedSubobject(Type, Subobj);
8209 }
8210
8211 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8212 Subobject Subobj) {
8213 return getDerived().visitSubobject(Type, Subobj);
8214 }
8215
8216protected:
8217 Sema &S;
8218 CXXRecordDecl *RD;
8219 FunctionDecl *FD;
8220 DefaultedComparisonKind DCK;
8221 UnresolvedSet<16> Fns;
8222};
8223
8224/// Information about a defaulted comparison, as determined by
8225/// DefaultedComparisonAnalyzer.
8226struct DefaultedComparisonInfo {
8227 bool Deleted = false;
8228 bool Constexpr = true;
8229 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8230
8231 static DefaultedComparisonInfo deleted() {
8232 DefaultedComparisonInfo Deleted;
8233 Deleted.Deleted = true;
8234 return Deleted;
8235 }
8236
8237 bool add(const DefaultedComparisonInfo &R) {
8238 Deleted |= R.Deleted;
8239 Constexpr &= R.Constexpr;
8240 Category = commonComparisonType(Category, R.Category);
8241 return Deleted;
8242 }
8243};
8244
8245/// An element in the expanded list of subobjects of a defaulted comparison, as
8246/// specified in C++2a [class.compare.default]p4.
8247struct DefaultedComparisonSubobject {
8248 enum { CompleteObject, Member, Base } Kind;
8249 NamedDecl *Decl;
8250 SourceLocation Loc;
8251};
8252
8253/// A visitor over the notional body of a defaulted comparison that determines
8254/// whether that body would be deleted or constexpr.
8255class DefaultedComparisonAnalyzer
8256 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8257 DefaultedComparisonInfo,
8258 DefaultedComparisonInfo,
8259 DefaultedComparisonSubobject> {
8260public:
8261 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8262
8263private:
8264 DiagnosticKind Diagnose;
8265
8266public:
8267 using Base = DefaultedComparisonVisitor;
8268 using Result = DefaultedComparisonInfo;
8269 using Subobject = DefaultedComparisonSubobject;
8270
8271 friend Base;
8272
8273 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8274 DefaultedComparisonKind DCK,
8275 DiagnosticKind Diagnose = NoDiagnostics)
8276 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8277
8278 Result visit() {
8279 if ((DCK == DefaultedComparisonKind::Equal ||
8280 DCK == DefaultedComparisonKind::ThreeWay) &&
8281 RD->hasVariantMembers()) {
8282 // C++2a [class.compare.default]p2 [P2002R0]:
8283 // A defaulted comparison operator function for class C is defined as
8284 // deleted if [...] C has variant members.
8285 if (Diagnose == ExplainDeleted) {
8286 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8287 << FD << RD->isUnion() << RD;
8288 }
8289 return Result::deleted();
8290 }
8291
8292 return Base::visit();
8293 }
8294
8295private:
8296 Subobject getCompleteObject() {
8297 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8298 }
8299
8300 Subobject getBase(CXXBaseSpecifier *Base) {
8301 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8302 Base->getBaseTypeLoc()};
8303 }
8304
8305 Subobject getField(FieldDecl *Field) {
8306 return Subobject{Subobject::Member, Field, Field->getLocation()};
8307 }
8308
8309 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8310 // C++2a [class.compare.default]p2 [P2002R0]:
8311 // A defaulted <=> or == operator function for class C is defined as
8312 // deleted if any non-static data member of C is of reference type
8313 if (Type->isReferenceType()) {
8314 if (Diagnose == ExplainDeleted) {
8315 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8316 << FD << RD;
8317 }
8318 return Result::deleted();
8319 }
8320
8321 // [...] Let xi be an lvalue denoting the ith element [...]
8322 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8323 Expr *Args[] = {&Xi, &Xi};
8324
8325 // All operators start by trying to apply that same operator recursively.
8327 assert(OO != OO_None && "not an overloaded operator!");
8328 return visitBinaryOperator(OO, Args, Subobj);
8329 }
8330
8331 Result
8332 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8333 Subobject Subobj,
8334 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8335 // Note that there is no need to consider rewritten candidates here if
8336 // we've already found there is no viable 'operator<=>' candidate (and are
8337 // considering synthesizing a '<=>' from '==' and '<').
8338 OverloadCandidateSet CandidateSet(
8340 OverloadCandidateSet::OperatorRewriteInfo(
8341 OO, FD->getLocation(),
8342 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8343
8344 /// C++2a [class.compare.default]p1 [P2002R0]:
8345 /// [...] the defaulted function itself is never a candidate for overload
8346 /// resolution [...]
8347 CandidateSet.exclude(FD);
8348
8349 if (Args[0]->getType()->isOverloadableType())
8350 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8351 else
8352 // FIXME: We determine whether this is a valid expression by checking to
8353 // see if there's a viable builtin operator candidate for it. That isn't
8354 // really what the rules ask us to do, but should give the right results.
8355 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8356
8357 Result R;
8358
8360 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8361 case OR_Success: {
8362 // C++2a [class.compare.secondary]p2 [P2002R0]:
8363 // The operator function [...] is defined as deleted if [...] the
8364 // candidate selected by overload resolution is not a rewritten
8365 // candidate.
8366 if ((DCK == DefaultedComparisonKind::NotEqual ||
8367 DCK == DefaultedComparisonKind::Relational) &&
8368 !Best->RewriteKind) {
8369 if (Diagnose == ExplainDeleted) {
8370 if (Best->Function) {
8371 S.Diag(Best->Function->getLocation(),
8372 diag::note_defaulted_comparison_not_rewritten_callee)
8373 << FD;
8374 } else {
8375 assert(Best->Conversions.size() == 2 &&
8376 Best->Conversions[0].isUserDefined() &&
8377 "non-user-defined conversion from class to built-in "
8378 "comparison");
8379 S.Diag(Best->Conversions[0]
8380 .UserDefined.FoundConversionFunction.getDecl()
8381 ->getLocation(),
8382 diag::note_defaulted_comparison_not_rewritten_conversion)
8383 << FD;
8384 }
8385 }
8386 return Result::deleted();
8387 }
8388
8389 // Throughout C++2a [class.compare]: if overload resolution does not
8390 // result in a usable function, the candidate function is defined as
8391 // deleted. This requires that we selected an accessible function.
8392 //
8393 // Note that this only considers the access of the function when named
8394 // within the type of the subobject, and not the access path for any
8395 // derived-to-base conversion.
8396 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8397 if (ArgClass && Best->FoundDecl.getDecl() &&
8398 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8399 QualType ObjectType = Subobj.Kind == Subobject::Member
8400 ? Args[0]->getType()
8403 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8404 Diagnose == ExplainDeleted
8405 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8406 << FD << Subobj.Kind << Subobj.Decl
8407 : S.PDiag()))
8408 return Result::deleted();
8409 }
8410
8411 bool NeedsDeducing =
8412 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8413
8414 if (FunctionDecl *BestFD = Best->Function) {
8415 // C++2a [class.compare.default]p3 [P2002R0]:
8416 // A defaulted comparison function is constexpr-compatible if
8417 // [...] no overlod resolution performed [...] results in a
8418 // non-constexpr function.
8419 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8420 // If it's not constexpr, explain why not.
8421 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8422 if (Subobj.Kind != Subobject::CompleteObject)
8423 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8424 << Subobj.Kind << Subobj.Decl;
8425 S.Diag(BestFD->getLocation(),
8426 diag::note_defaulted_comparison_not_constexpr_here);
8427 // Bail out after explaining; we don't want any more notes.
8428 return Result::deleted();
8429 }
8430 R.Constexpr &= BestFD->isConstexpr();
8431
8432 if (NeedsDeducing) {
8433 // If any callee has an undeduced return type, deduce it now.
8434 // FIXME: It's not clear how a failure here should be handled. For
8435 // now, we produce an eager diagnostic, because that is forward
8436 // compatible with most (all?) other reasonable options.
8437 if (BestFD->getReturnType()->isUndeducedType() &&
8438 S.DeduceReturnType(BestFD, FD->getLocation(),
8439 /*Diagnose=*/false)) {
8440 // Don't produce a duplicate error when asked to explain why the
8441 // comparison is deleted: we diagnosed that when initially checking
8442 // the defaulted operator.
8443 if (Diagnose == NoDiagnostics) {
8444 S.Diag(
8445 FD->getLocation(),
8446 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8447 << Subobj.Kind << Subobj.Decl;
8448 S.Diag(
8449 Subobj.Loc,
8450 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8451 << Subobj.Kind << Subobj.Decl;
8452 S.Diag(BestFD->getLocation(),
8453 diag::note_defaulted_comparison_cannot_deduce_callee)
8454 << Subobj.Kind << Subobj.Decl;
8455 }
8456 return Result::deleted();
8457 }
8459 BestFD->getCallResultType());
8460 if (!Info) {
8461 if (Diagnose == ExplainDeleted) {
8462 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8463 << Subobj.Kind << Subobj.Decl
8464 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8465 S.Diag(BestFD->getLocation(),
8466 diag::note_defaulted_comparison_cannot_deduce_callee)
8467 << Subobj.Kind << Subobj.Decl;
8468 }
8469 return Result::deleted();
8470 }
8471 R.Category = Info->Kind;
8472 }
8473 } else {
8474 QualType T = Best->BuiltinParamTypes[0];
8475 assert(T == Best->BuiltinParamTypes[1] &&
8476 "builtin comparison for different types?");
8477 assert(Best->BuiltinParamTypes[2].isNull() &&
8478 "invalid builtin comparison");
8479
8480 // FIXME: If the type we deduced is a vector type, we mark the
8481 // comparison as deleted because we don't yet support this.
8482 if (isa<VectorType>(T)) {
8483 if (Diagnose == ExplainDeleted) {
8484 S.Diag(FD->getLocation(),
8485 diag::note_defaulted_comparison_vector_types)
8486 << FD;
8487 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);
8488 }
8489 return Result::deleted();
8490 }
8491
8492 if (NeedsDeducing) {
8493 std::optional<ComparisonCategoryType> Cat =
8495 assert(Cat && "no category for builtin comparison?");
8496 R.Category = *Cat;
8497 }
8498 }
8499
8500 // Note that we might be rewriting to a different operator. That call is
8501 // not considered until we come to actually build the comparison function.
8502 break;
8503 }
8504
8505 case OR_Ambiguous:
8506 if (Diagnose == ExplainDeleted) {
8507 unsigned Kind = 0;
8508 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8509 Kind = OO == OO_EqualEqual ? 1 : 2;
8510 CandidateSet.NoteCandidates(
8512 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8513 << FD << Kind << Subobj.Kind << Subobj.Decl),
8514 S, OCD_AmbiguousCandidates, Args);
8515 }
8516 R = Result::deleted();
8517 break;
8518
8519 case OR_Deleted:
8520 if (Diagnose == ExplainDeleted) {
8521 if ((DCK == DefaultedComparisonKind::NotEqual ||
8522 DCK == DefaultedComparisonKind::Relational) &&
8523 !Best->RewriteKind) {
8524 S.Diag(Best->Function->getLocation(),
8525 diag::note_defaulted_comparison_not_rewritten_callee)
8526 << FD;
8527 } else {
8528 S.Diag(Subobj.Loc,
8529 diag::note_defaulted_comparison_calls_deleted)
8530 << FD << Subobj.Kind << Subobj.Decl;
8531 S.NoteDeletedFunction(Best->Function);
8532 }
8533 }
8534 R = Result::deleted();
8535 break;
8536
8538 // If there's no usable candidate, we're done unless we can rewrite a
8539 // '<=>' in terms of '==' and '<'.
8540 if (OO == OO_Spaceship &&
8542 // For any kind of comparison category return type, we need a usable
8543 // '==' and a usable '<'.
8544 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8545 &CandidateSet)))
8546 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8547 break;
8548 }
8549
8550 if (Diagnose == ExplainDeleted) {
8551 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8552 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8553 << Subobj.Kind << Subobj.Decl;
8554
8555 // For a three-way comparison, list both the candidates for the
8556 // original operator and the candidates for the synthesized operator.
8557 if (SpaceshipCandidates) {
8558 SpaceshipCandidates->NoteCandidates(
8559 S, Args,
8560 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8561 Args, FD->getLocation()));
8562 S.Diag(Subobj.Loc,
8563 diag::note_defaulted_comparison_no_viable_function_synthesized)
8564 << (OO == OO_EqualEqual ? 0 : 1);
8565 }
8566
8567 CandidateSet.NoteCandidates(
8568 S, Args,
8569 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8570 FD->getLocation()));
8571 }
8572 R = Result::deleted();
8573 break;
8574 }
8575
8576 return R;
8577 }
8578};
8579
8580/// A list of statements.
8581struct StmtListResult {
8582 bool IsInvalid = false;
8583 llvm::SmallVector<Stmt*, 16> Stmts;
8584
8585 bool add(const StmtResult &S) {
8586 IsInvalid |= S.isInvalid();
8587 if (IsInvalid)
8588 return true;
8589 Stmts.push_back(S.get());
8590 return false;
8591 }
8592};
8593
8594/// A visitor over the notional body of a defaulted comparison that synthesizes
8595/// the actual body.
8596class DefaultedComparisonSynthesizer
8597 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8598 StmtListResult, StmtResult,
8599 std::pair<ExprResult, ExprResult>> {
8600 SourceLocation Loc;
8601 unsigned ArrayDepth = 0;
8602
8603public:
8604 using Base = DefaultedComparisonVisitor;
8605 using ExprPair = std::pair<ExprResult, ExprResult>;
8606
8607 friend Base;
8608
8609 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8610 DefaultedComparisonKind DCK,
8611 SourceLocation BodyLoc)
8612 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8613
8614 /// Build a suitable function body for this defaulted comparison operator.
8615 StmtResult build() {
8616 Sema::CompoundScopeRAII CompoundScope(S);
8617
8618 StmtListResult Stmts = visit();
8619 if (Stmts.IsInvalid)
8620 return StmtError();
8621
8622 ExprResult RetVal;
8623 switch (DCK) {
8624 case DefaultedComparisonKind::None:
8625 llvm_unreachable("not a defaulted comparison");
8626
8627 case DefaultedComparisonKind::Equal: {
8628 // C++2a [class.eq]p3:
8629 // [...] compar[e] the corresponding elements [...] until the first
8630 // index i where xi == yi yields [...] false. If no such index exists,
8631 // V is true. Otherwise, V is false.
8632 //
8633 // Join the comparisons with '&&'s and return the result. Use a right
8634 // fold (traversing the conditions right-to-left), because that
8635 // short-circuits more naturally.
8636 auto OldStmts = std::move(Stmts.Stmts);
8637 Stmts.Stmts.clear();
8638 ExprResult CmpSoFar;
8639 // Finish a particular comparison chain.
8640 auto FinishCmp = [&] {
8641 if (Expr *Prior = CmpSoFar.get()) {
8642 // Convert the last expression to 'return ...;'
8643 if (RetVal.isUnset() && Stmts.Stmts.empty())
8644 RetVal = CmpSoFar;
8645 // Convert any prior comparison to 'if (!(...)) return false;'
8646 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8647 return true;
8648 CmpSoFar = ExprResult();
8649 }
8650 return false;
8651 };
8652 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8653 Expr *E = dyn_cast<Expr>(EAsStmt);
8654 if (!E) {
8655 // Found an array comparison.
8656 if (FinishCmp() || Stmts.add(EAsStmt))
8657 return StmtError();
8658 continue;
8659 }
8660
8661 if (CmpSoFar.isUnset()) {
8662 CmpSoFar = E;
8663 continue;
8664 }
8665 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8666 if (CmpSoFar.isInvalid())
8667 return StmtError();
8668 }
8669 if (FinishCmp())
8670 return StmtError();
8671 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8672 // If no such index exists, V is true.
8673 if (RetVal.isUnset())
8674 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8675 break;
8676 }
8677
8678 case DefaultedComparisonKind::ThreeWay: {
8679 // Per C++2a [class.spaceship]p3, as a fallback add:
8680 // return static_cast<R>(std::strong_ordering::equal);
8681 QualType StrongOrdering = S.CheckComparisonCategoryType(
8682 ComparisonCategoryType::StrongOrdering, Loc,
8683 Sema::ComparisonCategoryUsage::DefaultedOperator);
8684 if (StrongOrdering.isNull())
8685 return StmtError();
8686 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8687 .getValueInfo(ComparisonCategoryResult::Equal)
8688 ->VD;
8689 RetVal = getDecl(EqualVD);
8690 if (RetVal.isInvalid())
8691 return StmtError();
8692 RetVal = buildStaticCastToR(RetVal.get());
8693 break;
8694 }
8695
8696 case DefaultedComparisonKind::NotEqual:
8697 case DefaultedComparisonKind::Relational:
8698 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8699 break;
8700 }
8701
8702 // Build the final return statement.
8703 if (RetVal.isInvalid())
8704 return StmtError();
8705 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8706 if (ReturnStmt.isInvalid())
8707 return StmtError();
8708 Stmts.Stmts.push_back(ReturnStmt.get());
8709
8710 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8711 }
8712
8713private:
8714 ExprResult getDecl(ValueDecl *VD) {
8715 return S.BuildDeclarationNameExpr(
8716 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8717 }
8718
8719 ExprResult getParam(unsigned I) {
8720 ParmVarDecl *PD = FD->getParamDecl(I);
8721 return getDecl(PD);
8722 }
8723
8724 ExprPair getCompleteObject() {
8725 unsigned Param = 0;
8726 ExprResult LHS;
8727 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8728 MD && MD->isImplicitObjectMemberFunction()) {
8729 // LHS is '*this'.
8730 LHS = S.ActOnCXXThis(Loc);
8731 if (!LHS.isInvalid())
8732 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8733 } else {
8734 LHS = getParam(Param++);
8735 }
8736 ExprResult RHS = getParam(Param++);
8737 assert(Param == FD->getNumParams());
8738 return {LHS, RHS};
8739 }
8740
8741 ExprPair getBase(CXXBaseSpecifier *Base) {
8742 ExprPair Obj = getCompleteObject();
8743 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8744 return {ExprError(), ExprError()};
8745 CXXCastPath Path = {Base};
8746 const auto CastToBase = [&](Expr *E) {
8747 QualType ToType = S.Context.getQualifiedType(
8748 Base->getType(), E->getType().getQualifiers());
8749 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);
8750 };
8751 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8752 }
8753
8754 ExprPair getField(FieldDecl *Field) {
8755 ExprPair Obj = getCompleteObject();
8756 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8757 return {ExprError(), ExprError()};
8758
8759 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8760 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8761 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8762 CXXScopeSpec(), Field, Found, NameInfo),
8763 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8764 CXXScopeSpec(), Field, Found, NameInfo)};
8765 }
8766
8767 // FIXME: When expanding a subobject, register a note in the code synthesis
8768 // stack to say which subobject we're comparing.
8769
8770 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8771 if (Cond.isInvalid())
8772 return StmtError();
8773
8774 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8775 if (NotCond.isInvalid())
8776 return StmtError();
8777
8778 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8779 assert(!False.isInvalid() && "should never fail");
8780 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8781 if (ReturnFalse.isInvalid())
8782 return StmtError();
8783
8784 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8785 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8786 Sema::ConditionKind::Boolean),
8787 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8788 }
8789
8790 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8791 ExprPair Subobj) {
8792 QualType SizeType = S.Context.getSizeType();
8793 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8794
8795 // Build 'size_t i$n = 0'.
8796 IdentifierInfo *IterationVarName = nullptr;
8797 {
8798 SmallString<8> Str;
8799 llvm::raw_svector_ostream OS(Str);
8800 OS << "i" << ArrayDepth;
8801 IterationVarName = &S.Context.Idents.get(OS.str());
8802 }
8803 VarDecl *IterationVar = VarDecl::Create(
8804 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8805 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8806 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8807 IterationVar->setInit(
8808 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8809 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8810
8811 auto IterRef = [&] {
8812 ExprResult Ref = S.BuildDeclarationNameExpr(
8813 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8814 IterationVar);
8815 assert(!Ref.isInvalid() && "can't reference our own variable?");
8816 return Ref.get();
8817 };
8818
8819 // Build 'i$n != Size'.
8820 ExprResult Cond = S.CreateBuiltinBinOp(
8821 Loc, BO_NE, IterRef(),
8822 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8823 assert(!Cond.isInvalid() && "should never fail");
8824
8825 // Build '++i$n'.
8826 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8827 assert(!Inc.isInvalid() && "should never fail");
8828
8829 // Build 'a[i$n]' and 'b[i$n]'.
8830 auto Index = [&](ExprResult E) {
8831 if (E.isInvalid())
8832 return ExprError();
8833 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8834 };
8835 Subobj.first = Index(Subobj.first);
8836 Subobj.second = Index(Subobj.second);
8837
8838 // Compare the array elements.
8839 ++ArrayDepth;
8840 StmtResult Substmt = visitSubobject(Type, Subobj);
8841 --ArrayDepth;
8842
8843 if (Substmt.isInvalid())
8844 return StmtError();
8845
8846 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8847 // For outer levels or for an 'operator<=>' we already have a suitable
8848 // statement that returns as necessary.
8849 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8850 assert(DCK == DefaultedComparisonKind::Equal &&
8851 "should have non-expression statement");
8852 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8853 if (Substmt.isInvalid())
8854 return StmtError();
8855 }
8856
8857 // Build 'for (...) ...'
8858 return S.ActOnForStmt(Loc, Loc, Init,
8859 S.ActOnCondition(nullptr, Loc, Cond.get(),
8860 Sema::ConditionKind::Boolean),
8861 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8862 Substmt.get());
8863 }
8864
8865 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8866 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8867 return StmtError();
8868
8871 ExprResult Op;
8872 if (Type->isOverloadableType())
8873 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8874 Obj.second.get(), /*PerformADL=*/true,
8875 /*AllowRewrittenCandidates=*/true, FD);
8876 else
8877 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8878 if (Op.isInvalid())
8879 return StmtError();
8880
8881 switch (DCK) {
8882 case DefaultedComparisonKind::None:
8883 llvm_unreachable("not a defaulted comparison");
8884
8885 case DefaultedComparisonKind::Equal:
8886 // Per C++2a [class.eq]p2, each comparison is individually contextually
8887 // converted to bool.
8888 Op = S.PerformContextuallyConvertToBool(Op.get());
8889 if (Op.isInvalid())
8890 return StmtError();
8891 return Op.get();
8892
8893 case DefaultedComparisonKind::ThreeWay: {
8894 // Per C++2a [class.spaceship]p3, form:
8895 // if (R cmp = static_cast<R>(op); cmp != 0)
8896 // return cmp;
8897 QualType R = FD->getReturnType();
8898 Op = buildStaticCastToR(Op.get());
8899 if (Op.isInvalid())
8900 return StmtError();
8901
8902 // R cmp = ...;
8903 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8904 VarDecl *VD =
8905 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8906 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8907 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8908 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8909
8910 // cmp != 0
8911 ExprResult VDRef = getDecl(VD);
8912 if (VDRef.isInvalid())
8913 return StmtError();
8914 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8915 Expr *Zero =
8916 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8918 if (VDRef.get()->getType()->isOverloadableType())
8919 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8920 true, FD);
8921 else
8922 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8923 if (Comp.isInvalid())
8924 return StmtError();
8925 Sema::ConditionResult Cond = S.ActOnCondition(
8926 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8927 if (Cond.isInvalid())
8928 return StmtError();
8929
8930 // return cmp;
8931 VDRef = getDecl(VD);
8932 if (VDRef.isInvalid())
8933 return StmtError();
8934 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8935 if (ReturnStmt.isInvalid())
8936 return StmtError();
8937
8938 // if (...)
8939 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8940 Loc, ReturnStmt.get(),
8941 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8942 }
8943
8944 case DefaultedComparisonKind::NotEqual:
8945 case DefaultedComparisonKind::Relational:
8946 // C++2a [class.compare.secondary]p2:
8947 // Otherwise, the operator function yields x @ y.
8948 return Op.get();
8949 }
8950 llvm_unreachable("");
8951 }
8952
8953 /// Build "static_cast<R>(E)".
8954 ExprResult buildStaticCastToR(Expr *E) {
8955 QualType R = FD->getReturnType();
8956 assert(!R->isUndeducedType() && "type should have been deduced already");
8957
8958 // Don't bother forming a no-op cast in the common case.
8959 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8960 return E;
8961 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8962 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8963 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8964 }
8965};
8966}
8967
8968/// Perform the unqualified lookups that might be needed to form a defaulted
8969/// comparison function for the given operator.
8971 UnresolvedSetImpl &Operators,
8973 auto Lookup = [&](OverloadedOperatorKind OO) {
8974 Self.LookupOverloadedOperatorName(OO, S, Operators);
8975 };
8976
8977 // Every defaulted operator looks up itself.
8978 Lookup(Op);
8979 // ... and the rewritten form of itself, if any.
8981 Lookup(ExtraOp);
8982
8983 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8984 // synthesize a three-way comparison from '<' and '=='. In a dependent
8985 // context, we also need to look up '==' in case we implicitly declare a
8986 // defaulted 'operator=='.
8987 if (Op == OO_Spaceship) {
8988 Lookup(OO_ExclaimEqual);
8989 Lookup(OO_Less);
8990 Lookup(OO_EqualEqual);
8991 }
8992}
8993
8996 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8997
8998 // Perform any unqualified lookups we're going to need to default this
8999 // function.
9000 if (S) {
9001 UnresolvedSet<32> Operators;
9002 lookupOperatorsForDefaultedComparison(*this, S, Operators,
9003 FD->getOverloadedOperator());
9006 Context, Operators.pairs()));
9007 }
9008
9009 // C++2a [class.compare.default]p1:
9010 // A defaulted comparison operator function for some class C shall be a
9011 // non-template function declared in the member-specification of C that is
9012 // -- a non-static const non-volatile member of C having one parameter of
9013 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9014 // -- a friend of C having two parameters of type const C& or two
9015 // parameters of type C.
9016
9017 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
9018 bool IsMethod = isa<CXXMethodDecl>(FD);
9019 if (IsMethod) {
9020 auto *MD = cast<CXXMethodDecl>(FD);
9021 assert(!MD->isStatic() && "comparison function cannot be a static member");
9022
9023 if (MD->getRefQualifier() == RQ_RValue) {
9024 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
9025
9026 // Remove the ref qualifier to recover.
9027 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9028 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9029 EPI.RefQualifier = RQ_None;
9030 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9031 FPT->getParamTypes(), EPI));
9032 }
9033
9034 // If we're out-of-class, this is the class we're comparing.
9035 if (!RD)
9036 RD = MD->getParent();
9037 QualType T = MD->getFunctionObjectParameterReferenceType();
9038 if (!T.getNonReferenceType().isConstQualified() &&
9039 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9040 SourceLocation Loc, InsertLoc;
9041 if (MD->isExplicitObjectMemberFunction()) {
9042 Loc = MD->getParamDecl(0)->getBeginLoc();
9043 InsertLoc = getLocForEndOfToken(
9044 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
9045 } else {
9046 Loc = MD->getLocation();
9047 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9048 InsertLoc = Loc.getRParenLoc();
9049 }
9050 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9051 // corresponding defaulted 'operator<=>' already.
9052 if (!MD->isImplicit()) {
9053 Diag(Loc, diag::err_defaulted_comparison_non_const)
9054 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
9055 }
9056
9057 // Add the 'const' to the type to recover.
9058 if (MD->isExplicitObjectMemberFunction()) {
9059 assert(T->isLValueReferenceType());
9060 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(
9061 T.getNonReferenceType().withConst()));
9062 } else {
9063 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9064 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9065 EPI.TypeQuals.addConst();
9066 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9067 FPT->getParamTypes(), EPI));
9068 }
9069 }
9070
9071 if (MD->isVolatile()) {
9072 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
9073
9074 // Remove the 'volatile' from the type to recover.
9075 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9076 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9078 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9079 FPT->getParamTypes(), EPI));
9080 }
9081 }
9082
9083 if ((FD->getNumParams() -
9084 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9085 (IsMethod ? 1 : 2)) {
9086 // Let's not worry about using a variadic template pack here -- who would do
9087 // such a thing?
9088 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
9089 << int(IsMethod) << int(DCK);
9090 return true;
9091 }
9092
9093 const ParmVarDecl *KnownParm = nullptr;
9094 for (const ParmVarDecl *Param : FD->parameters()) {
9095 QualType ParmTy = Param->getType();
9096 if (!KnownParm) {
9097 auto CTy = ParmTy;
9098 // Is it `T const &`?
9099 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9100 QualType ExpectedTy;
9101 if (RD)
9102 ExpectedTy = Context.getCanonicalTagType(RD);
9103 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9104 CTy = Ref->getPointeeType();
9105 if (RD)
9106 ExpectedTy.addConst();
9107 Ok = true;
9108 }
9109
9110 // Is T a class?
9111 if (RD) {
9112 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);
9113 } else {
9114 RD = CTy->getAsCXXRecordDecl();
9115 Ok &= RD != nullptr;
9116 }
9117
9118 if (Ok) {
9119 KnownParm = Param;
9120 } else {
9121 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9122 // corresponding defaulted 'operator<=>' already.
9123 if (!FD->isImplicit()) {
9124 if (RD) {
9125 CanQualType PlainTy = Context.getCanonicalTagType(RD);
9126 QualType RefTy =
9127 Context.getLValueReferenceType(PlainTy.withConst());
9128 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
9129 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9130 << Param->getSourceRange();
9131 } else {
9132 assert(!IsMethod && "should know expected type for method");
9133 Diag(FD->getLocation(),
9134 diag::err_defaulted_comparison_param_unknown)
9135 << int(DCK) << ParmTy << Param->getSourceRange();
9136 }
9137 }
9138 return true;
9139 }
9140 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
9141 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
9142 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9143 << ParmTy << Param->getSourceRange();
9144 return true;
9145 }
9146 }
9147
9148 assert(RD && "must have determined class");
9149 if (IsMethod) {
9150 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9151 // In-class, must be a friend decl.
9152 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9153 } else {
9154 // Out of class, require the defaulted comparison to be a friend (of a
9155 // complete type, per CWG2547).
9156 if (RequireCompleteType(FD->getLocation(), Context.getCanonicalTagType(RD),
9157 diag::err_defaulted_comparison_not_friend, int(DCK),
9158 int(1)))
9159 return true;
9160
9161 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
9162 return declaresSameEntity(F->getFriendDecl(), FD);
9163 })) {
9164 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
9165 << int(DCK) << int(0) << RD;
9166 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
9167 return true;
9168 }
9169 }
9170
9171 // C++2a [class.eq]p1, [class.rel]p1:
9172 // A [defaulted comparison other than <=>] shall have a declared return
9173 // type bool.
9176 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
9177 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
9178 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9179 << FD->getReturnTypeSourceRange();
9180 return true;
9181 }
9182 // C++2a [class.spaceship]p2 [P2002R0]:
9183 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9184 // R shall not contain a placeholder type.
9185 if (QualType RT = FD->getDeclaredReturnType();
9187 RT->getContainedDeducedType() &&
9188 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
9189 RT->getContainedAutoType()->isConstrained())) {
9190 Diag(FD->getLocation(),
9191 diag::err_defaulted_comparison_deduced_return_type_not_auto)
9192 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9193 << FD->getReturnTypeSourceRange();
9194 return true;
9195 }
9196
9197 // For a defaulted function in a dependent class, defer all remaining checks
9198 // until instantiation.
9199 if (RD->isDependentType())
9200 return false;
9201
9202 // Determine whether the function should be defined as deleted.
9203 DefaultedComparisonInfo Info =
9204 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9205
9206 bool First = FD == FD->getCanonicalDecl();
9207
9208 if (!First) {
9209 if (Info.Deleted) {
9210 // C++11 [dcl.fct.def.default]p4:
9211 // [For a] user-provided explicitly-defaulted function [...] if such a
9212 // function is implicitly defined as deleted, the program is ill-formed.
9213 //
9214 // This is really just a consequence of the general rule that you can
9215 // only delete a function on its first declaration.
9216 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9217 << FD->isImplicit() << (int)DCK;
9218 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9219 DefaultedComparisonAnalyzer::ExplainDeleted)
9220 .visit();
9221 return true;
9222 }
9224 // C++20 [class.compare.default]p1:
9225 // [...] A definition of a comparison operator as defaulted that appears
9226 // in a class shall be the first declaration of that function.
9227 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9228 << (int)DCK;
9230 diag::note_previous_declaration);
9231 return true;
9232 }
9233 }
9234
9235 // If we want to delete the function, then do so; there's nothing else to
9236 // check in that case.
9237 if (Info.Deleted) {
9238 SetDeclDeleted(FD, FD->getLocation());
9239 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9240 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9241 << (int)DCK;
9242 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9243 DefaultedComparisonAnalyzer::ExplainDeleted)
9244 .visit();
9245 if (FD->getDefaultLoc().isValid())
9246 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9247 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9248 }
9249 return false;
9250 }
9251
9252 // C++2a [class.spaceship]p2:
9253 // The return type is deduced as the common comparison type of R0, R1, ...
9257 if (RetLoc.isInvalid())
9258 RetLoc = FD->getBeginLoc();
9259 // FIXME: Should we really care whether we have the complete type and the
9260 // 'enumerator' constants here? A forward declaration seems sufficient.
9262 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9263 if (Cat.isNull())
9264 return true;
9265 Context.adjustDeducedFunctionResultType(
9266 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9267 }
9268
9269 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9270 // An explicitly-defaulted function that is not defined as deleted may be
9271 // declared constexpr or consteval only if it is constexpr-compatible.
9272 // C++2a [class.compare.default]p3 [P2002R0]:
9273 // A defaulted comparison function is constexpr-compatible if it satisfies
9274 // the requirements for a constexpr function [...]
9275 // The only relevant requirements are that the parameter and return types are
9276 // literal types. The remaining conditions are checked by the analyzer.
9277 //
9278 // We support P2448R2 in language modes earlier than C++23 as an extension.
9279 // The concept of constexpr-compatible was removed.
9280 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9281 // A function explicitly defaulted on its first declaration is implicitly
9282 // inline, and is implicitly constexpr if it is constexpr-suitable.
9283 // C++23 [dcl.constexpr]p3
9284 // A function is constexpr-suitable if
9285 // - it is not a coroutine, and
9286 // - if the function is a constructor or destructor, its class does not
9287 // have any virtual base classes.
9288 if (FD->isConstexpr()) {
9289 if (!getLangOpts().CPlusPlus23 &&
9292 !Info.Constexpr) {
9293 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
9294 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9295 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9296 DefaultedComparisonAnalyzer::ExplainConstexpr)
9297 .visit();
9298 }
9299 }
9300
9301 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9302 // If a constexpr-compatible function is explicitly defaulted on its first
9303 // declaration, it is implicitly considered to be constexpr.
9304 // FIXME: Only applying this to the first declaration seems problematic, as
9305 // simple reorderings can affect the meaning of the program.
9306 if (First && !FD->isConstexpr() && Info.Constexpr)
9308
9309 // C++2a [except.spec]p3:
9310 // If a declaration of a function does not have a noexcept-specifier
9311 // [and] is defaulted on its first declaration, [...] the exception
9312 // specification is as specified below
9313 if (FD->getExceptionSpecType() == EST_None) {
9314 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9315 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9317 EPI.ExceptionSpec.SourceDecl = FD;
9318 FD->setType(Context.getFunctionType(FPT->getReturnType(),
9319 FPT->getParamTypes(), EPI));
9320 }
9321
9322 return false;
9323}
9324
9326 FunctionDecl *Spaceship) {
9329 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9330 Ctx.Entity = Spaceship;
9332
9333 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9334 EqualEqual->setImplicit();
9335
9337}
9338
9341 assert(FD->isDefaulted() && !FD->isDeleted() &&
9343 if (FD->willHaveBody() || FD->isInvalidDecl())
9344 return;
9345
9347
9348 // Add a context note for diagnostics produced after this point.
9349 Scope.addContextNote(UseLoc);
9350
9351 {
9352 // Build and set up the function body.
9353 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9354 // the type of the class being compared.
9355 auto PT = FD->getParamDecl(0)->getType();
9356 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9357 SourceLocation BodyLoc =
9358 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9359 StmtResult Body =
9360 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9361 if (Body.isInvalid()) {
9362 FD->setInvalidDecl();
9363 return;
9364 }
9365 FD->setBody(Body.get());
9366 FD->markUsed(Context);
9367 }
9368
9369 // The exception specification is needed because we are defining the
9370 // function. Note that this will reuse the body we just built.
9372
9374 L->CompletedImplicitDefinition(FD);
9375}
9376
9379 FunctionDecl *FD,
9381 ComputingExceptionSpec CES(S, FD, Loc);
9383
9384 if (FD->isInvalidDecl())
9385 return ExceptSpec;
9386
9387 // The common case is that we just defined the comparison function. In that
9388 // case, just look at whether the body can throw.
9389 if (FD->hasBody()) {
9390 ExceptSpec.CalledStmt(FD->getBody());
9391 } else {
9392 // Otherwise, build a body so we can check it. This should ideally only
9393 // happen when we're not actually marking the function referenced. (This is
9394 // only really important for efficiency: we don't want to build and throw
9395 // away bodies for comparison functions more than we strictly need to.)
9396
9397 // Pretend to synthesize the function body in an unevaluated context.
9398 // Note that we can't actually just go ahead and define the function here:
9399 // we are not permitted to mark its callees as referenced.
9403
9404 CXXRecordDecl *RD =
9406 ? FD->getDeclContext()
9407 : FD->getLexicalDeclContext());
9408 SourceLocation BodyLoc =
9409 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9410 StmtResult Body =
9411 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9412 if (!Body.isInvalid())
9413 ExceptSpec.CalledStmt(Body.get());
9414
9415 // FIXME: Can we hold onto this body and just transform it to potentially
9416 // evaluated when we're asked to define the function rather than rebuilding
9417 // it? Either that, or we should only build the bits of the body that we
9418 // need (the expressions, not the statements).
9419 }
9420
9421 return ExceptSpec;
9422}
9423
9425 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9427
9428 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9430
9431 // Perform any deferred checking of exception specifications for virtual
9432 // destructors.
9433 for (auto &Check : Overriding)
9434 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9435
9436 // Perform any deferred checking of exception specifications for befriended
9437 // special members.
9438 for (auto &Check : Equivalent)
9439 CheckEquivalentExceptionSpec(Check.second, Check.first);
9440}
9441
9442namespace {
9443/// CRTP base class for visiting operations performed by a special member
9444/// function (or inherited constructor).
9445template<typename Derived>
9446struct SpecialMemberVisitor {
9447 Sema &S;
9448 CXXMethodDecl *MD;
9451
9452 // Properties of the special member, computed for convenience.
9453 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9454
9455 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9457 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9458 switch (CSM) {
9462 IsConstructor = true;
9463 break;
9466 IsAssignment = true;
9467 break;
9469 break;
9471 llvm_unreachable("invalid special member kind");
9472 }
9473
9474 if (MD->getNumExplicitParams()) {
9475 if (const ReferenceType *RT =
9476 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9477 ConstArg = RT->getPointeeType().isConstQualified();
9478 }
9479 }
9480
9481 Derived &getDerived() { return static_cast<Derived&>(*this); }
9482
9483 /// Is this a "move" special member?
9484 bool isMove() const {
9485 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9486 CSM == CXXSpecialMemberKind::MoveAssignment;
9487 }
9488
9489 /// Look up the corresponding special member in the given class.
9490 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9491 unsigned Quals, bool IsMutable) {
9492 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9493 ConstArg && !IsMutable);
9494 }
9495
9496 /// Look up the constructor for the specified base class to see if it's
9497 /// overridden due to this being an inherited constructor.
9498 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9499 if (!ICI)
9500 return {};
9501 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9502 auto *BaseCtor =
9503 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9504 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9505 return MD;
9506 return {};
9507 }
9508
9509 /// A base or member subobject.
9510 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9511
9512 /// Get the location to use for a subobject in diagnostics.
9513 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9514 // FIXME: For an indirect virtual base, the direct base leading to
9515 // the indirect virtual base would be a more useful choice.
9516 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))
9517 return B->getBaseTypeLoc();
9518 else
9519 return cast<FieldDecl *>(Subobj)->getLocation();
9520 }
9521
9522 enum BasesToVisit {
9523 /// Visit all non-virtual (direct) bases.
9524 VisitNonVirtualBases,
9525 /// Visit all direct bases, virtual or not.
9526 VisitDirectBases,
9527 /// Visit all non-virtual bases, and all virtual bases if the class
9528 /// is not abstract.
9529 VisitPotentiallyConstructedBases,
9530 /// Visit all direct or virtual bases.
9531 VisitAllBases
9532 };
9533
9534 // Visit the bases and members of the class.
9535 bool visit(BasesToVisit Bases) {
9536 CXXRecordDecl *RD = MD->getParent();
9537
9538 if (Bases == VisitPotentiallyConstructedBases)
9539 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9540
9541 for (auto &B : RD->bases())
9542 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9543 getDerived().visitBase(&B))
9544 return true;
9545
9546 if (Bases == VisitAllBases)
9547 for (auto &B : RD->vbases())
9548 if (getDerived().visitBase(&B))
9549 return true;
9550
9551 for (auto *F : RD->fields())
9552 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9553 getDerived().visitField(F))
9554 return true;
9555
9556 return false;
9557 }
9558};
9559}
9560
9561namespace {
9562struct SpecialMemberDeletionInfo
9563 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9564 bool Diagnose;
9565
9566 SourceLocation Loc;
9567
9568 bool AllFieldsAreConst;
9569
9570 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9572 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9573 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9574 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9575
9576 bool inUnion() const { return MD->getParent()->isUnion(); }
9577
9578 CXXSpecialMemberKind getEffectiveCSM() {
9579 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9580 }
9581
9582 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9583
9584 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9585
9586 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9587 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9588
9589 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9590 bool shouldDeleteForField(FieldDecl *FD);
9591 bool shouldDeleteForAllConstMembers();
9592
9593 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9594 unsigned Quals);
9595 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9596 Sema::SpecialMemberOverloadResult SMOR,
9597 bool IsDtorCallInCtor);
9598
9599 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9600};
9601}
9602
9603/// Is the given special member inaccessible when used on the given
9604/// sub-object.
9605bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9606 CXXMethodDecl *target) {
9607 /// If we're operating on a base class, the object type is the
9608 /// type of this special member.
9609 CanQualType objectTy;
9610 AccessSpecifier access = target->getAccess();
9611 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9612 objectTy = S.Context.getCanonicalTagType(MD->getParent());
9613 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9614
9615 // If we're operating on a field, the object type is the type of the field.
9616 } else {
9617 objectTy = S.Context.getCanonicalTagType(target->getParent());
9618 }
9619
9621 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9622}
9623
9624/// Check whether we should delete a special member due to the implicit
9625/// definition containing a call to a special member of a subobject.
9626bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9627 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9628 bool IsDtorCallInCtor) {
9629 CXXMethodDecl *Decl = SMOR.getMethod();
9630 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9631
9632 enum {
9633 NotSet = -1,
9634 NoDecl,
9635 DeletedDecl,
9636 MultipleDecl,
9637 InaccessibleDecl,
9638 NonTrivialDecl
9639 } DiagKind = NotSet;
9640
9642 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9643 Field->getParent()->isUnion()) {
9644 // [class.default.ctor]p2:
9645 // A defaulted default constructor for class X is defined as deleted if
9646 // - X is a union that has a variant member with a non-trivial default
9647 // constructor and no variant member of X has a default member
9648 // initializer
9649 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9650 if (RD->hasInClassInitializer())
9651 return false;
9652 }
9653 DiagKind = !Decl ? NoDecl : DeletedDecl;
9655 DiagKind = MultipleDecl;
9656 else if (!isAccessible(Subobj, Decl))
9657 DiagKind = InaccessibleDecl;
9658 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9659 !Decl->isTrivial()) {
9660 // A member of a union must have a trivial corresponding special member.
9661 // As a weird special case, a destructor call from a union's constructor
9662 // must be accessible and non-deleted, but need not be trivial. Such a
9663 // destructor is never actually called, but is semantically checked as
9664 // if it were.
9665 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9666 // [class.default.ctor]p2:
9667 // A defaulted default constructor for class X is defined as deleted if
9668 // - X is a union that has a variant member with a non-trivial default
9669 // constructor and no variant member of X has a default member
9670 // initializer
9671 const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9672 if (!RD->hasInClassInitializer())
9673 DiagKind = NonTrivialDecl;
9674 } else {
9675 DiagKind = NonTrivialDecl;
9676 }
9677 }
9678
9679 if (DiagKind == NotSet)
9680 return false;
9681
9682 if (Diagnose) {
9683 if (Field) {
9684 S.Diag(Field->getLocation(),
9685 diag::note_deleted_special_member_class_subobject)
9686 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9687 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9688 } else {
9689 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);
9690 S.Diag(Base->getBeginLoc(),
9691 diag::note_deleted_special_member_class_subobject)
9692 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9693 << Base->getType() << DiagKind << IsDtorCallInCtor
9694 << /*IsObjCPtr*/ false;
9695 }
9696
9697 if (DiagKind == DeletedDecl)
9698 S.NoteDeletedFunction(Decl);
9699 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9700 }
9701
9702 return true;
9703}
9704
9705/// Check whether we should delete a special member function due to having a
9706/// direct or virtual base class or non-static data member of class type M.
9707bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9708 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9709 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9710 bool IsMutable = Field && Field->isMutable();
9711
9712 // C++11 [class.ctor]p5:
9713 // -- any direct or virtual base class, or non-static data member with no
9714 // brace-or-equal-initializer, has class type M (or array thereof) and
9715 // either M has no default constructor or overload resolution as applied
9716 // to M's default constructor results in an ambiguity or in a function
9717 // that is deleted or inaccessible
9718 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9719 // -- a direct or virtual base class B that cannot be copied/moved because
9720 // overload resolution, as applied to B's corresponding special member,
9721 // results in an ambiguity or a function that is deleted or inaccessible
9722 // from the defaulted special member
9723 // C++11 [class.dtor]p5:
9724 // -- any direct or virtual base class [...] has a type with a destructor
9725 // that is deleted or inaccessible
9726 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9727 Field->hasInClassInitializer()) &&
9728 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9729 false))
9730 return true;
9731
9732 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9733 // -- any direct or virtual base class or non-static data member has a
9734 // type with a destructor that is deleted or inaccessible
9735 if (IsConstructor) {
9736 Sema::SpecialMemberOverloadResult SMOR =
9737 S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
9738 false, false, false, false);
9739 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9740 return true;
9741 }
9742
9743 return false;
9744}
9745
9746bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9747 FieldDecl *FD, QualType FieldType) {
9748 // The defaulted special functions are defined as deleted if this is a variant
9749 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9750 // type under ARC.
9751 if (!FieldType.hasNonTrivialObjCLifetime())
9752 return false;
9753
9754 // Don't make the defaulted default constructor defined as deleted if the
9755 // member has an in-class initializer.
9756 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9758 return false;
9759
9760 if (Diagnose) {
9761 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9762 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9763 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9764 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9765 }
9766
9767 return true;
9768}
9769
9770bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9771 const FieldDecl *FD) {
9772 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9773 // Copy/move constructors/assignment operators are deleted if the field has an
9774 // address-discriminated ptrauth qualifier.
9775 PointerAuthQualifier Q = FieldType.getPointerAuth();
9776
9777 if (!Q || !Q.isAddressDiscriminated())
9778 return false;
9779
9780 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9781 CSM == CXXSpecialMemberKind::Destructor)
9782 return false;
9783
9784 if (Diagnose) {
9785 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9786 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9787 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9788 << /*IsDtorCallInCtor*/ false << 2;
9789 }
9790
9791 return true;
9792}
9793
9794/// Check whether we should delete a special member function due to the class
9795/// having a particular direct or virtual base class.
9796bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9797 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9798 // If program is correct, BaseClass cannot be null, but if it is, the error
9799 // must be reported elsewhere.
9800 if (!BaseClass)
9801 return false;
9802 // If we have an inheriting constructor, check whether we're calling an
9803 // inherited constructor instead of a default constructor.
9804 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9805 if (auto *BaseCtor = SMOR.getMethod()) {
9806 // Note that we do not check access along this path; other than that,
9807 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9808 // FIXME: Check that the base has a usable destructor! Sink this into
9809 // shouldDeleteForClassSubobject.
9810 if (BaseCtor->isDeleted() && Diagnose) {
9811 S.Diag(Base->getBeginLoc(),
9812 diag::note_deleted_special_member_class_subobject)
9813 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9814 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9815 << /*IsObjCPtr*/ false;
9816 S.NoteDeletedFunction(BaseCtor);
9817 }
9818 return BaseCtor->isDeleted();
9819 }
9820 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9821}
9822
9823/// Check whether we should delete a special member function due to the class
9824/// having a particular non-static data member.
9825bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9826 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9827 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9828
9829 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9830 return true;
9831
9832 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9833 return true;
9834
9835 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9836 // For a default constructor, all references must be initialized in-class
9837 // and, if a union, it must have a non-const member.
9838 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9839 if (Diagnose)
9840 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9841 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9842 return true;
9843 }
9844 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9845 // data member of const-qualified type (or array thereof) with no
9846 // brace-or-equal-initializer is not const-default-constructible.
9847 if (!inUnion() && FieldType.isConstQualified() &&
9848 !FD->hasInClassInitializer() &&
9849 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9850 if (Diagnose)
9851 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9852 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9853 return true;
9854 }
9855
9856 if (inUnion() && !FieldType.isConstQualified())
9857 AllFieldsAreConst = false;
9858 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9859 // For a copy constructor, data members must not be of rvalue reference
9860 // type.
9861 if (FieldType->isRValueReferenceType()) {
9862 if (Diagnose)
9863 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9864 << MD->getParent() << FD << FieldType;
9865 return true;
9866 }
9867 } else if (IsAssignment) {
9868 // For an assignment operator, data members must not be of reference type.
9869 if (FieldType->isReferenceType()) {
9870 if (Diagnose)
9871 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9872 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9873 return true;
9874 }
9875 if (!FieldRecord && FieldType.isConstQualified()) {
9876 // C++11 [class.copy]p23:
9877 // -- a non-static data member of const non-class type (or array thereof)
9878 if (Diagnose)
9879 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9880 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9881 return true;
9882 }
9883 }
9884
9885 if (FieldRecord) {
9886 // Some additional restrictions exist on the variant members.
9887 if (!inUnion() && FieldRecord->isUnion() &&
9888 FieldRecord->isAnonymousStructOrUnion()) {
9889 bool AllVariantFieldsAreConst = true;
9890
9891 // FIXME: Handle anonymous unions declared within anonymous unions.
9892 for (auto *UI : FieldRecord->fields()) {
9893 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9894
9895 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9896 return true;
9897
9898 if (shouldDeleteForVariantPtrAuthMember(&*UI))
9899 return true;
9900
9901 if (!UnionFieldType.isConstQualified())
9902 AllVariantFieldsAreConst = false;
9903
9904 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9905 if (UnionFieldRecord &&
9906 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9907 UnionFieldType.getCVRQualifiers()))
9908 return true;
9909 }
9910
9911 // At least one member in each anonymous union must be non-const
9912 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9913 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9914 if (Diagnose)
9915 S.Diag(FieldRecord->getLocation(),
9916 diag::note_deleted_default_ctor_all_const)
9917 << !!ICI << MD->getParent() << /*anonymous union*/1;
9918 return true;
9919 }
9920
9921 // Don't check the implicit member of the anonymous union type.
9922 // This is technically non-conformant but supported, and we have a
9923 // diagnostic for this elsewhere.
9924 return false;
9925 }
9926
9927 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9928 FieldType.getCVRQualifiers()))
9929 return true;
9930 }
9931
9932 return false;
9933}
9934
9935/// C++11 [class.ctor] p5:
9936/// A defaulted default constructor for a class X is defined as deleted if
9937/// X is a union and all of its variant members are of const-qualified type.
9938bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9939 // This is a silly definition, because it gives an empty union a deleted
9940 // default constructor. Don't do that.
9941 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9942 AllFieldsAreConst) {
9943 bool AnyFields = false;
9944 for (auto *F : MD->getParent()->fields())
9945 if ((AnyFields = !F->isUnnamedBitField()))
9946 break;
9947 if (!AnyFields)
9948 return false;
9949 if (Diagnose)
9950 S.Diag(MD->getParent()->getLocation(),
9951 diag::note_deleted_default_ctor_all_const)
9952 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9953 return true;
9954 }
9955 return false;
9956}
9957
9958/// Determine whether a defaulted special member function should be defined as
9959/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9960/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9964 bool Diagnose) {
9965 if (MD->isInvalidDecl())
9966 return false;
9967 CXXRecordDecl *RD = MD->getParent();
9968 assert(!RD->isDependentType() && "do deletion after instantiation");
9969 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9970 RD->isInvalidDecl())
9971 return false;
9972
9973 // C++11 [expr.lambda.prim]p19:
9974 // The closure type associated with a lambda-expression has a
9975 // deleted (8.4.3) default constructor and a deleted copy
9976 // assignment operator.
9977 // C++2a adds back these operators if the lambda has no lambda-capture.
9981 if (Diagnose)
9982 Diag(RD->getLocation(), diag::note_lambda_decl);
9983 return true;
9984 }
9985
9986 // C++11 [class.copy]p7, p18:
9987 // If the class definition declares a move constructor or move assignment
9988 // operator, an implicitly declared copy constructor or copy assignment
9989 // operator is defined as deleted.
9992 CXXMethodDecl *UserDeclaredMove = nullptr;
9993
9994 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9995 // deletion of the corresponding copy operation, not both copy operations.
9996 // MSVC 2015 has adopted the standards conforming behavior.
9997 bool DeletesOnlyMatchingCopy =
9998 getLangOpts().MSVCCompat &&
9999 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
10000
10002 (!DeletesOnlyMatchingCopy ||
10004 if (!Diagnose) return true;
10005
10006 // Find any user-declared move constructor.
10007 for (auto *I : RD->ctors()) {
10008 if (I->isMoveConstructor()) {
10009 UserDeclaredMove = I;
10010 break;
10011 }
10012 }
10013 assert(UserDeclaredMove);
10014 } else if (RD->hasUserDeclaredMoveAssignment() &&
10015 (!DeletesOnlyMatchingCopy ||
10017 if (!Diagnose) return true;
10018
10019 // Find any user-declared move assignment operator.
10020 for (auto *I : RD->methods()) {
10021 if (I->isMoveAssignmentOperator()) {
10022 UserDeclaredMove = I;
10023 break;
10024 }
10025 }
10026 assert(UserDeclaredMove);
10027 }
10028
10029 if (UserDeclaredMove) {
10030 Diag(UserDeclaredMove->getLocation(),
10031 diag::note_deleted_copy_user_declared_move)
10032 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10033 << UserDeclaredMove->isMoveAssignmentOperator();
10034 return true;
10035 }
10036 }
10037
10038 // Do access control from the special member function
10039 ContextRAII MethodContext(*this, MD);
10040
10041 // C++11 [class.dtor]p5:
10042 // -- for a virtual destructor, lookup of the non-array deallocation function
10043 // results in an ambiguity or in a function that is deleted or inaccessible
10044 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10045 FunctionDecl *OperatorDelete = nullptr;
10046 CanQualType DeallocType = Context.getCanonicalTagType(RD);
10047 DeclarationName Name =
10048 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
10052 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
10053 OperatorDelete, IDP,
10054 /*Diagnose=*/false)) {
10055 if (Diagnose)
10056 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
10057 return true;
10058 }
10059 }
10060
10061 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10062
10063 // Per DR1611, do not consider virtual bases of constructors of abstract
10064 // classes, since we are not going to construct them.
10065 // Per DR1658, do not consider virtual bases of destructors of abstract
10066 // classes either.
10067 // Per DR2180, for assignment operators we only assign (and thus only
10068 // consider) direct bases.
10069 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
10070 : SMI.VisitPotentiallyConstructedBases))
10071 return true;
10072
10073 if (SMI.shouldDeleteForAllConstMembers())
10074 return true;
10075
10076 if (getLangOpts().CUDA) {
10077 // We should delete the special member in CUDA mode if target inference
10078 // failed.
10079 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10080 // is treated as certain special member, which may not reflect what special
10081 // member MD really is. However inferTargetForImplicitSpecialMember
10082 // expects CSM to match MD, therefore recalculate CSM.
10083 assert(ICI || CSM == getSpecialMember(MD));
10084 auto RealCSM = CSM;
10085 if (ICI)
10086 RealCSM = getSpecialMember(MD);
10087
10088 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
10089 SMI.ConstArg, Diagnose);
10090 }
10091
10092 return false;
10093}
10094
10097 assert(DFK && "not a defaultable function");
10098 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10099
10100 if (DFK.isSpecialMember()) {
10102 nullptr, /*Diagnose=*/true);
10103 } else {
10104 DefaultedComparisonAnalyzer(
10106 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10107 .visit();
10108 }
10109}
10110
10111/// Perform lookup for a special member of the specified kind, and determine
10112/// whether it is trivial. If the triviality can be determined without the
10113/// lookup, skip it. This is intended for use when determining whether a
10114/// special member of a containing object is trivial, and thus does not ever
10115/// perform overload resolution for default constructors.
10116///
10117/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10118/// member that was most likely to be intended to be trivial, if any.
10119///
10120/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10121/// determine whether the special member is trivial.
10123 CXXSpecialMemberKind CSM, unsigned Quals,
10124 bool ConstRHS, TrivialABIHandling TAH,
10125 CXXMethodDecl **Selected) {
10126 if (Selected)
10127 *Selected = nullptr;
10128
10129 switch (CSM) {
10131 llvm_unreachable("not a special member");
10132
10134 // C++11 [class.ctor]p5:
10135 // A default constructor is trivial if:
10136 // - all the [direct subobjects] have trivial default constructors
10137 //
10138 // Note, no overload resolution is performed in this case.
10140 return true;
10141
10142 if (Selected) {
10143 // If there's a default constructor which could have been trivial, dig it
10144 // out. Otherwise, if there's any user-provided default constructor, point
10145 // to that as an example of why there's not a trivial one.
10146 CXXConstructorDecl *DefCtor = nullptr;
10149 for (auto *CI : RD->ctors()) {
10150 if (!CI->isDefaultConstructor())
10151 continue;
10152 DefCtor = CI;
10153 if (!DefCtor->isUserProvided())
10154 break;
10155 }
10156
10157 *Selected = DefCtor;
10158 }
10159
10160 return false;
10161
10163 // C++11 [class.dtor]p5:
10164 // A destructor is trivial if:
10165 // - all the direct [subobjects] have trivial destructors
10166 if (RD->hasTrivialDestructor() ||
10169 return true;
10170
10171 if (Selected) {
10172 if (RD->needsImplicitDestructor())
10174 *Selected = RD->getDestructor();
10175 }
10176
10177 return false;
10178
10180 // C++11 [class.copy]p12:
10181 // A copy constructor is trivial if:
10182 // - the constructor selected to copy each direct [subobject] is trivial
10183 if (RD->hasTrivialCopyConstructor() ||
10186 if (Quals == Qualifiers::Const)
10187 // We must either select the trivial copy constructor or reach an
10188 // ambiguity; no need to actually perform overload resolution.
10189 return true;
10190 } else if (!Selected) {
10191 return false;
10192 }
10193 // In C++98, we are not supposed to perform overload resolution here, but we
10194 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10195 // cases like B as having a non-trivial copy constructor:
10196 // struct A { template<typename T> A(T&); };
10197 // struct B { mutable A a; };
10198 goto NeedOverloadResolution;
10199
10201 // C++11 [class.copy]p25:
10202 // A copy assignment operator is trivial if:
10203 // - the assignment operator selected to copy each direct [subobject] is
10204 // trivial
10205 if (RD->hasTrivialCopyAssignment()) {
10206 if (Quals == Qualifiers::Const)
10207 return true;
10208 } else if (!Selected) {
10209 return false;
10210 }
10211 // In C++98, we are not supposed to perform overload resolution here, but we
10212 // treat that as a language defect.
10213 goto NeedOverloadResolution;
10214
10217 NeedOverloadResolution:
10219 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
10220
10221 // The standard doesn't describe how to behave if the lookup is ambiguous.
10222 // We treat it as not making the member non-trivial, just like the standard
10223 // mandates for the default constructor. This should rarely matter, because
10224 // the member will also be deleted.
10226 return true;
10227
10228 if (!SMOR.getMethod()) {
10229 assert(SMOR.getKind() ==
10231 return false;
10232 }
10233
10234 // We deliberately don't check if we found a deleted special member. We're
10235 // not supposed to!
10236 if (Selected)
10237 *Selected = SMOR.getMethod();
10238
10242 return SMOR.getMethod()->isTrivialForCall();
10243 return SMOR.getMethod()->isTrivial();
10244 }
10245
10246 llvm_unreachable("unknown special method kind");
10247}
10248
10250 for (auto *CI : RD->ctors())
10251 if (!CI->isImplicit())
10252 return CI;
10253
10254 // Look for constructor templates.
10256 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10257 if (CXXConstructorDecl *CD =
10258 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10259 return CD;
10260 }
10261
10262 return nullptr;
10263}
10264
10265/// The kind of subobject we are checking for triviality. The values of this
10266/// enumeration are used in diagnostics.
10268 /// The subobject is a base class.
10270 /// The subobject is a non-static data member.
10272 /// The object is actually the complete object.
10274};
10275
10276/// Check whether the special member selected for a given type would be trivial.
10278 QualType SubType, bool ConstRHS,
10281 TrivialABIHandling TAH, bool Diagnose) {
10282 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10283 if (!SubRD)
10284 return true;
10285
10286 CXXMethodDecl *Selected;
10287 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10288 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10289 return true;
10290
10291 if (Diagnose) {
10292 if (ConstRHS)
10293 SubType.addConst();
10294
10295 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10296 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10297 << Kind << SubType.getUnqualifiedType();
10299 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10300 } else if (!Selected)
10301 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10302 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10303 else if (Selected->isUserProvided()) {
10304 if (Kind == TSK_CompleteObject)
10305 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10306 << Kind << SubType.getUnqualifiedType() << CSM;
10307 else {
10308 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10309 << Kind << SubType.getUnqualifiedType() << CSM;
10310 S.Diag(Selected->getLocation(), diag::note_declared_at);
10311 }
10312 } else {
10313 if (Kind != TSK_CompleteObject)
10314 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10315 << Kind << SubType.getUnqualifiedType() << CSM;
10316
10317 // Explain why the defaulted or deleted special member isn't trivial.
10318 S.SpecialMemberIsTrivial(Selected, CSM,
10320 }
10321 }
10322
10323 return false;
10324}
10325
10326/// Check whether the members of a class type allow a special member to be
10327/// trivial.
10329 CXXSpecialMemberKind CSM, bool ConstArg,
10330 TrivialABIHandling TAH, bool Diagnose) {
10331 for (const auto *FI : RD->fields()) {
10332 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10333 continue;
10334
10335 QualType FieldType = S.Context.getBaseElementType(FI->getType());
10336
10337 // Pretend anonymous struct or union members are members of this class.
10338 if (FI->isAnonymousStructOrUnion()) {
10339 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10340 CSM, ConstArg, TAH, Diagnose))
10341 return false;
10342 continue;
10343 }
10344
10345 // C++11 [class.ctor]p5:
10346 // A default constructor is trivial if [...]
10347 // -- no non-static data member of its class has a
10348 // brace-or-equal-initializer
10350 FI->hasInClassInitializer()) {
10351 if (Diagnose)
10352 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10353 << FI;
10354 return false;
10355 }
10356
10357 // Objective C ARC 4.3.5:
10358 // [...] nontrivally ownership-qualified types are [...] not trivially
10359 // default constructible, copy constructible, move constructible, copy
10360 // assignable, move assignable, or destructible [...]
10361 if (FieldType.hasNonTrivialObjCLifetime()) {
10362 if (Diagnose)
10363 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10364 << RD << FieldType.getObjCLifetime();
10365 return false;
10366 }
10367
10368 bool ConstRHS = ConstArg && !FI->isMutable();
10369 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10370 CSM, TSK_Field, TAH, Diagnose))
10371 return false;
10372 }
10373
10374 return true;
10375}
10376
10379 CanQualType Ty = Context.getCanonicalTagType(RD);
10380
10381 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10383 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10386 /*Diagnose*/ true);
10387}
10388
10390 TrivialABIHandling TAH, bool Diagnose) {
10391 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10392 "not special enough");
10393
10394 CXXRecordDecl *RD = MD->getParent();
10395
10396 bool ConstArg = false;
10397
10398 // C++11 [class.copy]p12, p25: [DR1593]
10399 // A [special member] is trivial if [...] its parameter-type-list is
10400 // equivalent to the parameter-type-list of an implicit declaration [...]
10401 switch (CSM) {
10404 // Trivial default constructors and destructors cannot have parameters.
10405 break;
10406
10409 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10410 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10411
10412 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10413 // if they are not user-provided and their parameter-type-list is equivalent
10414 // to the parameter-type-list of an implicit declaration. This maintains the
10415 // behavior before dr2171 was implemented.
10416 //
10417 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10418 // trivial, if they are not user-provided, regardless of the qualifiers on
10419 // the reference type.
10420 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10421 LangOptions::ClangABI::Ver14;
10422 if (!RT ||
10424 ClangABICompat14)) {
10425 if (Diagnose)
10426 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10427 << Param0->getSourceRange() << Param0->getType()
10428 << Context.getLValueReferenceType(
10429 Context.getCanonicalTagType(RD).withConst());
10430 return false;
10431 }
10432
10433 ConstArg = RT->getPointeeType().isConstQualified();
10434 break;
10435 }
10436
10439 // Trivial move operations always have non-cv-qualified parameters.
10440 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10441 const RValueReferenceType *RT =
10442 Param0->getType()->getAs<RValueReferenceType>();
10443 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10444 if (Diagnose)
10445 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10446 << Param0->getSourceRange() << Param0->getType()
10447 << Context.getRValueReferenceType(Context.getCanonicalTagType(RD));
10448 return false;
10449 }
10450 break;
10451 }
10452
10454 llvm_unreachable("not a special member");
10455 }
10456
10457 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10458 if (Diagnose)
10460 diag::note_nontrivial_default_arg)
10462 return false;
10463 }
10464 if (MD->isVariadic()) {
10465 if (Diagnose)
10466 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10467 return false;
10468 }
10469
10470 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10471 // A copy/move [constructor or assignment operator] is trivial if
10472 // -- the [member] selected to copy/move each direct base class subobject
10473 // is trivial
10474 //
10475 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10476 // A [default constructor or destructor] is trivial if
10477 // -- all the direct base classes have trivial [default constructors or
10478 // destructors]
10479 for (const auto &BI : RD->bases())
10480 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10481 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10482 return false;
10483
10484 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10485 // A copy/move [constructor or assignment operator] for a class X is
10486 // trivial if
10487 // -- for each non-static data member of X that is of class type (or array
10488 // thereof), the constructor selected to copy/move that member is
10489 // trivial
10490 //
10491 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10492 // A [default constructor or destructor] is trivial if
10493 // -- for all of the non-static data members of its class that are of class
10494 // type (or array thereof), each such class has a trivial [default
10495 // constructor or destructor]
10496 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10497 return false;
10498
10499 // C++11 [class.dtor]p5:
10500 // A destructor is trivial if [...]
10501 // -- the destructor is not virtual
10502 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10503 if (Diagnose)
10504 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10505 return false;
10506 }
10507
10508 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10509 // A [special member] for class X is trivial if [...]
10510 // -- class X has no virtual functions and no virtual base classes
10512 MD->getParent()->isDynamicClass()) {
10513 if (!Diagnose)
10514 return false;
10515
10516 if (RD->getNumVBases()) {
10517 // Check for virtual bases. We already know that the corresponding
10518 // member in all bases is trivial, so vbases must all be direct.
10519 CXXBaseSpecifier &BS = *RD->vbases_begin();
10520 assert(BS.isVirtual());
10521 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10522 return false;
10523 }
10524
10525 // Must have a virtual method.
10526 for (const auto *MI : RD->methods()) {
10527 if (MI->isVirtual()) {
10528 SourceLocation MLoc = MI->getBeginLoc();
10529 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10530 return false;
10531 }
10532 }
10533
10534 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10535 }
10536
10537 // Looks like it's trivial!
10538 return true;
10539}
10540
10541namespace {
10542struct FindHiddenVirtualMethod {
10543 Sema *S;
10545 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10546 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10547
10548private:
10549 /// Check whether any most overridden method from MD in Methods
10550 static bool CheckMostOverridenMethods(
10551 const CXXMethodDecl *MD,
10552 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10553 if (MD->size_overridden_methods() == 0)
10554 return Methods.count(MD->getCanonicalDecl());
10555 for (const CXXMethodDecl *O : MD->overridden_methods())
10556 if (CheckMostOverridenMethods(O, Methods))
10557 return true;
10558 return false;
10559 }
10560
10561public:
10562 /// Member lookup function that determines whether a given C++
10563 /// method overloads virtual methods in a base class without overriding any,
10564 /// to be used with CXXRecordDecl::lookupInBases().
10565 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10566 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10567 DeclarationName Name = Method->getDeclName();
10568 assert(Name.getNameKind() == DeclarationName::Identifier);
10569
10570 bool foundSameNameMethod = false;
10571 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10572 for (Path.Decls = BaseRecord->lookup(Name).begin();
10573 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10574 NamedDecl *D = *Path.Decls;
10575 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10576 MD = MD->getCanonicalDecl();
10577 foundSameNameMethod = true;
10578 // Interested only in hidden virtual methods.
10579 if (!MD->isVirtual())
10580 continue;
10581 // If the method we are checking overrides a method from its base
10582 // don't warn about the other overloaded methods. Clang deviates from
10583 // GCC by only diagnosing overloads of inherited virtual functions that
10584 // do not override any other virtual functions in the base. GCC's
10585 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10586 // function from a base class. These cases may be better served by a
10587 // warning (not specific to virtual functions) on call sites when the
10588 // call would select a different function from the base class, were it
10589 // visible.
10590 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10591 if (!S->IsOverload(Method, MD, false))
10592 return true;
10593 // Collect the overload only if its hidden.
10594 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10595 overloadedMethods.push_back(MD);
10596 }
10597 }
10598
10599 if (foundSameNameMethod)
10600 OverloadedMethods.append(overloadedMethods.begin(),
10601 overloadedMethods.end());
10602 return foundSameNameMethod;
10603 }
10604};
10605} // end anonymous namespace
10606
10607/// Add the most overridden methods from MD to Methods
10609 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10610 if (MD->size_overridden_methods() == 0)
10611 Methods.insert(MD->getCanonicalDecl());
10612 else
10613 for (const CXXMethodDecl *O : MD->overridden_methods())
10614 AddMostOverridenMethods(O, Methods);
10615}
10616
10618 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10619 if (!MD->getDeclName().isIdentifier())
10620 return;
10621
10622 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10623 /*bool RecordPaths=*/false,
10624 /*bool DetectVirtual=*/false);
10625 FindHiddenVirtualMethod FHVM;
10626 FHVM.Method = MD;
10627 FHVM.S = this;
10628
10629 // Keep the base methods that were overridden or introduced in the subclass
10630 // by 'using' in a set. A base method not in this set is hidden.
10631 CXXRecordDecl *DC = MD->getParent();
10632 for (NamedDecl *ND : DC->lookup(MD->getDeclName())) {
10633 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(ND))
10634 ND = shad->getTargetDecl();
10635 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10636 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10637 }
10638
10639 if (DC->lookupInBases(FHVM, Paths))
10640 OverloadedMethods = FHVM.OverloadedMethods;
10641}
10642
10644 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10645 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10647 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10648 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10649 Diag(overloadedMD->getLocation(), PD);
10650 }
10651}
10652
10654 if (MD->isInvalidDecl())
10655 return;
10656
10657 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10658 return;
10659
10660 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10661 FindHiddenVirtualMethods(MD, OverloadedMethods);
10662 if (!OverloadedMethods.empty()) {
10663 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10664 << MD << (OverloadedMethods.size() > 1);
10665
10666 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10667 }
10668}
10669
10671 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10672 // No diagnostics if this is a template instantiation.
10674 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10675 diag::ext_cannot_use_trivial_abi) << &RD;
10676 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10677 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10678 }
10679 RD.dropAttr<TrivialABIAttr>();
10680 };
10681
10682 // Ill-formed if the struct has virtual functions.
10683 if (RD.isPolymorphic()) {
10684 PrintDiagAndRemoveAttr(1);
10685 return;
10686 }
10687
10688 for (const auto &B : RD.bases()) {
10689 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10690 // virtual base.
10691 if (!B.getType()->isDependentType() &&
10692 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10693 PrintDiagAndRemoveAttr(2);
10694 return;
10695 }
10696
10697 if (B.isVirtual()) {
10698 PrintDiagAndRemoveAttr(3);
10699 return;
10700 }
10701 }
10702
10703 for (const auto *FD : RD.fields()) {
10704 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10705 // non-trivial for the purpose of calls.
10706 QualType FT = FD->getType();
10708 PrintDiagAndRemoveAttr(4);
10709 return;
10710 }
10711
10712 // Ill-formed if the field is an address-discriminated value.
10714 PrintDiagAndRemoveAttr(6);
10715 return;
10716 }
10717
10718 if (const auto *RT =
10719 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10720 if (!RT->isDependentType() &&
10721 !cast<CXXRecordDecl>(RT->getDecl()->getDefinitionOrSelf())
10722 ->canPassInRegisters()) {
10723 PrintDiagAndRemoveAttr(5);
10724 return;
10725 }
10726 }
10727
10729 return;
10730
10731 // Ill-formed if the copy and move constructors are deleted.
10732 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10733 // If the type is dependent, then assume it might have
10734 // implicit copy or move ctor because we won't know yet at this point.
10735 if (RD.isDependentType())
10736 return true;
10739 return true;
10742 return true;
10743 for (const CXXConstructorDecl *CD : RD.ctors())
10744 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10745 return true;
10746 return false;
10747 };
10748
10749 if (!HasNonDeletedCopyOrMoveConstructor()) {
10750 PrintDiagAndRemoveAttr(0);
10751 return;
10752 }
10753}
10754
10756 CXXRecordDecl &RD) {
10757 if (RequireCompleteType(RD.getLocation(), Context.getCanonicalTagType(&RD),
10758 diag::err_incomplete_type_vtable_pointer_auth))
10759 return;
10760
10761 const CXXRecordDecl *PrimaryBase = &RD;
10762 if (PrimaryBase->hasAnyDependentBases())
10763 return;
10764
10765 while (1) {
10766 assert(PrimaryBase);
10767 const CXXRecordDecl *Base = nullptr;
10768 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10769 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10770 continue;
10771 Base = BasePtr.getType()->getAsCXXRecordDecl();
10772 break;
10773 }
10774 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10775 break;
10776 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10777 diag::err_non_top_level_vtable_pointer_auth)
10778 << &RD << Base;
10779 PrimaryBase = Base;
10780 }
10781
10782 if (!RD.isPolymorphic())
10783 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10784 diag::err_non_polymorphic_vtable_pointer_auth)
10785 << &RD;
10786}
10787
10790 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10791 if (!TagDecl)
10792 return;
10793
10795
10796 for (const ParsedAttr &AL : AttrList) {
10797 if (AL.getKind() != ParsedAttr::AT_Visibility)
10798 continue;
10799 AL.setInvalid();
10800 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10801 }
10802
10803 ActOnFields(S, RLoc, TagDecl,
10805 // strict aliasing violation!
10806 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10807 FieldCollector->getCurNumFields()),
10808 LBrac, RBrac, AttrList);
10809
10811}
10812
10813/// Find the equality comparison functions that should be implicitly declared
10814/// in a given class definition, per C++2a [class.compare.default]p3.
10816 ASTContext &Ctx, CXXRecordDecl *RD,
10818 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10819 if (!RD->lookup(EqEq).empty())
10820 // Member operator== explicitly declared: no implicit operator==s.
10821 return;
10822
10823 // Traverse friends looking for an '==' or a '<=>'.
10824 for (FriendDecl *Friend : RD->friends()) {
10825 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10826 if (!FD) continue;
10827
10828 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10829 // Friend operator== explicitly declared: no implicit operator==s.
10830 Spaceships.clear();
10831 return;
10832 }
10833
10834 if (FD->getOverloadedOperator() == OO_Spaceship &&
10836 Spaceships.push_back(FD);
10837 }
10838
10839 // Look for members named 'operator<=>'.
10841 for (NamedDecl *ND : RD->lookup(Cmp)) {
10842 // Note that we could find a non-function here (either a function template
10843 // or a using-declaration). Neither case results in an implicit
10844 // 'operator=='.
10845 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10846 if (FD->isExplicitlyDefaulted())
10847 Spaceships.push_back(FD);
10848 }
10849}
10850
10852 // Don't add implicit special members to templated classes.
10853 // FIXME: This means unqualified lookups for 'operator=' within a class
10854 // template don't work properly.
10855 if (!ClassDecl->isDependentType()) {
10856 if (ClassDecl->needsImplicitDefaultConstructor()) {
10857 ++getASTContext().NumImplicitDefaultConstructors;
10858
10859 if (ClassDecl->hasInheritedConstructor())
10861 }
10862
10863 if (ClassDecl->needsImplicitCopyConstructor()) {
10864 ++getASTContext().NumImplicitCopyConstructors;
10865
10866 // If the properties or semantics of the copy constructor couldn't be
10867 // determined while the class was being declared, force a declaration
10868 // of it now.
10870 ClassDecl->hasInheritedConstructor())
10872 // For the MS ABI we need to know whether the copy ctor is deleted. A
10873 // prerequisite for deleting the implicit copy ctor is that the class has
10874 // a move ctor or move assignment that is either user-declared or whose
10875 // semantics are inherited from a subobject. FIXME: We should provide a
10876 // more direct way for CodeGen to ask whether the constructor was deleted.
10877 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10878 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10880 ClassDecl->hasUserDeclaredMoveAssignment() ||
10883 }
10884
10885 if (getLangOpts().CPlusPlus11 &&
10886 ClassDecl->needsImplicitMoveConstructor()) {
10887 ++getASTContext().NumImplicitMoveConstructors;
10888
10890 ClassDecl->hasInheritedConstructor())
10892 }
10893
10894 if (ClassDecl->needsImplicitCopyAssignment()) {
10895 ++getASTContext().NumImplicitCopyAssignmentOperators;
10896
10897 // If we have a dynamic class, then the copy assignment operator may be
10898 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10899 // it shows up in the right place in the vtable and that we diagnose
10900 // problems with the implicit exception specification.
10901 if (ClassDecl->isDynamicClass() ||
10903 ClassDecl->hasInheritedAssignment())
10905 }
10906
10907 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10908 ++getASTContext().NumImplicitMoveAssignmentOperators;
10909
10910 // Likewise for the move assignment operator.
10911 if (ClassDecl->isDynamicClass() ||
10913 ClassDecl->hasInheritedAssignment())
10915 }
10916
10917 if (ClassDecl->needsImplicitDestructor()) {
10918 ++getASTContext().NumImplicitDestructors;
10919
10920 // If we have a dynamic class, then the destructor may be virtual, so we
10921 // have to declare the destructor immediately. This ensures that, e.g., it
10922 // shows up in the right place in the vtable and that we diagnose problems
10923 // with the implicit exception specification.
10924 if (ClassDecl->isDynamicClass() ||
10926 DeclareImplicitDestructor(ClassDecl);
10927 }
10928 }
10929
10930 // C++2a [class.compare.default]p3:
10931 // If the member-specification does not explicitly declare any member or
10932 // friend named operator==, an == operator function is declared implicitly
10933 // for each defaulted three-way comparison operator function defined in
10934 // the member-specification
10935 // FIXME: Consider doing this lazily.
10936 // We do this during the initial parse for a class template, not during
10937 // instantiation, so that we can handle unqualified lookups for 'operator=='
10938 // when parsing the template.
10940 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10942 DefaultedSpaceships);
10943 for (auto *FD : DefaultedSpaceships)
10944 DeclareImplicitEqualityComparison(ClassDecl, FD);
10945 }
10946}
10947
10948unsigned
10950 llvm::function_ref<Scope *()> EnterScope) {
10951 if (!D)
10952 return 0;
10954
10955 // In order to get name lookup right, reenter template scopes in order from
10956 // outermost to innermost.
10958 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10959
10960 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10961 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10962 ParameterLists.push_back(DD->getTemplateParameterList(i));
10963
10964 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10965 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10966 ParameterLists.push_back(FTD->getTemplateParameters());
10967 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10968 LookupDC = VD->getDeclContext();
10969
10971 ParameterLists.push_back(VTD->getTemplateParameters());
10972 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10973 ParameterLists.push_back(PSD->getTemplateParameters());
10974 }
10975 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10976 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10977 ParameterLists.push_back(TD->getTemplateParameterList(i));
10978
10979 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10981 ParameterLists.push_back(CTD->getTemplateParameters());
10982 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10983 ParameterLists.push_back(PSD->getTemplateParameters());
10984 }
10985 }
10986 // FIXME: Alias declarations and concepts.
10987
10988 unsigned Count = 0;
10989 Scope *InnermostTemplateScope = nullptr;
10990 for (TemplateParameterList *Params : ParameterLists) {
10991 // Ignore explicit specializations; they don't contribute to the template
10992 // depth.
10993 if (Params->size() == 0)
10994 continue;
10995
10996 InnermostTemplateScope = EnterScope();
10997 for (NamedDecl *Param : *Params) {
10998 if (Param->getDeclName()) {
10999 InnermostTemplateScope->AddDecl(Param);
11000 IdResolver.AddDecl(Param);
11001 }
11002 }
11003 ++Count;
11004 }
11005
11006 // Associate the new template scopes with the corresponding entities.
11007 if (InnermostTemplateScope) {
11008 assert(LookupDC && "no enclosing DeclContext for template lookup");
11009 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
11010 }
11011
11012 return Count;
11013}
11014
11016 if (!RecordD) return;
11017 AdjustDeclIfTemplate(RecordD);
11020}
11021
11023 if (!RecordD) return;
11025}
11026
11028 if (!Param)
11029 return;
11030
11031 S->AddDecl(Param);
11032 if (Param->getDeclName())
11033 IdResolver.AddDecl(Param);
11034}
11035
11038
11039/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11040/// C++ method declaration. We're (re-)introducing the given
11041/// function parameter into scope for use in parsing later parts of
11042/// the method declaration. For example, we could see an
11043/// ActOnParamDefaultArgument event for this parameter.
11045 if (!ParamD)
11046 return;
11047
11048 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
11049
11050 S->AddDecl(Param);
11051 if (Param->getDeclName())
11052 IdResolver.AddDecl(Param);
11053}
11054
11056 if (!MethodD)
11057 return;
11058
11059 AdjustDeclIfTemplate(MethodD);
11060
11062
11063 // Now that we have our default arguments, check the constructor
11064 // again. It could produce additional diagnostics or affect whether
11065 // the class has implicitly-declared destructors, among other
11066 // things.
11067 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
11069
11070 // Check the default arguments, which we may have added.
11071 if (!Method->isInvalidDecl())
11073}
11074
11075// Emit the given diagnostic for each non-address-space qualifier.
11076// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11077static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11079 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11080 bool DiagOccurred = false;
11082 [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11083 SourceLocation SL) {
11084 // This diagnostic should be emitted on any qualifier except an addr
11085 // space qualifier. However, forEachQualifier currently doesn't visit
11086 // addr space qualifiers, so there's no way to write this condition
11087 // right now; we just diagnose on everything.
11088 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
11089 DiagOccurred = true;
11090 });
11091 if (DiagOccurred)
11092 D.setInvalidType();
11093 }
11094}
11095
11097 unsigned Kind) {
11098 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11099 return;
11100
11102 if (Chunk.Kind == DeclaratorChunk::Paren ||
11104 return;
11105
11106 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11107 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)
11108 << Kind << Chunk.getSourceRange();
11109 D.setInvalidType();
11110}
11111
11113 StorageClass &SC) {
11114 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11115
11116 // C++ [class.ctor]p3:
11117 // A constructor shall not be virtual (10.3) or static (9.4). A
11118 // constructor can be invoked for a const, volatile or const
11119 // volatile object. A constructor shall not be declared const,
11120 // volatile, or const volatile (9.3.2).
11121 if (isVirtual) {
11122 if (!D.isInvalidType())
11123 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11124 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11126 D.setInvalidType();
11127 }
11128 if (SC == SC_Static) {
11129 if (!D.isInvalidType())
11130 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
11131 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11133 D.setInvalidType();
11134 SC = SC_None;
11135 }
11136
11137 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11139 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
11143 D.setInvalidType();
11144 }
11145
11146 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
11147 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);
11148
11149 // C++0x [class.ctor]p4:
11150 // A constructor shall not be declared with a ref-qualifier.
11152 if (FTI.hasRefQualifier()) {
11153 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
11156 D.setInvalidType();
11157 }
11158
11159 // Rebuild the function type "R" without any type qualifiers (in
11160 // case any of the errors above fired) and with "void" as the
11161 // return type, since constructors don't have return types.
11162 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11163 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11164 return R;
11165
11167 EPI.TypeQuals = Qualifiers();
11168 EPI.RefQualifier = RQ_None;
11169
11170 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
11171}
11172
11174 CXXRecordDecl *ClassDecl
11175 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
11176 if (!ClassDecl)
11177 return Constructor->setInvalidDecl();
11178
11179 // C++ [class.copy]p3:
11180 // A declaration of a constructor for a class X is ill-formed if
11181 // its first parameter is of type (optionally cv-qualified) X and
11182 // either there are no other parameters or else all other
11183 // parameters have default arguments.
11184 if (!Constructor->isInvalidDecl() &&
11185 Constructor->hasOneParamOrDefaultArgs() &&
11186 !Constructor->isFunctionTemplateSpecialization()) {
11187 CanQualType ParamType =
11188 Constructor->getParamDecl(0)->getType()->getCanonicalTypeUnqualified();
11189 CanQualType ClassTy = Context.getCanonicalTagType(ClassDecl);
11190 if (ParamType == ClassTy) {
11191 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
11192 const char *ConstRef
11193 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
11194 : " const &";
11195 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
11196 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
11197
11198 // FIXME: Rather that making the constructor invalid, we should endeavor
11199 // to fix the type.
11200 Constructor->setInvalidDecl();
11201 }
11202 }
11203}
11204
11206 CXXRecordDecl *RD = Destructor->getParent();
11207
11208 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11209 SourceLocation Loc;
11210
11211 if (!Destructor->isImplicit())
11212 Loc = Destructor->getLocation();
11213 else
11214 Loc = RD->getLocation();
11215
11216 DeclarationName Name =
11217 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
11218 // If we have a virtual destructor, look up the deallocation function
11220 Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11221 Expr *ThisArg = nullptr;
11222
11223 // If the notional 'delete this' expression requires a non-trivial
11224 // conversion from 'this' to the type of a destroying operator delete's
11225 // first parameter, perform that conversion now.
11226 if (OperatorDelete->isDestroyingOperatorDelete()) {
11227 unsigned AddressParamIndex = 0;
11228 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11229 ++AddressParamIndex;
11230 QualType ParamType =
11231 OperatorDelete->getParamDecl(AddressParamIndex)->getType();
11232 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
11233 // C++ [class.dtor]p13:
11234 // ... as if for the expression 'delete this' appearing in a
11235 // non-virtual destructor of the destructor's class.
11236 ContextRAII SwitchContext(*this, Destructor);
11238 OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());
11239 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11240 This = PerformImplicitConversion(This.get(), ParamType,
11242 if (This.isInvalid()) {
11243 // FIXME: Register this as a context note so that it comes out
11244 // in the right order.
11245 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
11246 return true;
11247 }
11248 ThisArg = This.get();
11249 }
11250 }
11251
11252 DiagnoseUseOfDecl(OperatorDelete, Loc);
11253 MarkFunctionReferenced(Loc, OperatorDelete);
11254 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
11255
11256 if (isa<CXXMethodDecl>(OperatorDelete) &&
11257 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11258 Context.getLangOpts())) {
11259 // In Microsoft ABI whenever a class has a defined operator delete,
11260 // scalar deleting destructors check the 3rd bit of the implicit
11261 // parameter and if it is set, then, global operator delete must be
11262 // called instead of the class-specific one. Find and save the global
11263 // operator delete for that case. Do not diagnose at this point because
11264 // the lack of a global operator delete is not an error if there are no
11265 // delete calls that require it.
11266 FunctionDecl *GlobalOperatorDelete =
11267 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11268 /*LookForGlobal*/ true, Name);
11269 if (GlobalOperatorDelete) {
11270 MarkFunctionReferenced(Loc, GlobalOperatorDelete);
11271 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11272 }
11273 }
11274
11275 if (Context.getTargetInfo().emitVectorDeletingDtors(
11276 Context.getLangOpts())) {
11277 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11278 DeclarationName VDeleteName =
11279 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
11281 Loc, RD, /*Diagnose*/ false,
11282 /*LookForGlobal*/ false, VDeleteName);
11283 if (ArrOperatorDelete && isa<CXXMethodDecl>(ArrOperatorDelete)) {
11284 FunctionDecl *GlobalArrOperatorDelete =
11285 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,
11286 /*LookForGlobal*/ true,
11287 VDeleteName);
11288 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11289 if (GlobalArrOperatorDelete &&
11290 Context.classNeedsVectorDeletingDestructor(RD))
11291 MarkFunctionReferenced(Loc, GlobalArrOperatorDelete);
11292 } else if (!ArrOperatorDelete) {
11293 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11294 Loc, RD, /*Diagnose*/ false,
11295 /*LookForGlobal*/ true, VDeleteName);
11296 }
11297 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11298 if (ArrOperatorDelete && Context.classNeedsVectorDeletingDestructor(RD))
11299 MarkFunctionReferenced(Loc, ArrOperatorDelete);
11300 }
11301 }
11302 }
11303
11304 return false;
11305}
11306
11308 StorageClass& SC) {
11309 // C++ [class.dtor]p1:
11310 // [...] A typedef-name that names a class is a class-name
11311 // (7.1.3); however, a typedef-name that names a class shall not
11312 // be used as the identifier in the declarator for a destructor
11313 // declaration.
11314 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
11315 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11316 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11317 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11318 else if (const TemplateSpecializationType *TST =
11319 DeclaratorType->getAs<TemplateSpecializationType>())
11320 if (TST->isTypeAlias())
11321 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11322 << DeclaratorType << 1;
11323
11324 // C++ [class.dtor]p2:
11325 // A destructor is used to destroy objects of its class type. A
11326 // destructor takes no parameters, and no return type can be
11327 // specified for it (not even void). The address of a destructor
11328 // shall not be taken. A destructor shall not be static. A
11329 // destructor can be invoked for a const, volatile or const
11330 // volatile object. A destructor shall not be declared const,
11331 // volatile or const volatile (9.3.2).
11332 if (SC == SC_Static) {
11333 if (!D.isInvalidType())
11334 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11335 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11338
11339 SC = SC_None;
11340 }
11341 if (!D.isInvalidType()) {
11342 // Destructors don't have return types, but the parser will
11343 // happily parse something like:
11344 //
11345 // class X {
11346 // float ~X();
11347 // };
11348 //
11349 // The return type will be eliminated later.
11350 if (D.getDeclSpec().hasTypeSpecifier())
11351 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11354 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11355 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11361 D.setInvalidType();
11362 }
11363 }
11364
11365 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11366 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);
11367
11368 // C++0x [class.dtor]p2:
11369 // A destructor shall not be declared with a ref-qualifier.
11371 if (FTI.hasRefQualifier()) {
11372 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11375 D.setInvalidType();
11376 }
11377
11378 // Make sure we don't have any parameters.
11379 if (FTIHasNonVoidParameters(FTI)) {
11380 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11381
11382 // Delete the parameters.
11383 FTI.freeParams();
11384 D.setInvalidType();
11385 }
11386
11387 // Make sure the destructor isn't variadic.
11388 if (FTI.isVariadic) {
11389 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11390 D.setInvalidType();
11391 }
11392
11393 // Rebuild the function type "R" without any type qualifiers or
11394 // parameters (in case any of the errors above fired) and with
11395 // "void" as the return type, since destructors don't have return
11396 // types.
11397 if (!D.isInvalidType())
11398 return R;
11399
11400 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11402 EPI.Variadic = false;
11403 EPI.TypeQuals = Qualifiers();
11404 EPI.RefQualifier = RQ_None;
11405 return Context.getFunctionType(Context.VoidTy, {}, EPI);
11406}
11407
11408static void extendLeft(SourceRange &R, SourceRange Before) {
11409 if (Before.isInvalid())
11410 return;
11411 R.setBegin(Before.getBegin());
11412 if (R.getEnd().isInvalid())
11413 R.setEnd(Before.getEnd());
11414}
11415
11416static void extendRight(SourceRange &R, SourceRange After) {
11417 if (After.isInvalid())
11418 return;
11419 if (R.getBegin().isInvalid())
11420 R.setBegin(After.getBegin());
11421 R.setEnd(After.getEnd());
11422}
11423
11425 StorageClass& SC) {
11426 // C++ [class.conv.fct]p1:
11427 // Neither parameter types nor return type can be specified. The
11428 // type of a conversion function (8.3.5) is "function taking no
11429 // parameter returning conversion-type-id."
11430 if (SC == SC_Static) {
11431 if (!D.isInvalidType())
11432 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11434 << D.getName().getSourceRange();
11435 D.setInvalidType();
11436 SC = SC_None;
11437 }
11438
11439 TypeSourceInfo *ConvTSI = nullptr;
11440 QualType ConvType =
11442
11443 const DeclSpec &DS = D.getDeclSpec();
11444 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11445 // Conversion functions don't have return types, but the parser will
11446 // happily parse something like:
11447 //
11448 // class X {
11449 // float operator bool();
11450 // };
11451 //
11452 // The return type will be changed later anyway.
11453 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11456 D.setInvalidType();
11457 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11458 // It's also plausible that the user writes type qualifiers in the wrong
11459 // place, such as:
11460 // struct S { const operator int(); };
11461 // FIXME: we could provide a fixit to move the qualifiers onto the
11462 // conversion type.
11463 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11464 << SourceRange(D.getIdentifierLoc()) << 0;
11465 D.setInvalidType();
11466 }
11467 const auto *Proto = R->castAs<FunctionProtoType>();
11468 // Make sure we don't have any parameters.
11470 unsigned NumParam = Proto->getNumParams();
11471
11472 // [C++2b]
11473 // A conversion function shall have no non-object parameters.
11474 if (NumParam == 1) {
11476 if (const auto *First =
11477 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11478 First && First->isExplicitObjectParameter())
11479 NumParam--;
11480 }
11481
11482 if (NumParam != 0) {
11483 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11484 // Delete the parameters.
11485 FTI.freeParams();
11486 D.setInvalidType();
11487 } else if (Proto->isVariadic()) {
11488 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11489 D.setInvalidType();
11490 }
11491
11492 // Diagnose "&operator bool()" and other such nonsense. This
11493 // is actually a gcc extension which we don't support.
11494 if (Proto->getReturnType() != ConvType) {
11495 bool NeedsTypedef = false;
11496 SourceRange Before, After;
11497
11498 // Walk the chunks and extract information on them for our diagnostic.
11499 bool PastFunctionChunk = false;
11500 for (auto &Chunk : D.type_objects()) {
11501 switch (Chunk.Kind) {
11503 if (!PastFunctionChunk) {
11504 if (Chunk.Fun.HasTrailingReturnType) {
11505 TypeSourceInfo *TRT = nullptr;
11506 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11507 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11508 }
11509 PastFunctionChunk = true;
11510 break;
11511 }
11512 [[fallthrough]];
11514 NeedsTypedef = true;
11515 extendRight(After, Chunk.getSourceRange());
11516 break;
11517
11523 extendLeft(Before, Chunk.getSourceRange());
11524 break;
11525
11527 extendLeft(Before, Chunk.Loc);
11528 extendRight(After, Chunk.EndLoc);
11529 break;
11530 }
11531 }
11532
11533 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11534 After.isValid() ? After.getBegin() :
11535 D.getIdentifierLoc();
11536 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11537 DB << Before << After;
11538
11539 if (!NeedsTypedef) {
11540 DB << /*don't need a typedef*/0;
11541
11542 // If we can provide a correct fix-it hint, do so.
11543 if (After.isInvalid() && ConvTSI) {
11544 SourceLocation InsertLoc =
11546 DB << FixItHint::CreateInsertion(InsertLoc, " ")
11548 InsertLoc, CharSourceRange::getTokenRange(Before))
11549 << FixItHint::CreateRemoval(Before);
11550 }
11551 } else if (!Proto->getReturnType()->isDependentType()) {
11552 DB << /*typedef*/1 << Proto->getReturnType();
11553 } else if (getLangOpts().CPlusPlus11) {
11554 DB << /*alias template*/2 << Proto->getReturnType();
11555 } else {
11556 DB << /*might not be fixable*/3;
11557 }
11558
11559 // Recover by incorporating the other type chunks into the result type.
11560 // Note, this does *not* change the name of the function. This is compatible
11561 // with the GCC extension:
11562 // struct S { &operator int(); } s;
11563 // int &r = s.operator int(); // ok in GCC
11564 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11565 ConvType = Proto->getReturnType();
11566 }
11567
11568 // C++ [class.conv.fct]p4:
11569 // The conversion-type-id shall not represent a function type nor
11570 // an array type.
11571 if (ConvType->isArrayType()) {
11572 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11573 ConvType = Context.getPointerType(ConvType);
11574 D.setInvalidType();
11575 } else if (ConvType->isFunctionType()) {
11576 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11577 ConvType = Context.getPointerType(ConvType);
11578 D.setInvalidType();
11579 }
11580
11581 // Rebuild the function type "R" without any parameters (in case any
11582 // of the errors above fired) and with the conversion type as the
11583 // return type.
11584 if (D.isInvalidType())
11585 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());
11586
11587 // C++0x explicit conversion operators.
11591 ? diag::warn_cxx98_compat_explicit_conversion_functions
11592 : diag::ext_explicit_conversion_functions)
11594}
11595
11597 assert(Conversion && "Expected to receive a conversion function declaration");
11598
11599 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11600
11601 // Make sure we aren't redeclaring the conversion function.
11602 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11603 // C++ [class.conv.fct]p1:
11604 // [...] A conversion function is never used to convert a
11605 // (possibly cv-qualified) object to the (possibly cv-qualified)
11606 // same object type (or a reference to it), to a (possibly
11607 // cv-qualified) base class of that type (or a reference to it),
11608 // or to (possibly cv-qualified) void.
11609 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
11610 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11611 ConvType = ConvTypeRef->getPointeeType();
11612 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11614 /* Suppress diagnostics for instantiations. */;
11615 else if (Conversion->size_overridden_methods() != 0)
11616 /* Suppress diagnostics for overriding virtual function in a base class. */;
11617 else if (ConvType->isRecordType()) {
11618 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11619 if (ConvType == ClassType)
11620 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11621 << ClassType;
11622 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11623 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11624 << ClassType << ConvType;
11625 } else if (ConvType->isVoidType()) {
11626 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11627 << ClassType << ConvType;
11628 }
11629
11630 if (FunctionTemplateDecl *ConversionTemplate =
11631 Conversion->getDescribedFunctionTemplate()) {
11632 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11633 ConvType = ConvTypePtr->getPointeeType();
11634 }
11635 if (ConvType->isUndeducedAutoType()) {
11636 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11637 << getReturnTypeLoc(Conversion).getSourceRange()
11638 << ConvType->castAs<AutoType>()->getKeyword()
11639 << /* in declaration of conversion function template= */ 24;
11640 }
11641
11642 return ConversionTemplate;
11643 }
11644
11645 return Conversion;
11646}
11647
11652
11656
11658 DeclarationName Name, QualType R,
11659 bool IsLambda, DeclContext *DC) {
11660 if (!D.isFunctionDeclarator())
11661 return;
11662
11664 if (FTI.NumParams == 0)
11665 return;
11666 ParmVarDecl *ExplicitObjectParam = nullptr;
11667 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11668 const auto &ParamInfo = FTI.Params[Idx];
11669 if (!ParamInfo.Param)
11670 continue;
11671 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11672 if (!Param->isExplicitObjectParameter())
11673 continue;
11674 if (Idx == 0) {
11675 ExplicitObjectParam = Param;
11676 continue;
11677 } else {
11678 Diag(Param->getLocation(),
11679 diag::err_explicit_object_parameter_must_be_first)
11680 << IsLambda << Param->getSourceRange();
11681 }
11682 }
11683 if (!ExplicitObjectParam)
11684 return;
11685
11686 if (ExplicitObjectParam->hasDefaultArg()) {
11687 Diag(ExplicitObjectParam->getLocation(),
11688 diag::err_explicit_object_default_arg)
11689 << ExplicitObjectParam->getSourceRange();
11690 D.setInvalidType();
11691 }
11692
11695 D.isStaticMember())) {
11696 Diag(ExplicitObjectParam->getBeginLoc(),
11697 diag::err_explicit_object_parameter_nonmember)
11698 << D.getSourceRange() << /*static=*/0 << IsLambda;
11699 D.setInvalidType();
11700 }
11701
11702 if (D.getDeclSpec().isVirtualSpecified()) {
11703 Diag(ExplicitObjectParam->getBeginLoc(),
11704 diag::err_explicit_object_parameter_nonmember)
11705 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11706 D.setInvalidType();
11707 }
11708
11709 // Friend declarations require some care. Consider:
11710 //
11711 // namespace N {
11712 // struct A{};
11713 // int f(A);
11714 // }
11715 //
11716 // struct S {
11717 // struct T {
11718 // int f(this T);
11719 // };
11720 //
11721 // friend int T::f(this T); // Allow this.
11722 // friend int f(this S); // But disallow this.
11723 // friend int N::f(this A); // And disallow this.
11724 // };
11725 //
11726 // Here, it seems to suffice to check whether the scope
11727 // specifier designates a class type.
11728 if (D.getDeclSpec().isFriendSpecified() &&
11729 !isa_and_present<CXXRecordDecl>(
11731 Diag(ExplicitObjectParam->getBeginLoc(),
11732 diag::err_explicit_object_parameter_nonmember)
11733 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11734 D.setInvalidType();
11735 }
11736
11737 if (IsLambda && FTI.hasMutableQualifier()) {
11738 Diag(ExplicitObjectParam->getBeginLoc(),
11739 diag::err_explicit_object_parameter_mutable)
11740 << D.getSourceRange();
11741 }
11742
11743 if (IsLambda)
11744 return;
11745
11746 if (!DC || !DC->isRecord()) {
11747 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11748 "should have been diagnosed already");
11749 return;
11750 }
11751
11752 // CWG2674: constructors and destructors cannot have explicit parameters.
11755 Diag(ExplicitObjectParam->getBeginLoc(),
11756 diag::err_explicit_object_parameter_constructor)
11758 << D.getSourceRange();
11759 D.setInvalidType();
11760 }
11761}
11762
11763namespace {
11764/// Utility class to accumulate and print a diagnostic listing the invalid
11765/// specifier(s) on a declaration.
11766struct BadSpecifierDiagnoser {
11767 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11768 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11769 ~BadSpecifierDiagnoser() {
11770 Diagnostic << Specifiers;
11771 }
11772
11773 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11774 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11775 }
11776 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11777 return check(SpecLoc,
11779 }
11780 void check(SourceLocation SpecLoc, const char *Spec) {
11781 if (SpecLoc.isInvalid()) return;
11782 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11783 if (!Specifiers.empty()) Specifiers += " ";
11784 Specifiers += Spec;
11785 }
11786
11787 Sema &S;
11788 Sema::SemaDiagnosticBuilder Diagnostic;
11789 std::string Specifiers;
11790};
11791}
11792
11794 StorageClass &SC) {
11795 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11796 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11797 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11798
11799 // C++ [temp.deduct.guide]p3:
11800 // A deduction-gide shall be declared in the same scope as the
11801 // corresponding class template.
11802 if (!CurContext->getRedeclContext()->Equals(
11803 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11804 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11805 << GuidedTemplateDecl;
11806 NoteTemplateLocation(*GuidedTemplateDecl);
11807 }
11808
11809 auto &DS = D.getMutableDeclSpec();
11810 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11811 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11812 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11813 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11814 BadSpecifierDiagnoser Diagnoser(
11815 *this, D.getIdentifierLoc(),
11816 diag::err_deduction_guide_invalid_specifier);
11817
11818 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11819 DS.ClearStorageClassSpecs();
11820 SC = SC_None;
11821
11822 // 'explicit' is permitted.
11823 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11824 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11825 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11826 DS.ClearConstexprSpec();
11827
11828 Diagnoser.check(DS.getConstSpecLoc(), "const");
11829 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11830 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11831 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11832 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11833 DS.ClearTypeQualifiers();
11834
11835 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11836 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11837 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11838 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11839 DS.ClearTypeSpecType();
11840 }
11841
11842 if (D.isInvalidType())
11843 return true;
11844
11845 // Check the declarator is simple enough.
11846 bool FoundFunction = false;
11847 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11848 if (Chunk.Kind == DeclaratorChunk::Paren)
11849 continue;
11850 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11852 diag::err_deduction_guide_with_complex_decl)
11853 << D.getSourceRange();
11854 break;
11855 }
11856 if (!Chunk.Fun.hasTrailingReturnType())
11857 return Diag(D.getName().getBeginLoc(),
11858 diag::err_deduction_guide_no_trailing_return_type);
11859
11860 // Check that the return type is written as a specialization of
11861 // the template specified as the deduction-guide's name.
11862 // The template name may not be qualified. [temp.deduct.guide]
11863 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11864 TypeSourceInfo *TSI = nullptr;
11865 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11866 assert(TSI && "deduction guide has valid type but invalid return type?");
11867 bool AcceptableReturnType = false;
11868 bool MightInstantiateToSpecialization = false;
11869 if (auto RetTST =
11871 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11872 bool TemplateMatches = Context.hasSameTemplateName(
11873 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);
11874
11876 SpecifiedName.getAsQualifiedTemplateName();
11877 assert(Qualifiers && "expected QualifiedTemplate");
11878 bool SimplyWritten =
11879 !Qualifiers->hasTemplateKeyword() && !Qualifiers->getQualifier();
11880 if (SimplyWritten && TemplateMatches)
11881 AcceptableReturnType = true;
11882 else {
11883 // This could still instantiate to the right type, unless we know it
11884 // names the wrong class template.
11885 auto *TD = SpecifiedName.getAsTemplateDecl();
11886 MightInstantiateToSpecialization =
11887 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);
11888 }
11889 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11890 MightInstantiateToSpecialization = true;
11891 }
11892
11893 if (!AcceptableReturnType)
11894 return Diag(TSI->getTypeLoc().getBeginLoc(),
11895 diag::err_deduction_guide_bad_trailing_return_type)
11896 << GuidedTemplate << TSI->getType()
11897 << MightInstantiateToSpecialization
11898 << TSI->getTypeLoc().getSourceRange();
11899
11900 // Keep going to check that we don't have any inner declarator pieces (we
11901 // could still have a function returning a pointer to a function).
11902 FoundFunction = true;
11903 }
11904
11905 if (D.isFunctionDefinition())
11906 // we can still create a valid deduction guide here.
11907 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11908 return false;
11909}
11910
11911//===----------------------------------------------------------------------===//
11912// Namespace Handling
11913//===----------------------------------------------------------------------===//
11914
11915/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11916/// reopened.
11918 SourceLocation Loc,
11919 IdentifierInfo *II, bool *IsInline,
11920 NamespaceDecl *PrevNS) {
11921 assert(*IsInline != PrevNS->isInline());
11922
11923 // 'inline' must appear on the original definition, but not necessarily
11924 // on all extension definitions, so the note should point to the first
11925 // definition to avoid confusion.
11926 PrevNS = PrevNS->getFirstDecl();
11927
11928 if (PrevNS->isInline())
11929 // The user probably just forgot the 'inline', so suggest that it
11930 // be added back.
11931 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11932 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11933 else
11934 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11935
11936 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11937 *IsInline = PrevNS->isInline();
11938}
11939
11940/// ActOnStartNamespaceDef - This is called at the start of a namespace
11941/// definition.
11943 SourceLocation InlineLoc,
11944 SourceLocation NamespaceLoc,
11945 SourceLocation IdentLoc, IdentifierInfo *II,
11946 SourceLocation LBrace,
11947 const ParsedAttributesView &AttrList,
11948 UsingDirectiveDecl *&UD, bool IsNested) {
11949 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11950 // For anonymous namespace, take the location of the left brace.
11951 SourceLocation Loc = II ? IdentLoc : LBrace;
11952 bool IsInline = InlineLoc.isValid();
11953 bool IsInvalid = false;
11954 bool IsStd = false;
11955 bool AddToKnown = false;
11956 Scope *DeclRegionScope = NamespcScope->getParent();
11957
11958 NamespaceDecl *PrevNS = nullptr;
11959 if (II) {
11960 // C++ [namespace.std]p7:
11961 // A translation unit shall not declare namespace std to be an inline
11962 // namespace (9.8.2).
11963 //
11964 // Precondition: the std namespace is in the file scope and is declared to
11965 // be inline
11966 auto DiagnoseInlineStdNS = [&]() {
11967 assert(IsInline && II->isStr("std") &&
11968 CurContext->getRedeclContext()->isTranslationUnit() &&
11969 "Precondition of DiagnoseInlineStdNS not met");
11970 Diag(InlineLoc, diag::err_inline_namespace_std)
11971 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11972 IsInline = false;
11973 };
11974 // C++ [namespace.def]p2:
11975 // The identifier in an original-namespace-definition shall not
11976 // have been previously defined in the declarative region in
11977 // which the original-namespace-definition appears. The
11978 // identifier in an original-namespace-definition is the name of
11979 // the namespace. Subsequently in that declarative region, it is
11980 // treated as an original-namespace-name.
11981 //
11982 // Since namespace names are unique in their scope, and we don't
11983 // look through using directives, just look for any ordinary names
11984 // as if by qualified name lookup.
11985 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11987 LookupQualifiedName(R, CurContext->getRedeclContext());
11988 NamedDecl *PrevDecl =
11989 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11990 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11991
11992 if (PrevNS) {
11993 // This is an extended namespace definition.
11994 if (IsInline && II->isStr("std") &&
11995 CurContext->getRedeclContext()->isTranslationUnit())
11996 DiagnoseInlineStdNS();
11997 else if (IsInline != PrevNS->isInline())
11998 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11999 &IsInline, PrevNS);
12000 } else if (PrevDecl) {
12001 // This is an invalid name redefinition.
12002 Diag(Loc, diag::err_redefinition_different_kind)
12003 << II;
12004 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12005 IsInvalid = true;
12006 // Continue on to push Namespc as current DeclContext and return it.
12007 } else if (II->isStr("std") &&
12008 CurContext->getRedeclContext()->isTranslationUnit()) {
12009 if (IsInline)
12010 DiagnoseInlineStdNS();
12011 // This is the first "real" definition of the namespace "std", so update
12012 // our cache of the "std" namespace to point at this definition.
12013 PrevNS = getStdNamespace();
12014 IsStd = true;
12015 AddToKnown = !IsInline;
12016 } else {
12017 // We've seen this namespace for the first time.
12018 AddToKnown = !IsInline;
12019 }
12020 } else {
12021 // Anonymous namespaces.
12022
12023 // Determine whether the parent already has an anonymous namespace.
12024 DeclContext *Parent = CurContext->getRedeclContext();
12025 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12026 PrevNS = TU->getAnonymousNamespace();
12027 } else {
12028 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
12029 PrevNS = ND->getAnonymousNamespace();
12030 }
12031
12032 if (PrevNS && IsInline != PrevNS->isInline())
12033 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
12034 &IsInline, PrevNS);
12035 }
12036
12038 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
12039 if (IsInvalid)
12040 Namespc->setInvalidDecl();
12041
12042 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
12043 AddPragmaAttributes(DeclRegionScope, Namespc);
12044 ProcessAPINotes(Namespc);
12045
12046 // FIXME: Should we be merging attributes?
12047 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12049
12050 if (IsStd)
12051 StdNamespace = Namespc;
12052 if (AddToKnown)
12053 KnownNamespaces[Namespc] = false;
12054
12055 if (II) {
12056 PushOnScopeChains(Namespc, DeclRegionScope);
12057 } else {
12058 // Link the anonymous namespace into its parent.
12059 DeclContext *Parent = CurContext->getRedeclContext();
12060 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
12061 TU->setAnonymousNamespace(Namespc);
12062 } else {
12063 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
12064 }
12065
12066 CurContext->addDecl(Namespc);
12067
12068 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12069 // behaves as if it were replaced by
12070 // namespace unique { /* empty body */ }
12071 // using namespace unique;
12072 // namespace unique { namespace-body }
12073 // where all occurrences of 'unique' in a translation unit are
12074 // replaced by the same identifier and this identifier differs
12075 // from all other identifiers in the entire program.
12076
12077 // We just create the namespace with an empty name and then add an
12078 // implicit using declaration, just like the standard suggests.
12079 //
12080 // CodeGen enforces the "universally unique" aspect by giving all
12081 // declarations semantically contained within an anonymous
12082 // namespace internal linkage.
12083
12084 if (!PrevNS) {
12086 /* 'using' */ LBrace,
12087 /* 'namespace' */ SourceLocation(),
12088 /* qualifier */ NestedNameSpecifierLoc(),
12089 /* identifier */ SourceLocation(),
12090 Namespc,
12091 /* Ancestor */ Parent);
12092 UD->setImplicit();
12093 Parent->addDecl(UD);
12094 }
12095 }
12096
12097 ActOnDocumentableDecl(Namespc);
12098
12099 // Although we could have an invalid decl (i.e. the namespace name is a
12100 // redefinition), push it as current DeclContext and try to continue parsing.
12101 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12102 // for the namespace has the declarations that showed up in that particular
12103 // namespace definition.
12104 PushDeclContext(NamespcScope, Namespc);
12105 return Namespc;
12106}
12107
12108/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12109/// is a namespace alias, returns the namespace it points to.
12111 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
12112 return AD->getNamespace();
12113 return dyn_cast_or_null<NamespaceDecl>(D);
12114}
12115
12117 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
12118 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12119 Namespc->setRBraceLoc(RBrace);
12121 if (Namespc->hasAttr<VisibilityAttr>())
12122 PopPragmaVisibility(true, RBrace);
12123 // If this namespace contains an export-declaration, export it now.
12124 if (DeferredExportedNamespaces.erase(Namespc))
12126}
12127
12129 return cast_or_null<CXXRecordDecl>(
12130 StdBadAlloc.get(Context.getExternalSource()));
12131}
12132
12134 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
12135}
12136
12138 return cast_or_null<NamespaceDecl>(
12139 StdNamespace.get(Context.getExternalSource()));
12140}
12141
12142namespace {
12143
12144enum UnsupportedSTLSelect {
12145 USS_InvalidMember,
12146 USS_MissingMember,
12147 USS_NonTrivial,
12148 USS_Other
12149};
12150
12151struct InvalidSTLDiagnoser {
12152 Sema &S;
12153 SourceLocation Loc;
12154 QualType TyForDiags;
12155
12156 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12157 const VarDecl *VD = nullptr) {
12158 {
12159 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
12160 << TyForDiags << ((int)Sel);
12161 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12162 assert(!Name.empty());
12163 D << Name;
12164 }
12165 }
12166 if (Sel == USS_InvalidMember) {
12167 S.Diag(VD->getLocation(), diag::note_var_declared_here)
12168 << VD << VD->getSourceRange();
12169 }
12170 return QualType();
12171 }
12172};
12173} // namespace
12174
12176 SourceLocation Loc,
12178 assert(getLangOpts().CPlusPlus &&
12179 "Looking for comparison category type outside of C++.");
12180
12181 // Use an elaborated type for diagnostics which has a name containing the
12182 // prepended 'std' namespace but not any inline namespace names.
12183 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12185 /*Prefix=*/std::nullopt);
12186 return Context.getTagType(ElaboratedTypeKeyword::None, Qualifier,
12187 Info->Record,
12188 /*OwnsTag=*/false);
12189 };
12190
12191 // Check if we've already successfully checked the comparison category type
12192 // before. If so, skip checking it again.
12193 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12194 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12195 // The only thing we need to check is that the type has a reachable
12196 // definition in the current context.
12197 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12198 return QualType();
12199
12200 return Info->getType();
12201 }
12202
12203 // If lookup failed
12204 if (!Info) {
12205 std::string NameForDiags = "std::";
12206 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12207 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
12208 << NameForDiags << (int)Usage;
12209 return QualType();
12210 }
12211
12212 assert(Info->Kind == Kind);
12213 assert(Info->Record);
12214
12215 // Update the Record decl in case we encountered a forward declaration on our
12216 // first pass. FIXME: This is a bit of a hack.
12217 if (Info->Record->hasDefinition())
12218 Info->Record = Info->Record->getDefinition();
12219
12220 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
12221 return QualType();
12222
12223 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
12224
12225 if (!Info->Record->isTriviallyCopyable())
12226 return UnsupportedSTLError(USS_NonTrivial);
12227
12228 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12229 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12230 // Tolerate empty base classes.
12231 if (Base->isEmpty())
12232 continue;
12233 // Reject STL implementations which have at least one non-empty base.
12234 return UnsupportedSTLError();
12235 }
12236
12237 // Check that the STL has implemented the types using a single integer field.
12238 // This expectation allows better codegen for builtin operators. We require:
12239 // (1) The class has exactly one field.
12240 // (2) The field is an integral or enumeration type.
12241 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12242 if (std::distance(FIt, FEnd) != 1 ||
12243 !FIt->getType()->isIntegralOrEnumerationType()) {
12244 return UnsupportedSTLError();
12245 }
12246
12247 // Build each of the require values and store them in Info.
12248 for (ComparisonCategoryResult CCR :
12250 StringRef MemName = ComparisonCategories::getResultString(CCR);
12251 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
12252
12253 if (!ValInfo)
12254 return UnsupportedSTLError(USS_MissingMember, MemName);
12255
12256 VarDecl *VD = ValInfo->VD;
12257 assert(VD && "should not be null!");
12258
12259 // Attempt to diagnose reasons why the STL definition of this type
12260 // might be foobar, including it failing to be a constant expression.
12261 // TODO Handle more ways the lookup or result can be invalid.
12262 if (!VD->isStaticDataMember() ||
12264 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12265
12266 // Attempt to evaluate the var decl as a constant expression and extract
12267 // the value of its first field as a ICE. If this fails, the STL
12268 // implementation is not supported.
12269 if (!ValInfo->hasValidIntValue())
12270 return UnsupportedSTLError();
12271
12272 MarkVariableReferenced(Loc, VD);
12273 }
12274
12275 // We've successfully built the required types and expressions. Update
12276 // the cache and return the newly cached value.
12277 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12278 return Info->getType();
12279}
12280
12282 if (!StdNamespace) {
12283 // The "std" namespace has not yet been defined, so build one implicitly.
12285 Context, Context.getTranslationUnitDecl(),
12286 /*Inline=*/false, SourceLocation(), SourceLocation(),
12287 &PP.getIdentifierTable().get("std"),
12288 /*PrevDecl=*/nullptr, /*Nested=*/false);
12289 getStdNamespace()->setImplicit(true);
12290 // We want the created NamespaceDecl to be available for redeclaration
12291 // lookups, but not for regular name lookups.
12292 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
12293 getStdNamespace()->clearIdentifierNamespace();
12294 }
12295
12296 return getStdNamespace();
12297}
12298
12299static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12300 const char *ClassName,
12301 ClassTemplateDecl **CachedDecl,
12302 const Decl **MalformedDecl) {
12303 // We're looking for implicit instantiations of
12304 // template <typename U> class std::{ClassName}.
12305
12306 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12307 // it.
12308 return false;
12309
12310 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12311 if (!MalformedDecl)
12312 return;
12313 if (!D)
12314 D = SugaredType->getAsTagDecl();
12315 if (!D || !D->isInStdNamespace())
12316 return;
12317 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12318 if (II && II == &S.PP.getIdentifierTable().get(ClassName))
12319 *MalformedDecl = D;
12320 };
12321
12322 ClassTemplateDecl *Template = nullptr;
12324 if (const TemplateSpecializationType *TST =
12326 Template = dyn_cast_or_null<ClassTemplateDecl>(
12327 TST->getTemplateName().getAsTemplateDecl());
12328 Arguments = TST->template_arguments();
12329 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12330 Template = TT->getTemplateDecl();
12331 Arguments = TT->getTemplateArgs(S.Context);
12332 }
12333
12334 if (!Template) {
12335 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12336 return false;
12337 }
12338
12339 if (!*CachedDecl) {
12340 // Haven't recognized std::{ClassName} yet, maybe this is it.
12341 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12342 // semantics of this are slightly different, most notably the existing
12343 // "lookup" semantics explicitly diagnose an invalid definition as an
12344 // error.
12345 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12346 if (TemplateClass->getIdentifier() !=
12347 &S.PP.getIdentifierTable().get(ClassName) ||
12349 TemplateClass->getNonTransparentDeclContext()))
12350 return false;
12351 // This is a template called std::{ClassName}, but is it the right
12352 // template?
12353 TemplateParameterList *Params = Template->getTemplateParameters();
12354 if (Params->getMinRequiredArguments() != 1 ||
12355 !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||
12356 Params->getParam(0)->isTemplateParameterPack()) {
12357 if (MalformedDecl)
12358 *MalformedDecl = TemplateClass;
12359 return false;
12360 }
12361
12362 // It's the right template.
12363 *CachedDecl = Template;
12364 }
12365
12366 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12367 return false;
12368
12369 // This is an instance of std::{ClassName}. Find the argument type.
12370 if (TypeArg) {
12371 QualType ArgType = Arguments[0].getAsType();
12372 // FIXME: Since TST only has as-written arguments, we have to perform the
12373 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12374 // - If an explicitly-specified template argument type is a lifetime type
12375 // with no lifetime qualifier, the __strong lifetime qualifier is
12376 // inferred.
12377 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12378 !ArgType.getObjCLifetime()) {
12379 Qualifiers Qs;
12381 ArgType = S.Context.getQualifiedType(ArgType, Qs);
12382 }
12383 *TypeArg = ArgType;
12384 }
12385
12386 return true;
12387}
12388
12390 assert(getLangOpts().CPlusPlus &&
12391 "Looking for std::initializer_list outside of C++.");
12392
12393 // We're looking for implicit instantiations of
12394 // template <typename E> class std::initializer_list.
12395
12396 return isStdClassTemplate(*this, Ty, Element, "initializer_list",
12397 &StdInitializerList, /*MalformedDecl=*/nullptr);
12398}
12399
12401 const Decl **MalformedDecl) {
12402 assert(getLangOpts().CPlusPlus &&
12403 "Looking for std::type_identity outside of C++.");
12404
12405 // We're looking for implicit instantiations of
12406 // template <typename T> struct std::type_identity.
12407
12408 return isStdClassTemplate(*this, Ty, Element, "type_identity",
12409 &StdTypeIdentity, MalformedDecl);
12410}
12411
12413 const char *ClassName,
12414 bool *WasMalformed) {
12415 if (!S.StdNamespace)
12416 return nullptr;
12417
12418 LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,
12420 if (!S.LookupQualifiedName(Result, S.getStdNamespace()))
12421 return nullptr;
12422
12423 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12424 if (!Template) {
12425 Result.suppressDiagnostics();
12426 // We found something weird. Complain about the first thing we found.
12427 NamedDecl *Found = *Result.begin();
12428 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)
12429 << ClassName;
12430 if (WasMalformed)
12431 *WasMalformed = true;
12432 return nullptr;
12433 }
12434
12435 // We found some template with the correct name. Now verify that it's
12436 // correct.
12437 TemplateParameterList *Params = Template->getTemplateParameters();
12438 if (Params->getMinRequiredArguments() != 1 ||
12439 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12440 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)
12441 << ClassName;
12442 if (WasMalformed)
12443 *WasMalformed = true;
12444 return nullptr;
12445 }
12446
12447 return Template;
12448}
12449
12451 QualType TypeParam, SourceLocation Loc) {
12452 assert(S.getStdNamespace());
12453 TemplateArgumentListInfo Args(Loc, Loc);
12454 auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);
12455 Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12456
12458 Loc, Args, /*Scope=*/nullptr,
12459 /*ForNestedNameSpecifier=*/false);
12460}
12461
12463 if (!StdInitializerList) {
12464 bool WasMalformed = false;
12466 LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);
12467 if (!StdInitializerList) {
12468 if (!WasMalformed)
12469 Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12470 return QualType();
12471 }
12472 }
12473 return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);
12474}
12475
12477 if (!StdTypeIdentity) {
12478 StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",
12479 /*WasMalformed=*/nullptr);
12480 if (!StdTypeIdentity)
12481 return QualType();
12482 }
12483 return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);
12484}
12485
12487 // C++ [dcl.init.list]p2:
12488 // A constructor is an initializer-list constructor if its first parameter
12489 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12490 // std::initializer_list<E> for some type E, and either there are no other
12491 // parameters or else all other parameters have default arguments.
12492 if (!Ctor->hasOneParamOrDefaultArgs())
12493 return false;
12494
12495 QualType ArgType = Ctor->getParamDecl(0)->getType();
12496 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12497 ArgType = RT->getPointeeType().getUnqualifiedType();
12498
12499 return isStdInitializerList(ArgType, nullptr);
12500}
12501
12502/// Determine whether a using statement is in a context where it will be
12503/// apply in all contexts.
12505 switch (CurContext->getDeclKind()) {
12506 case Decl::TranslationUnit:
12507 return true;
12508 case Decl::LinkageSpec:
12509 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12510 default:
12511 return false;
12512 }
12513}
12514
12515namespace {
12516
12517// Callback to only accept typo corrections that are namespaces.
12518class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12519public:
12520 bool ValidateCandidate(const TypoCorrection &candidate) override {
12521 if (NamedDecl *ND = candidate.getCorrectionDecl())
12523 return false;
12524 }
12525
12526 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12527 return std::make_unique<NamespaceValidatorCCC>(*this);
12528 }
12529};
12530
12531}
12532
12533static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12534 Sema &S) {
12535 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12536 Module *M = ND->getOwningModule();
12537 assert(M && "hidden namespace definition not in a module?");
12538
12539 if (M->isExplicitGlobalModule())
12540 S.Diag(Corrected.getCorrectionRange().getBegin(),
12541 diag::err_module_unimported_use_header)
12543 << /*Header Name*/ false;
12544 else
12545 S.Diag(Corrected.getCorrectionRange().getBegin(),
12546 diag::err_module_unimported_use)
12548 << M->getTopLevelModuleName();
12549}
12550
12552 CXXScopeSpec &SS,
12553 SourceLocation IdentLoc,
12554 IdentifierInfo *Ident) {
12555 R.clear();
12556 NamespaceValidatorCCC CCC{};
12557 if (TypoCorrection Corrected =
12558 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12560 // Generally we find it is confusing more than helpful to diagnose the
12561 // invisible namespace.
12562 // See https://github.com/llvm/llvm-project/issues/73893.
12563 //
12564 // However, we should diagnose when the users are trying to using an
12565 // invisible namespace. So we handle the case specially here.
12566 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12567 Corrected.requiresImport()) {
12568 DiagnoseInvisibleNamespace(Corrected, S);
12569 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12570 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12571 bool DroppedSpecifier =
12572 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12573 S.diagnoseTypo(Corrected,
12574 S.PDiag(diag::err_using_directive_member_suggest)
12575 << Ident << DC << DroppedSpecifier << SS.getRange(),
12576 S.PDiag(diag::note_namespace_defined_here));
12577 } else {
12578 S.diagnoseTypo(Corrected,
12579 S.PDiag(diag::err_using_directive_suggest) << Ident,
12580 S.PDiag(diag::note_namespace_defined_here));
12581 }
12582 R.addDecl(Corrected.getFoundDecl());
12583 return true;
12584 }
12585 return false;
12586}
12587
12589 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12590 SourceLocation IdentLoc,
12591 IdentifierInfo *NamespcName,
12592 const ParsedAttributesView &AttrList) {
12593 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12594 assert(NamespcName && "Invalid NamespcName.");
12595 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12596
12597 // Get the innermost enclosing declaration scope.
12598 S = S->getDeclParent();
12599
12600 UsingDirectiveDecl *UDir = nullptr;
12601 NestedNameSpecifier Qualifier = SS.getScopeRep();
12602
12603 // Lookup namespace name.
12604 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12605 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12606 if (R.isAmbiguous())
12607 return nullptr;
12608
12609 if (R.empty()) {
12610 R.clear();
12611 // Allow "using namespace std;" or "using namespace ::std;" even if
12612 // "std" hasn't been defined yet, for GCC compatibility.
12613 if ((!Qualifier ||
12614 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12615 NamespcName->isStr("std")) {
12616 Diag(IdentLoc, diag::ext_using_undefined_std);
12617 R.addDecl(getOrCreateStdNamespace());
12618 R.resolveKind();
12619 }
12620 // Otherwise, attempt typo correction.
12621 else
12622 TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12623 }
12624
12625 if (!R.empty()) {
12626 NamedDecl *Named = R.getRepresentativeDecl();
12627 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12628 assert(NS && "expected namespace decl");
12629
12630 // The use of a nested name specifier may trigger deprecation warnings.
12631 DiagnoseUseOfDecl(Named, IdentLoc);
12632
12633 // C++ [namespace.udir]p1:
12634 // A using-directive specifies that the names in the nominated
12635 // namespace can be used in the scope in which the
12636 // using-directive appears after the using-directive. During
12637 // unqualified name lookup (3.4.1), the names appear as if they
12638 // were declared in the nearest enclosing namespace which
12639 // contains both the using-directive and the nominated
12640 // namespace. [Note: in this context, "contains" means "contains
12641 // directly or indirectly". ]
12642
12643 // Find enclosing context containing both using-directive and
12644 // nominated namespace.
12645 DeclContext *CommonAncestor = NS;
12646 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12647 CommonAncestor = CommonAncestor->getParent();
12648
12649 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12651 IdentLoc, Named, CommonAncestor);
12652
12654 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12655 Diag(IdentLoc, diag::warn_using_directive_in_header);
12656 }
12657
12658 PushUsingDirective(S, UDir);
12659 } else {
12660 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12661 }
12662
12663 if (UDir) {
12664 ProcessDeclAttributeList(S, UDir, AttrList);
12665 ProcessAPINotes(UDir);
12666 }
12667
12668 return UDir;
12669}
12670
12672 // If the scope has an associated entity and the using directive is at
12673 // namespace or translation unit scope, add the UsingDirectiveDecl into
12674 // its lookup structure so qualified name lookup can find it.
12675 DeclContext *Ctx = S->getEntity();
12676 if (Ctx && !Ctx->isFunctionOrMethod())
12677 Ctx->addDecl(UDir);
12678 else
12679 // Otherwise, it is at block scope. The using-directives will affect lookup
12680 // only to the end of the scope.
12681 S->PushUsingDirective(UDir);
12682}
12683
12685 SourceLocation UsingLoc,
12686 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12687 UnqualifiedId &Name,
12688 SourceLocation EllipsisLoc,
12689 const ParsedAttributesView &AttrList) {
12690 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12691
12692 if (SS.isEmpty()) {
12693 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12694 return nullptr;
12695 }
12696
12697 switch (Name.getKind()) {
12703 break;
12704
12707 // C++11 inheriting constructors.
12708 Diag(Name.getBeginLoc(),
12710 ? diag::warn_cxx98_compat_using_decl_constructor
12711 : diag::err_using_decl_constructor)
12712 << SS.getRange();
12713
12714 if (getLangOpts().CPlusPlus11) break;
12715
12716 return nullptr;
12717
12719 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12720 return nullptr;
12721
12723 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12725 return nullptr;
12726
12728 llvm_unreachable("cannot parse qualified deduction guide name");
12729 }
12730
12731 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12732 DeclarationName TargetName = TargetNameInfo.getName();
12733 if (!TargetName)
12734 return nullptr;
12735
12736 // Warn about access declarations.
12737 if (UsingLoc.isInvalid()) {
12739 ? diag::err_access_decl
12740 : diag::warn_access_decl_deprecated)
12741 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12742 }
12743
12744 if (EllipsisLoc.isInvalid()) {
12747 return nullptr;
12748 } else {
12750 !TargetNameInfo.containsUnexpandedParameterPack()) {
12751 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12752 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12753 EllipsisLoc = SourceLocation();
12754 }
12755 }
12756
12757 NamedDecl *UD =
12758 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12759 SS, TargetNameInfo, EllipsisLoc, AttrList,
12760 /*IsInstantiation*/ false,
12761 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12762 if (UD)
12763 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12764
12765 return UD;
12766}
12767
12769 SourceLocation UsingLoc,
12770 SourceLocation EnumLoc, SourceRange TyLoc,
12771 const IdentifierInfo &II, ParsedType Ty,
12772 const CXXScopeSpec &SS) {
12773 TypeSourceInfo *TSI = nullptr;
12774 SourceLocation IdentLoc = TyLoc.getBegin();
12775 QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12776 if (EnumTy.isNull()) {
12777 Diag(IdentLoc, isDependentScopeSpecifier(SS)
12778 ? diag::err_using_enum_is_dependent
12779 : diag::err_unknown_typename)
12780 << II.getName()
12781 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12782 TyLoc.getEnd());
12783 return nullptr;
12784 }
12785
12786 if (EnumTy->isDependentType()) {
12787 Diag(IdentLoc, diag::err_using_enum_is_dependent);
12788 return nullptr;
12789 }
12790
12791 auto *Enum = EnumTy->getAsEnumDecl();
12792 if (!Enum) {
12793 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12794 return nullptr;
12795 }
12796
12797 if (TSI == nullptr)
12798 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12799
12800 auto *UD =
12801 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12802
12803 if (UD)
12804 PushOnScopeChains(UD, S, /*AddToContext*/ false);
12805
12806 return UD;
12807}
12808
12809/// Determine whether a using declaration considers the given
12810/// declarations as "equivalent", e.g., if they are redeclarations of
12811/// the same entity or are both typedefs of the same type.
12812static bool
12814 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12815 return true;
12816
12817 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12818 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12819 return Context.hasSameType(TD1->getUnderlyingType(),
12820 TD2->getUnderlyingType());
12821
12822 // Two using_if_exists using-declarations are equivalent if both are
12823 // unresolved.
12826 return true;
12827
12828 return false;
12829}
12830
12832 const LookupResult &Previous,
12833 UsingShadowDecl *&PrevShadow) {
12834 // Diagnose finding a decl which is not from a base class of the
12835 // current class. We do this now because there are cases where this
12836 // function will silently decide not to build a shadow decl, which
12837 // will pre-empt further diagnostics.
12838 //
12839 // We don't need to do this in C++11 because we do the check once on
12840 // the qualifier.
12841 //
12842 // FIXME: diagnose the following if we care enough:
12843 // struct A { int foo; };
12844 // struct B : A { using A::foo; };
12845 // template <class T> struct C : A {};
12846 // template <class T> struct D : C<T> { using B::foo; } // <---
12847 // This is invalid (during instantiation) in C++03 because B::foo
12848 // resolves to the using decl in B, which is not a base class of D<T>.
12849 // We can't diagnose it immediately because C<T> is an unknown
12850 // specialization. The UsingShadowDecl in D<T> then points directly
12851 // to A::foo, which will look well-formed when we instantiate.
12852 // The right solution is to not collapse the shadow-decl chain.
12853 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12854 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12855 DeclContext *OrigDC = Orig->getDeclContext();
12856
12857 // Handle enums and anonymous structs.
12858 if (isa<EnumDecl>(OrigDC))
12859 OrigDC = OrigDC->getParent();
12860 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12861 while (OrigRec->isAnonymousStructOrUnion())
12862 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12863
12865 if (OrigDC == CurContext) {
12866 Diag(Using->getLocation(),
12867 diag::err_using_decl_nested_name_specifier_is_current_class)
12868 << Using->getQualifierLoc().getSourceRange();
12869 Diag(Orig->getLocation(), diag::note_using_decl_target);
12870 Using->setInvalidDecl();
12871 return true;
12872 }
12873
12874 Diag(Using->getQualifierLoc().getBeginLoc(),
12875 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12876 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12877 << Using->getQualifierLoc().getSourceRange();
12878 Diag(Orig->getLocation(), diag::note_using_decl_target);
12879 Using->setInvalidDecl();
12880 return true;
12881 }
12882 }
12883
12884 if (Previous.empty()) return false;
12885
12886 NamedDecl *Target = Orig;
12888 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12889
12890 // If the target happens to be one of the previous declarations, we
12891 // don't have a conflict.
12892 //
12893 // FIXME: but we might be increasing its access, in which case we
12894 // should redeclare it.
12895 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12896 bool FoundEquivalentDecl = false;
12897 for (NamedDecl *Element : Previous) {
12898 NamedDecl *D = Element->getUnderlyingDecl();
12899 // We can have UsingDecls in our Previous results because we use the same
12900 // LookupResult for checking whether the UsingDecl itself is a valid
12901 // redeclaration.
12903 continue;
12904
12905 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12906 // C++ [class.mem]p19:
12907 // If T is the name of a class, then [every named member other than
12908 // a non-static data member] shall have a name different from T
12909 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12913 CurContext,
12915 return true;
12916 }
12917
12919 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Element))
12920 PrevShadow = Shadow;
12921 FoundEquivalentDecl = true;
12923 // We don't conflict with an existing using shadow decl of an equivalent
12924 // declaration, but we're not a redeclaration of it.
12925 FoundEquivalentDecl = true;
12926 }
12927
12928 if (isVisible(D))
12929 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12930 }
12931
12932 if (FoundEquivalentDecl)
12933 return false;
12934
12935 // Always emit a diagnostic for a mismatch between an unresolved
12936 // using_if_exists and a resolved using declaration in either direction.
12938 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12939 if (!NonTag && !Tag)
12940 return false;
12941 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12942 Diag(Target->getLocation(), diag::note_using_decl_target);
12943 Diag((NonTag ? NonTag : Tag)->getLocation(),
12944 diag::note_using_decl_conflict);
12945 BUD->setInvalidDecl();
12946 return true;
12947 }
12948
12949 if (FunctionDecl *FD = Target->getAsFunction()) {
12950 NamedDecl *OldDecl = nullptr;
12951 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12952 /*IsForUsingDecl*/ true)) {
12954 return false;
12955
12957 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12958 break;
12959
12960 // We found a decl with the exact signature.
12962 // If we're in a record, we want to hide the target, so we
12963 // return true (without a diagnostic) to tell the caller not to
12964 // build a shadow decl.
12965 if (CurContext->isRecord())
12966 return true;
12967
12968 // If we're not in a record, this is an error.
12969 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12970 break;
12971 }
12972
12973 Diag(Target->getLocation(), diag::note_using_decl_target);
12974 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12975 BUD->setInvalidDecl();
12976 return true;
12977 }
12978
12979 // Target is not a function.
12980
12981 if (isa<TagDecl>(Target)) {
12982 // No conflict between a tag and a non-tag.
12983 if (!Tag) return false;
12984
12985 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12986 Diag(Target->getLocation(), diag::note_using_decl_target);
12987 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12988 BUD->setInvalidDecl();
12989 return true;
12990 }
12991
12992 // No conflict between a tag and a non-tag.
12993 if (!NonTag) return false;
12994
12995 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12996 Diag(Target->getLocation(), diag::note_using_decl_target);
12997 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12998 BUD->setInvalidDecl();
12999 return true;
13000}
13001
13002/// Determine whether a direct base class is a virtual base class.
13004 if (!Derived->getNumVBases())
13005 return false;
13006 for (auto &B : Derived->bases())
13007 if (B.getType()->getAsCXXRecordDecl() == Base)
13008 return B.isVirtual();
13009 llvm_unreachable("not a direct base class");
13010}
13011
13013 NamedDecl *Orig,
13014 UsingShadowDecl *PrevDecl) {
13015 // If we resolved to another shadow declaration, just coalesce them.
13016 NamedDecl *Target = Orig;
13018 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
13019 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13020 }
13021
13022 NamedDecl *NonTemplateTarget = Target;
13023 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
13024 NonTemplateTarget = TargetTD->getTemplatedDecl();
13025
13026 UsingShadowDecl *Shadow;
13027 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
13028 UsingDecl *Using = cast<UsingDecl>(BUD);
13029 bool IsVirtualBase =
13031 Using->getQualifier().getAsRecordDecl());
13033 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
13034 } else {
13036 Target->getDeclName(), BUD, Target);
13037 }
13038 BUD->addShadowDecl(Shadow);
13039
13040 Shadow->setAccess(BUD->getAccess());
13041 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13042 Shadow->setInvalidDecl();
13043
13044 Shadow->setPreviousDecl(PrevDecl);
13045
13046 if (S)
13047 PushOnScopeChains(Shadow, S);
13048 else
13049 CurContext->addDecl(Shadow);
13050
13051
13052 return Shadow;
13053}
13054
13056 if (Shadow->getDeclName().getNameKind() ==
13058 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
13059
13060 // Remove it from the DeclContext...
13061 Shadow->getDeclContext()->removeDecl(Shadow);
13062
13063 // ...and the scope, if applicable...
13064 if (S) {
13065 S->RemoveDecl(Shadow);
13066 IdResolver.RemoveDecl(Shadow);
13067 }
13068
13069 // ...and the using decl.
13070 Shadow->getIntroducer()->removeShadowDecl(Shadow);
13071
13072 // TODO: complain somehow if Shadow was used. It shouldn't
13073 // be possible for this to happen, because...?
13074}
13075
13076/// Find the base specifier for a base class with the given type.
13078 QualType DesiredBase,
13079 bool &AnyDependentBases) {
13080 // Check whether the named type is a direct base class.
13081 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13082 for (auto &Base : Derived->bases()) {
13083 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13084 if (CanonicalDesiredBase == BaseType)
13085 return &Base;
13086 if (BaseType->isDependentType())
13087 AnyDependentBases = true;
13088 }
13089 return nullptr;
13090}
13091
13092namespace {
13093class UsingValidatorCCC final : public CorrectionCandidateCallback {
13094public:
13095 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13096 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13097 : HasTypenameKeyword(HasTypenameKeyword),
13098 IsInstantiation(IsInstantiation), OldNNS(NNS),
13099 RequireMemberOf(RequireMemberOf) {}
13100
13101 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13102 NamedDecl *ND = Candidate.getCorrectionDecl();
13103
13104 // Keywords are not valid here.
13105 if (!ND || isa<NamespaceDecl>(ND))
13106 return false;
13107
13108 // Completely unqualified names are invalid for a 'using' declaration.
13109 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13110 return false;
13111
13112 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13113 // reject.
13114
13115 if (RequireMemberOf) {
13116 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13117 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13118 // No-one ever wants a using-declaration to name an injected-class-name
13119 // of a base class, unless they're declaring an inheriting constructor.
13120 ASTContext &Ctx = ND->getASTContext();
13121 if (!Ctx.getLangOpts().CPlusPlus11)
13122 return false;
13123 CanQualType FoundType = Ctx.getCanonicalTagType(FoundRecord);
13124
13125 // Check that the injected-class-name is named as a member of its own
13126 // type; we don't want to suggest 'using Derived::Base;', since that
13127 // means something else.
13128 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13129 ? Candidate.getCorrectionSpecifier()
13130 : OldNNS;
13131 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13132 !Ctx.hasSameType(QualType(Specifier.getAsType(), 0), FoundType))
13133 return false;
13134
13135 // Check that this inheriting constructor declaration actually names a
13136 // direct base class of the current class.
13137 bool AnyDependentBases = false;
13138 if (!findDirectBaseWithType(RequireMemberOf,
13139 Ctx.getCanonicalTagType(FoundRecord),
13140 AnyDependentBases) &&
13141 !AnyDependentBases)
13142 return false;
13143 } else {
13144 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
13145 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
13146 return false;
13147
13148 // FIXME: Check that the base class member is accessible?
13149 }
13150 } else {
13151 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
13152 if (FoundRecord && FoundRecord->isInjectedClassName())
13153 return false;
13154 }
13155
13156 if (isa<TypeDecl>(ND))
13157 return HasTypenameKeyword || !IsInstantiation;
13158
13159 return !HasTypenameKeyword;
13160 }
13161
13162 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13163 return std::make_unique<UsingValidatorCCC>(*this);
13164 }
13165
13166private:
13167 bool HasTypenameKeyword;
13168 bool IsInstantiation;
13169 NestedNameSpecifier OldNNS;
13170 CXXRecordDecl *RequireMemberOf;
13171};
13172} // end anonymous namespace
13173
13175 // It is really dumb that we have to do this.
13176 LookupResult::Filter F = Previous.makeFilter();
13177 while (F.hasNext()) {
13178 NamedDecl *D = F.next();
13179 if (!isDeclInScope(D, CurContext, S))
13180 F.erase();
13181 // If we found a local extern declaration that's not ordinarily visible,
13182 // and this declaration is being added to a non-block scope, ignore it.
13183 // We're only checking for scope conflicts here, not also for violations
13184 // of the linkage rules.
13185 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13187 F.erase();
13188 }
13189 F.done();
13190}
13191
13193 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13194 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13195 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13196 const ParsedAttributesView &AttrList, bool IsInstantiation,
13197 bool IsUsingIfExists) {
13198 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13199 SourceLocation IdentLoc = NameInfo.getLoc();
13200 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13201
13202 // FIXME: We ignore attributes for now.
13203
13204 // For an inheriting constructor declaration, the name of the using
13205 // declaration is the name of a constructor in this class, not in the
13206 // base class.
13207 DeclarationNameInfo UsingName = NameInfo;
13209 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
13210 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13211 Context.getCanonicalTagType(RD)));
13212
13213 // Do the redeclaration lookup in the current scope.
13214 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13216 Previous.setHideTags(false);
13217 if (S) {
13218 LookupName(Previous, S);
13219
13221 } else {
13222 assert(IsInstantiation && "no scope in non-instantiation");
13223 if (CurContext->isRecord())
13225 else {
13226 // No redeclaration check is needed here; in non-member contexts we
13227 // diagnosed all possible conflicts with other using-declarations when
13228 // building the template:
13229 //
13230 // For a dependent non-type using declaration, the only valid case is
13231 // if we instantiate to a single enumerator. We check for conflicts
13232 // between shadow declarations we introduce, and we check in the template
13233 // definition for conflicts between a non-type using declaration and any
13234 // other declaration, which together covers all cases.
13235 //
13236 // A dependent typename using declaration will never successfully
13237 // instantiate, since it will always name a class member, so we reject
13238 // that in the template definition.
13239 }
13240 }
13241
13242 // Check for invalid redeclarations.
13243 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13244 SS, IdentLoc, Previous))
13245 return nullptr;
13246
13247 // 'using_if_exists' doesn't make sense on an inherited constructor.
13248 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13250 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
13251 return nullptr;
13252 }
13253
13254 DeclContext *LookupContext = computeDeclContext(SS);
13256 if (!LookupContext || EllipsisLoc.isValid()) {
13257 NamedDecl *D;
13258 // Dependent scope, or an unexpanded pack
13259 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
13260 SS, NameInfo, IdentLoc))
13261 return nullptr;
13262
13263 if (Previous.isSingleResult() &&
13264 Previous.getFoundDecl()->isTemplateParameter())
13265 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());
13266
13267 if (HasTypenameKeyword) {
13268 // FIXME: not all declaration name kinds are legal here
13270 UsingLoc, TypenameLoc,
13271 QualifierLoc,
13272 IdentLoc, NameInfo.getName(),
13273 EllipsisLoc);
13274 } else {
13276 QualifierLoc, NameInfo, EllipsisLoc);
13277 }
13278 D->setAccess(AS);
13279 CurContext->addDecl(D);
13280 ProcessDeclAttributeList(S, D, AttrList);
13281 return D;
13282 }
13283
13284 auto Build = [&](bool Invalid) {
13285 UsingDecl *UD =
13286 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
13287 UsingName, HasTypenameKeyword);
13288 UD->setAccess(AS);
13289 CurContext->addDecl(UD);
13290 ProcessDeclAttributeList(S, UD, AttrList);
13292 return UD;
13293 };
13294 auto BuildInvalid = [&]{ return Build(true); };
13295 auto BuildValid = [&]{ return Build(false); };
13296
13297 if (RequireCompleteDeclContext(SS, LookupContext))
13298 return BuildInvalid();
13299
13300 // Look up the target name.
13301 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13302
13303 // Unlike most lookups, we don't always want to hide tag
13304 // declarations: tag names are visible through the using declaration
13305 // even if hidden by ordinary names, *except* in a dependent context
13306 // where they may be used by two-phase lookup.
13307 if (!IsInstantiation)
13308 R.setHideTags(false);
13309
13310 // For the purposes of this lookup, we have a base object type
13311 // equal to that of the current context.
13312 if (CurContext->isRecord()) {
13313 R.setBaseObjectType(
13314 Context.getCanonicalTagType(cast<CXXRecordDecl>(CurContext)));
13315 }
13316
13317 LookupQualifiedName(R, LookupContext);
13318
13319 // Validate the context, now we have a lookup
13320 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
13321 IdentLoc, &R))
13322 return nullptr;
13323
13324 if (R.empty() && IsUsingIfExists)
13326 UsingName.getName()),
13327 AS_public);
13328
13329 // Try to correct typos if possible. If constructor name lookup finds no
13330 // results, that means the named class has no explicit constructors, and we
13331 // suppressed declaring implicit ones (probably because it's dependent or
13332 // invalid).
13333 if (R.empty() &&
13335 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13336 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13337 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13338 auto *II = NameInfo.getName().getAsIdentifierInfo();
13339 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
13340 CurContext->isStdNamespace() &&
13341 isa<TranslationUnitDecl>(LookupContext) &&
13342 PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&
13343 getSourceManager().isInSystemHeader(UsingLoc))
13344 return nullptr;
13345 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13346 dyn_cast<CXXRecordDecl>(CurContext));
13347 if (TypoCorrection Corrected =
13348 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
13350 // We reject candidates where DroppedSpecifier == true, hence the
13351 // literal '0' below.
13352 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
13353 << NameInfo.getName() << LookupContext << 0
13354 << SS.getRange());
13355
13356 // If we picked a correction with no attached Decl we can't do anything
13357 // useful with it, bail out.
13358 NamedDecl *ND = Corrected.getCorrectionDecl();
13359 if (!ND)
13360 return BuildInvalid();
13361
13362 // If we corrected to an inheriting constructor, handle it as one.
13363 auto *RD = dyn_cast<CXXRecordDecl>(ND);
13364 if (RD && RD->isInjectedClassName()) {
13365 // The parent of the injected class name is the class itself.
13366 RD = cast<CXXRecordDecl>(RD->getParent());
13367
13368 // Fix up the information we'll use to build the using declaration.
13369 if (Corrected.WillReplaceSpecifier()) {
13371 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
13372 QualifierLoc.getSourceRange());
13373 QualifierLoc = Builder.getWithLocInContext(Context);
13374 }
13375
13376 // In this case, the name we introduce is the name of a derived class
13377 // constructor.
13378 auto *CurClass = cast<CXXRecordDecl>(CurContext);
13379 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13380 Context.getCanonicalTagType(CurClass)));
13381 UsingName.setNamedTypeInfo(nullptr);
13382 for (auto *Ctor : LookupConstructors(RD))
13383 R.addDecl(Ctor);
13384 R.resolveKind();
13385 } else {
13386 // FIXME: Pick up all the declarations if we found an overloaded
13387 // function.
13388 UsingName.setName(ND->getDeclName());
13389 R.addDecl(ND);
13390 }
13391 } else {
13392 Diag(IdentLoc, diag::err_no_member)
13393 << NameInfo.getName() << LookupContext << SS.getRange();
13394 return BuildInvalid();
13395 }
13396 }
13397
13398 if (R.isAmbiguous())
13399 return BuildInvalid();
13400
13401 if (HasTypenameKeyword) {
13402 // If we asked for a typename and got a non-type decl, error out.
13403 if (!R.getAsSingle<TypeDecl>() &&
13404 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13405 Diag(IdentLoc, diag::err_using_typename_non_type);
13406 for (const NamedDecl *D : R)
13407 Diag(D->getUnderlyingDecl()->getLocation(),
13408 diag::note_using_decl_target);
13409 return BuildInvalid();
13410 }
13411 } else {
13412 // If we asked for a non-typename and we got a type, error out,
13413 // but only if this is an instantiation of an unresolved using
13414 // decl. Otherwise just silently find the type name.
13415 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13416 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13417 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13418 return BuildInvalid();
13419 }
13420 }
13421
13422 // C++14 [namespace.udecl]p6:
13423 // A using-declaration shall not name a namespace.
13424 if (R.getAsSingle<NamespaceDecl>()) {
13425 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13426 << SS.getRange();
13427 // Suggest using 'using namespace ...' instead.
13428 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
13429 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
13430 return BuildInvalid();
13431 }
13432
13433 UsingDecl *UD = BuildValid();
13434
13435 // Some additional rules apply to inheriting constructors.
13436 if (UsingName.getName().getNameKind() ==
13438 // Suppress access diagnostics; the access check is instead performed at the
13439 // point of use for an inheriting constructor.
13440 R.suppressDiagnostics();
13442 return UD;
13443 }
13444
13445 for (NamedDecl *D : R) {
13446 UsingShadowDecl *PrevDecl = nullptr;
13447 if (!CheckUsingShadowDecl(UD, D, Previous, PrevDecl))
13448 BuildUsingShadowDecl(S, UD, D, PrevDecl);
13449 }
13450
13451 return UD;
13452}
13453
13455 SourceLocation UsingLoc,
13456 SourceLocation EnumLoc,
13457 SourceLocation NameLoc,
13458 TypeSourceInfo *EnumType,
13459 EnumDecl *ED) {
13460 bool Invalid = false;
13461
13462 if (CurContext->getRedeclContext()->isRecord()) {
13463 /// In class scope, check if this is a duplicate, for better a diagnostic.
13464 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13465 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13467
13469
13470 for (NamedDecl *D : Previous)
13471 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13472 if (UED->getEnumDecl() == ED) {
13473 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13474 << SourceRange(EnumLoc, NameLoc);
13475 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13476 Invalid = true;
13477 break;
13478 }
13479 }
13480
13481 if (RequireCompleteEnumDecl(ED, NameLoc))
13482 Invalid = true;
13483
13485 EnumLoc, NameLoc, EnumType);
13486 UD->setAccess(AS);
13487 CurContext->addDecl(UD);
13488
13489 if (Invalid) {
13490 UD->setInvalidDecl();
13491 return UD;
13492 }
13493
13494 // Create the shadow decls for each enumerator
13495 for (EnumConstantDecl *EC : ED->enumerators()) {
13496 UsingShadowDecl *PrevDecl = nullptr;
13497 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13500 LookupName(Previous, S);
13502
13503 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13504 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13505 }
13506
13507 return UD;
13508}
13509
13511 ArrayRef<NamedDecl *> Expansions) {
13512 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13513 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13514 isa<UsingPackDecl>(InstantiatedFrom));
13515
13516 auto *UPD =
13517 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13518 UPD->setAccess(InstantiatedFrom->getAccess());
13519 CurContext->addDecl(UPD);
13520 return UPD;
13521}
13522
13524 assert(!UD->hasTypename() && "expecting a constructor name");
13525
13526 QualType SourceType(UD->getQualifier().getAsType(), 0);
13528
13529 // Check whether the named type is a direct base class.
13530 bool AnyDependentBases = false;
13531 auto *Base =
13532 findDirectBaseWithType(TargetClass, SourceType, AnyDependentBases);
13533 if (!Base && !AnyDependentBases) {
13534 Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base)
13535 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13536 UD->setInvalidDecl();
13537 return true;
13538 }
13539
13540 if (Base)
13541 Base->setInheritConstructors();
13542
13543 return false;
13544}
13545
13547 bool HasTypenameKeyword,
13548 const CXXScopeSpec &SS,
13549 SourceLocation NameLoc,
13550 const LookupResult &Prev) {
13551 NestedNameSpecifier Qual = SS.getScopeRep();
13552
13553 // C++03 [namespace.udecl]p8:
13554 // C++0x [namespace.udecl]p10:
13555 // A using-declaration is a declaration and can therefore be used
13556 // repeatedly where (and only where) multiple declarations are
13557 // allowed.
13558 //
13559 // That's in non-member contexts.
13560 if (!CurContext->getRedeclContext()->isRecord()) {
13561 // A dependent qualifier outside a class can only ever resolve to an
13562 // enumeration type. Therefore it conflicts with any other non-type
13563 // declaration in the same scope.
13564 // FIXME: How should we check for dependent type-type conflicts at block
13565 // scope?
13566 if (Qual.isDependent() && !HasTypenameKeyword) {
13567 for (auto *D : Prev) {
13568 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13569 bool OldCouldBeEnumerator =
13571 Diag(NameLoc,
13572 OldCouldBeEnumerator ? diag::err_redefinition
13573 : diag::err_redefinition_different_kind)
13574 << Prev.getLookupName();
13575 Diag(D->getLocation(), diag::note_previous_definition);
13576 return true;
13577 }
13578 }
13579 }
13580 return false;
13581 }
13582
13583 NestedNameSpecifier CNNS = Qual.getCanonical();
13584 for (const NamedDecl *D : Prev) {
13585 bool DTypename;
13586 NestedNameSpecifier DQual = std::nullopt;
13587 if (const auto *UD = dyn_cast<UsingDecl>(D)) {
13588 DTypename = UD->hasTypename();
13589 DQual = UD->getQualifier();
13590 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13591 DTypename = false;
13592 DQual = UD->getQualifier();
13593 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13594 DTypename = true;
13595 DQual = UD->getQualifier();
13596 } else
13597 continue;
13598
13599 // using decls differ if one says 'typename' and the other doesn't.
13600 // FIXME: non-dependent using decls?
13601 if (HasTypenameKeyword != DTypename) continue;
13602
13603 // using decls differ if they name different scopes (but note that
13604 // template instantiation can cause this check to trigger when it
13605 // didn't before instantiation).
13606 if (CNNS != DQual.getCanonical())
13607 continue;
13608
13609 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13610 Diag(D->getLocation(), diag::note_using_decl) << 1;
13611 return true;
13612 }
13613
13614 return false;
13615}
13616
13617bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13618 const CXXScopeSpec &SS,
13619 const DeclarationNameInfo &NameInfo,
13620 SourceLocation NameLoc,
13621 const LookupResult *R, const UsingDecl *UD) {
13622 DeclContext *NamedContext = computeDeclContext(SS);
13623 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13624 "resolvable context must have exactly one set of decls");
13625
13626 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13627 // relationship.
13628 bool Cxx20Enumerator = false;
13629 if (NamedContext) {
13630 EnumConstantDecl *EC = nullptr;
13631 if (R)
13632 EC = R->getAsSingle<EnumConstantDecl>();
13633 else if (UD && UD->shadow_size() == 1)
13634 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13635 if (EC)
13636 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13637
13638 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13639 // C++14 [namespace.udecl]p7:
13640 // A using-declaration shall not name a scoped enumerator.
13641 // C++20 p1099 permits enumerators.
13642 if (EC && R && ED->isScoped())
13643 Diag(SS.getBeginLoc(),
13645 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13646 : diag::ext_using_decl_scoped_enumerator)
13647 << SS.getRange();
13648
13649 // We want to consider the scope of the enumerator
13650 NamedContext = ED->getDeclContext();
13651 }
13652 }
13653
13654 if (!CurContext->isRecord()) {
13655 // C++03 [namespace.udecl]p3:
13656 // C++0x [namespace.udecl]p8:
13657 // A using-declaration for a class member shall be a member-declaration.
13658 // C++20 [namespace.udecl]p7
13659 // ... other than an enumerator ...
13660
13661 // If we weren't able to compute a valid scope, it might validly be a
13662 // dependent class or enumeration scope. If we have a 'typename' keyword,
13663 // the scope must resolve to a class type.
13664 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13665 : !HasTypename)
13666 return false; // OK
13667
13668 Diag(NameLoc,
13669 Cxx20Enumerator
13670 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13671 : diag::err_using_decl_can_not_refer_to_class_member)
13672 << SS.getRange();
13673
13674 if (Cxx20Enumerator)
13675 return false; // OK
13676
13677 auto *RD = NamedContext
13678 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13679 : nullptr;
13680 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13681 // See if there's a helpful fixit
13682
13683 if (!R) {
13684 // We will have already diagnosed the problem on the template
13685 // definition, Maybe we should do so again?
13686 } else if (R->getAsSingle<TypeDecl>()) {
13687 if (getLangOpts().CPlusPlus11) {
13688 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13689 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13690 << diag::MemClassWorkaround::AliasDecl
13692 NameInfo.getName().getAsString() +
13693 " = ");
13694 } else {
13695 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13696 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13697 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13698 << diag::MemClassWorkaround::TypedefDecl
13699 << FixItHint::CreateReplacement(UsingLoc, "typedef")
13701 InsertLoc, " " + NameInfo.getName().getAsString());
13702 }
13703 } else if (R->getAsSingle<VarDecl>()) {
13704 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13705 // repeating the type of the static data member here.
13706 FixItHint FixIt;
13707 if (getLangOpts().CPlusPlus11) {
13708 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13710 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13711 }
13712
13713 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13714 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13715 } else if (R->getAsSingle<EnumConstantDecl>()) {
13716 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13717 // repeating the type of the enumeration here, and we can't do so if
13718 // the type is anonymous.
13719 FixItHint FixIt;
13720 if (getLangOpts().CPlusPlus11) {
13721 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13723 UsingLoc,
13724 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13725 }
13726
13727 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13728 << (getLangOpts().CPlusPlus11
13729 ? diag::MemClassWorkaround::ConstexprVar
13730 : diag::MemClassWorkaround::ConstVar)
13731 << FixIt;
13732 }
13733 }
13734
13735 return true; // Fail
13736 }
13737
13738 // If the named context is dependent, we can't decide much.
13739 if (!NamedContext) {
13740 // FIXME: in C++0x, we can diagnose if we can prove that the
13741 // nested-name-specifier does not refer to a base class, which is
13742 // still possible in some cases.
13743
13744 // Otherwise we have to conservatively report that things might be
13745 // okay.
13746 return false;
13747 }
13748
13749 // The current scope is a record.
13750 if (!NamedContext->isRecord()) {
13751 // Ideally this would point at the last name in the specifier,
13752 // but we don't have that level of source info.
13753 Diag(SS.getBeginLoc(),
13754 Cxx20Enumerator
13755 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13756 : diag::err_using_decl_nested_name_specifier_is_not_class)
13757 << SS.getScopeRep() << SS.getRange();
13758
13759 if (Cxx20Enumerator)
13760 return false; // OK
13761
13762 return true;
13763 }
13764
13765 if (!NamedContext->isDependentContext() &&
13766 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13767 return true;
13768
13769 // C++26 [namespace.udecl]p3:
13770 // In a using-declaration used as a member-declaration, each
13771 // using-declarator shall either name an enumerator or have a
13772 // nested-name-specifier naming a base class of the current class
13773 // ([expr.prim.this]). ...
13774 // "have a nested-name-specifier naming a base class of the current class"
13775 // was introduced by CWG400.
13776
13779
13780 if (Cxx20Enumerator) {
13781 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13782 << SS.getScopeRep() << SS.getRange();
13783 return false;
13784 }
13785
13786 if (CurContext == NamedContext) {
13787 Diag(SS.getBeginLoc(),
13788 diag::err_using_decl_nested_name_specifier_is_current_class)
13789 << SS.getRange();
13790 return true;
13791 }
13792
13793 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13794 Diag(SS.getBeginLoc(),
13795 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13797 << SS.getRange();
13798 }
13799 return true;
13800 }
13801
13802 return false;
13803}
13804
13806 MultiTemplateParamsArg TemplateParamLists,
13807 SourceLocation UsingLoc, UnqualifiedId &Name,
13808 const ParsedAttributesView &AttrList,
13809 TypeResult Type, Decl *DeclFromDeclSpec) {
13810
13811 if (Type.isInvalid())
13812 return nullptr;
13813
13814 bool Invalid = false;
13816 TypeSourceInfo *TInfo = nullptr;
13817 GetTypeFromParser(Type.get(), &TInfo);
13818
13819 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13820 return nullptr;
13821
13824 Invalid = true;
13825 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13826 TInfo->getTypeLoc().getBeginLoc());
13827 }
13828
13829 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13830 TemplateParamLists.size()
13833 LookupName(Previous, S);
13834
13835 // Warn about shadowing the name of a template parameter.
13836 if (Previous.isSingleResult() &&
13837 Previous.getFoundDecl()->isTemplateParameter()) {
13839 Previous.clear();
13840 }
13841
13842 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13843 "name in alias declaration must be an identifier");
13845 Name.StartLocation,
13846 Name.Identifier, TInfo);
13847
13848 NewTD->setAccess(AS);
13849
13850 if (Invalid)
13851 NewTD->setInvalidDecl();
13852
13853 ProcessDeclAttributeList(S, NewTD, AttrList);
13854 AddPragmaAttributes(S, NewTD);
13855 ProcessAPINotes(NewTD);
13856
13858 Invalid |= NewTD->isInvalidDecl();
13859
13860 // Get the innermost enclosing declaration scope.
13861 S = S->getDeclParent();
13862
13863 bool Redeclaration = false;
13864
13865 NamedDecl *NewND;
13866 if (TemplateParamLists.size()) {
13867 TypeAliasTemplateDecl *OldDecl = nullptr;
13868 TemplateParameterList *OldTemplateParams = nullptr;
13869
13870 if (TemplateParamLists.size() != 1) {
13871 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13872 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13873 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13874 Invalid = true;
13875 }
13876 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13877
13878 // Check that we can declare a template here.
13879 if (CheckTemplateDeclScope(S, TemplateParams))
13880 return nullptr;
13881
13882 // Only consider previous declarations in the same scope.
13883 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13884 /*ExplicitInstantiationOrSpecialization*/false);
13885 if (!Previous.empty()) {
13886 Redeclaration = true;
13887
13888 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13889 if (!OldDecl && !Invalid) {
13890 Diag(UsingLoc, diag::err_redefinition_different_kind)
13891 << Name.Identifier;
13892
13893 NamedDecl *OldD = Previous.getRepresentativeDecl();
13894 if (OldD->getLocation().isValid())
13895 Diag(OldD->getLocation(), diag::note_previous_definition);
13896
13897 Invalid = true;
13898 }
13899
13900 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13901 if (TemplateParameterListsAreEqual(TemplateParams,
13902 OldDecl->getTemplateParameters(),
13903 /*Complain=*/true,
13905 OldTemplateParams =
13907 else
13908 Invalid = true;
13909
13910 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13911 if (!Invalid &&
13912 !Context.hasSameType(OldTD->getUnderlyingType(),
13913 NewTD->getUnderlyingType())) {
13914 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13915 // but we can't reasonably accept it.
13916 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13917 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13918 if (OldTD->getLocation().isValid())
13919 Diag(OldTD->getLocation(), diag::note_previous_definition);
13920 Invalid = true;
13921 }
13922 }
13923 }
13924
13925 // Merge any previous default template arguments into our parameters,
13926 // and check the parameter list.
13927 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13928 TPC_Other))
13929 return nullptr;
13930
13931 TypeAliasTemplateDecl *NewDecl =
13933 Name.Identifier, TemplateParams,
13934 NewTD);
13935 NewTD->setDescribedAliasTemplate(NewDecl);
13936
13937 NewDecl->setAccess(AS);
13938
13939 if (Invalid)
13940 NewDecl->setInvalidDecl();
13941 else if (OldDecl) {
13942 NewDecl->setPreviousDecl(OldDecl);
13943 CheckRedeclarationInModule(NewDecl, OldDecl);
13944 }
13945
13946 NewND = NewDecl;
13947 } else {
13948 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13950 handleTagNumbering(TD, S);
13951 }
13953 NewND = NewTD;
13954 }
13955
13956 PushOnScopeChains(NewND, S);
13957 ActOnDocumentableDecl(NewND);
13958 return NewND;
13959}
13960
13962 SourceLocation AliasLoc,
13963 IdentifierInfo *Alias, CXXScopeSpec &SS,
13964 SourceLocation IdentLoc,
13965 IdentifierInfo *Ident) {
13966
13967 // Lookup the namespace name.
13968 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13969 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
13970
13971 if (R.isAmbiguous())
13972 return nullptr;
13973
13974 if (R.empty()) {
13975 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13976 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13977 return nullptr;
13978 }
13979 }
13980 assert(!R.isAmbiguous() && !R.empty());
13981 auto *ND = cast<NamespaceBaseDecl>(R.getRepresentativeDecl());
13982
13983 // Check if we have a previous declaration with the same name.
13984 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13986 LookupName(PrevR, S);
13987
13988 // Check we're not shadowing a template parameter.
13989 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13991 PrevR.clear();
13992 }
13993
13994 // Filter out any other lookup result from an enclosing scope.
13995 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13996 /*AllowInlineNamespace*/false);
13997
13998 // Find the previous declaration and check that we can redeclare it.
13999 NamespaceAliasDecl *Prev = nullptr;
14000 if (PrevR.isSingleResult()) {
14001 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14002 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
14003 // We already have an alias with the same name that points to the same
14004 // namespace; check that it matches.
14005 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
14006 Prev = AD;
14007 } else if (isVisible(PrevDecl)) {
14008 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
14009 << Alias;
14010 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
14011 << AD->getNamespace();
14012 return nullptr;
14013 }
14014 } else if (isVisible(PrevDecl)) {
14015 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
14016 ? diag::err_redefinition
14017 : diag::err_redefinition_different_kind;
14018 Diag(AliasLoc, DiagID) << Alias;
14019 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14020 return nullptr;
14021 }
14022 }
14023
14024 // The use of a nested name specifier may trigger deprecation warnings.
14025 DiagnoseUseOfDecl(ND, IdentLoc);
14026
14028 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
14029 Alias, SS.getWithLocInContext(Context),
14030 IdentLoc, ND);
14031 if (Prev)
14032 AliasDecl->setPreviousDecl(Prev);
14033
14035 return AliasDecl;
14036}
14037
14038namespace {
14039struct SpecialMemberExceptionSpecInfo
14040 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14041 SourceLocation Loc;
14043
14044 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14047 SourceLocation Loc)
14048 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14049
14050 bool visitBase(CXXBaseSpecifier *Base);
14051 bool visitField(FieldDecl *FD);
14052
14053 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14054 unsigned Quals);
14055
14056 void visitSubobjectCall(Subobject Subobj,
14058};
14059}
14060
14061bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14062 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14063 if (!BaseClass)
14064 return false;
14065
14066 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
14067 if (auto *BaseCtor = SMOR.getMethod()) {
14068 visitSubobjectCall(Base, BaseCtor);
14069 return false;
14070 }
14071
14072 visitClassSubobject(BaseClass, Base, 0);
14073 return false;
14074}
14075
14076bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14077 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14078 FD->hasInClassInitializer()) {
14079 Expr *E = FD->getInClassInitializer();
14080 if (!E)
14081 // FIXME: It's a little wasteful to build and throw away a
14082 // CXXDefaultInitExpr here.
14083 // FIXME: We should have a single context note pointing at Loc, and
14084 // this location should be MD->getLocation() instead, since that's
14085 // the location where we actually use the default init expression.
14086 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
14087 if (E)
14088 ExceptSpec.CalledExpr(E);
14089 } else if (auto *RD = S.Context.getBaseElementType(FD->getType())
14090 ->getAsCXXRecordDecl()) {
14091 visitClassSubobject(RD, FD, FD->getType().getCVRQualifiers());
14092 }
14093 return false;
14094}
14095
14096void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14097 Subobject Subobj,
14098 unsigned Quals) {
14099 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14100 bool IsMutable = Field && Field->isMutable();
14101 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
14102}
14103
14104void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14105 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14106 // Note, if lookup fails, it doesn't matter what exception specification we
14107 // choose because the special member will be deleted.
14108 if (CXXMethodDecl *MD = SMOR.getMethod())
14109 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
14110}
14111
14113 llvm::APSInt Result;
14115 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);
14116 ExplicitSpec.setExpr(Converted.get());
14117 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14118 ExplicitSpec.setKind(Result.getBoolValue()
14121 return true;
14122 }
14124 return false;
14125}
14126
14129 if (!ExplicitExpr->isTypeDependent())
14131 return ES;
14132}
14133
14138 ComputingExceptionSpec CES(S, MD, Loc);
14139
14140 CXXRecordDecl *ClassDecl = MD->getParent();
14141
14142 // C++ [except.spec]p14:
14143 // An implicitly declared special member function (Clause 12) shall have an
14144 // exception-specification. [...]
14145 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14146 if (ClassDecl->isInvalidDecl())
14147 return Info.ExceptSpec;
14148
14149 // FIXME: If this diagnostic fires, we're probably missing a check for
14150 // attempting to resolve an exception specification before it's known
14151 // at a higher level.
14152 if (S.RequireCompleteType(MD->getLocation(),
14153 S.Context.getCanonicalTagType(ClassDecl),
14154 diag::err_exception_spec_incomplete_type))
14155 return Info.ExceptSpec;
14156
14157 // C++1z [except.spec]p7:
14158 // [Look for exceptions thrown by] a constructor selected [...] to
14159 // initialize a potentially constructed subobject,
14160 // C++1z [except.spec]p8:
14161 // The exception specification for an implicitly-declared destructor, or a
14162 // destructor without a noexcept-specifier, is potentially-throwing if and
14163 // only if any of the destructors for any of its potentially constructed
14164 // subojects is potentially throwing.
14165 // FIXME: We respect the first rule but ignore the "potentially constructed"
14166 // in the second rule to resolve a core issue (no number yet) that would have
14167 // us reject:
14168 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14169 // struct B : A {};
14170 // struct C : B { void f(); };
14171 // ... due to giving B::~B() a non-throwing exception specification.
14172 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14173 : Info.VisitAllBases);
14174
14175 return Info.ExceptSpec;
14176}
14177
14178namespace {
14179/// RAII object to register a special member as being currently declared.
14180struct DeclaringSpecialMember {
14181 Sema &S;
14183 Sema::ContextRAII SavedContext;
14184 bool WasAlreadyBeingDeclared;
14185
14186 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14187 : S(S), D(RD, CSM), SavedContext(S, RD) {
14188 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
14189 if (WasAlreadyBeingDeclared)
14190 // This almost never happens, but if it does, ensure that our cache
14191 // doesn't contain a stale result.
14192 S.SpecialMemberCache.clear();
14193 else {
14194 // Register a note to be produced if we encounter an error while
14195 // declaring the special member.
14196 Sema::CodeSynthesisContext Ctx;
14197 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14198 // FIXME: We don't have a location to use here. Using the class's
14199 // location maintains the fiction that we declare all special members
14200 // with the class, but (1) it's not clear that lying about that helps our
14201 // users understand what's going on, and (2) there may be outer contexts
14202 // on the stack (some of which are relevant) and printing them exposes
14203 // our lies.
14204 Ctx.PointOfInstantiation = RD->getLocation();
14205 Ctx.Entity = RD;
14206 Ctx.SpecialMember = CSM;
14207 S.pushCodeSynthesisContext(Ctx);
14208 }
14209 }
14210 ~DeclaringSpecialMember() {
14211 if (!WasAlreadyBeingDeclared) {
14212 S.SpecialMembersBeingDeclared.erase(D);
14214 }
14215 }
14216
14217 /// Are we already trying to declare this special member?
14218 bool isAlreadyBeingDeclared() const {
14219 return WasAlreadyBeingDeclared;
14220 }
14221};
14222}
14223
14225 // Look up any existing declarations, but don't trigger declaration of all
14226 // implicit special members with this name.
14227 DeclarationName Name = FD->getDeclName();
14230 for (auto *D : FD->getParent()->lookup(Name))
14231 if (auto *Acceptable = R.getAcceptableDecl(D))
14232 R.addDecl(Acceptable);
14233 R.resolveKind();
14234 R.suppressDiagnostics();
14235
14236 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
14238}
14239
14240void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14241 QualType ResultTy,
14242 ArrayRef<QualType> Args) {
14243 // Build an exception specification pointing back at this constructor.
14245
14246 LangAS AS = getDefaultCXXMethodAddrSpace();
14247 if (AS != LangAS::Default) {
14248 EPI.TypeQuals.addAddressSpace(AS);
14249 }
14250
14251 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14252 SpecialMem->setType(QT);
14253
14254 // During template instantiation of implicit special member functions we need
14255 // a reliable TypeSourceInfo for the function prototype in order to allow
14256 // functions to be substituted.
14257 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {
14258 TypeSourceInfo *TSI =
14259 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
14260 SpecialMem->setTypeSourceInfo(TSI);
14261 }
14262}
14263
14265 CXXRecordDecl *ClassDecl) {
14266 // C++ [class.ctor]p5:
14267 // A default constructor for a class X is a constructor of class X
14268 // that can be called without an argument. If there is no
14269 // user-declared constructor for class X, a default constructor is
14270 // implicitly declared. An implicitly-declared default constructor
14271 // is an inline public member of its class.
14272 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14273 "Should not build implicit default constructor!");
14274
14275 DeclaringSpecialMember DSM(*this, ClassDecl,
14277 if (DSM.isAlreadyBeingDeclared())
14278 return nullptr;
14279
14281 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
14282
14283 // Create the actual constructor declaration.
14284 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14285 SourceLocation ClassLoc = ClassDecl->getLocation();
14286 DeclarationName Name
14287 = Context.DeclarationNames.getCXXConstructorName(ClassType);
14288 DeclarationNameInfo NameInfo(Name, ClassLoc);
14290 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
14291 /*TInfo=*/nullptr, ExplicitSpecifier(),
14292 getCurFPFeatures().isFPConstrained(),
14293 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14296 DefaultCon->setAccess(AS_public);
14297 DefaultCon->setDefaulted();
14298
14299 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});
14300
14301 if (getLangOpts().CUDA)
14302 CUDA().inferTargetForImplicitSpecialMember(
14303 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
14304 /* ConstRHS */ false,
14305 /* Diagnose */ false);
14306
14307 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14308 // constructors is easy to compute.
14309 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14310
14311 // Note that we have declared this constructor.
14312 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14313
14314 Scope *S = getScopeForContext(ClassDecl);
14316
14317 if (ShouldDeleteSpecialMember(DefaultCon,
14319 SetDeclDeleted(DefaultCon, ClassLoc);
14320
14321 if (S)
14322 PushOnScopeChains(DefaultCon, S, false);
14323 ClassDecl->addDecl(DefaultCon);
14324
14325 return DefaultCon;
14326}
14327
14330 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14331 !Constructor->doesThisDeclarationHaveABody() &&
14332 !Constructor->isDeleted()) &&
14333 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14334 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14335 return;
14336
14337 CXXRecordDecl *ClassDecl = Constructor->getParent();
14338 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14339 if (ClassDecl->isInvalidDecl()) {
14340 return;
14341 }
14342
14344
14345 // The exception specification is needed because we are defining the
14346 // function.
14347 ResolveExceptionSpec(CurrentLocation,
14348 Constructor->getType()->castAs<FunctionProtoType>());
14349 MarkVTableUsed(CurrentLocation, ClassDecl);
14350
14351 // Add a context note for diagnostics produced after this point.
14352 Scope.addContextNote(CurrentLocation);
14353
14354 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14355 Constructor->setInvalidDecl();
14356 return;
14357 }
14358
14359 SourceLocation Loc = Constructor->getEndLoc().isValid()
14360 ? Constructor->getEndLoc()
14361 : Constructor->getLocation();
14362 Constructor->setBody(new (Context) CompoundStmt(Loc));
14363 Constructor->markUsed(Context);
14364
14366 L->CompletedImplicitDefinition(Constructor);
14367 }
14368
14369 DiagnoseUninitializedFields(*this, Constructor);
14370}
14371
14373 // Perform any delayed checks on exception specifications.
14375}
14376
14377/// Find or create the fake constructor we synthesize to model constructing an
14378/// object of a derived class via a constructor of a base class.
14381 CXXConstructorDecl *BaseCtor,
14383 CXXRecordDecl *Derived = Shadow->getParent();
14384 SourceLocation UsingLoc = Shadow->getLocation();
14385
14386 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14387 // For now we use the name of the base class constructor as a member of the
14388 // derived class to indicate a (fake) inherited constructor name.
14389 DeclarationName Name = BaseCtor->getDeclName();
14390
14391 // Check to see if we already have a fake constructor for this inherited
14392 // constructor call.
14393 for (NamedDecl *Ctor : Derived->lookup(Name))
14395 ->getInheritedConstructor()
14396 .getConstructor(),
14397 BaseCtor))
14398 return cast<CXXConstructorDecl>(Ctor);
14399
14400 DeclarationNameInfo NameInfo(Name, UsingLoc);
14401 TypeSourceInfo *TInfo =
14402 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14403 FunctionProtoTypeLoc ProtoLoc =
14405
14406 // Check the inherited constructor is valid and find the list of base classes
14407 // from which it was inherited.
14408 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14409
14410 bool Constexpr = BaseCtor->isConstexpr() &&
14413 false, BaseCtor, &ICI);
14414
14416 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14417 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14418 /*isInline=*/true,
14419 /*isImplicitlyDeclared=*/true,
14421 InheritedConstructor(Shadow, BaseCtor),
14422 BaseCtor->getTrailingRequiresClause());
14423 if (Shadow->isInvalidDecl())
14424 DerivedCtor->setInvalidDecl();
14425
14426 // Build an unevaluated exception specification for this fake constructor.
14427 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14430 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14431 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14432 FPT->getParamTypes(), EPI));
14433
14434 // Build the parameter declarations.
14436 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14437 TypeSourceInfo *TInfo =
14438 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14440 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14441 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14442 PD->setScopeInfo(0, I);
14443 PD->setImplicit();
14444 // Ensure attributes are propagated onto parameters (this matters for
14445 // format, pass_object_size, ...).
14446 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14447 ParamDecls.push_back(PD);
14448 ProtoLoc.setParam(I, PD);
14449 }
14450
14451 // Set up the new constructor.
14452 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14453 DerivedCtor->setAccess(BaseCtor->getAccess());
14454 DerivedCtor->setParams(ParamDecls);
14455 Derived->addDecl(DerivedCtor);
14456
14457 if (ShouldDeleteSpecialMember(DerivedCtor,
14459 SetDeclDeleted(DerivedCtor, UsingLoc);
14460
14461 return DerivedCtor;
14462}
14463
14471
14474 CXXRecordDecl *ClassDecl = Constructor->getParent();
14475 assert(Constructor->getInheritedConstructor() &&
14476 !Constructor->doesThisDeclarationHaveABody() &&
14477 !Constructor->isDeleted());
14478 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14479 return;
14480
14481 // Initializations are performed "as if by a defaulted default constructor",
14482 // so enter the appropriate scope.
14484
14485 // The exception specification is needed because we are defining the
14486 // function.
14487 ResolveExceptionSpec(CurrentLocation,
14488 Constructor->getType()->castAs<FunctionProtoType>());
14489 MarkVTableUsed(CurrentLocation, ClassDecl);
14490
14491 // Add a context note for diagnostics produced after this point.
14492 Scope.addContextNote(CurrentLocation);
14493
14495 Constructor->getInheritedConstructor().getShadowDecl();
14496 CXXConstructorDecl *InheritedCtor =
14497 Constructor->getInheritedConstructor().getConstructor();
14498
14499 // [class.inhctor.init]p1:
14500 // initialization proceeds as if a defaulted default constructor is used to
14501 // initialize the D object and each base class subobject from which the
14502 // constructor was inherited
14503
14504 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14505 CXXRecordDecl *RD = Shadow->getParent();
14506 SourceLocation InitLoc = Shadow->getLocation();
14507
14508 // Build explicit initializers for all base classes from which the
14509 // constructor was inherited.
14511 for (bool VBase : {false, true}) {
14512 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14513 if (B.isVirtual() != VBase)
14514 continue;
14515
14516 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14517 if (!BaseRD)
14518 continue;
14519
14520 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14521 if (!BaseCtor.first)
14522 continue;
14523
14524 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14526 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14527
14528 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14529 Inits.push_back(new (Context) CXXCtorInitializer(
14530 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14531 SourceLocation()));
14532 }
14533 }
14534
14535 // We now proceed as if for a defaulted default constructor, with the relevant
14536 // initializers replaced.
14537
14538 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14539 Constructor->setInvalidDecl();
14540 return;
14541 }
14542
14543 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14544 Constructor->markUsed(Context);
14545
14547 L->CompletedImplicitDefinition(Constructor);
14548 }
14549
14550 DiagnoseUninitializedFields(*this, Constructor);
14551}
14552
14554 // C++ [class.dtor]p2:
14555 // If a class has no user-declared destructor, a destructor is
14556 // declared implicitly. An implicitly-declared destructor is an
14557 // inline public member of its class.
14558 assert(ClassDecl->needsImplicitDestructor());
14559
14560 DeclaringSpecialMember DSM(*this, ClassDecl,
14562 if (DSM.isAlreadyBeingDeclared())
14563 return nullptr;
14564
14566 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14567
14568 // Create the actual destructor declaration.
14569 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);
14570 SourceLocation ClassLoc = ClassDecl->getLocation();
14571 DeclarationName Name
14572 = Context.DeclarationNames.getCXXDestructorName(ClassType);
14573 DeclarationNameInfo NameInfo(Name, ClassLoc);
14575 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14576 getCurFPFeatures().isFPConstrained(),
14577 /*isInline=*/true,
14578 /*isImplicitlyDeclared=*/true,
14581 Destructor->setAccess(AS_public);
14582 Destructor->setDefaulted();
14583
14584 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});
14585
14586 if (getLangOpts().CUDA)
14587 CUDA().inferTargetForImplicitSpecialMember(
14589 /* ConstRHS */ false,
14590 /* Diagnose */ false);
14591
14592 // We don't need to use SpecialMemberIsTrivial here; triviality for
14593 // destructors is easy to compute.
14594 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14595 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14596 ClassDecl->hasTrivialDestructorForCall());
14597
14598 // Note that we have declared this destructor.
14599 ++getASTContext().NumImplicitDestructorsDeclared;
14600
14601 Scope *S = getScopeForContext(ClassDecl);
14603
14604 // We can't check whether an implicit destructor is deleted before we complete
14605 // the definition of the class, because its validity depends on the alignment
14606 // of the class. We'll check this from ActOnFields once the class is complete.
14607 if (ClassDecl->isCompleteDefinition() &&
14609 SetDeclDeleted(Destructor, ClassLoc);
14610
14611 // Introduce this destructor into its scope.
14612 if (S)
14613 PushOnScopeChains(Destructor, S, false);
14614 ClassDecl->addDecl(Destructor);
14615
14616 return Destructor;
14617}
14618
14621 assert((Destructor->isDefaulted() &&
14622 !Destructor->doesThisDeclarationHaveABody() &&
14623 !Destructor->isDeleted()) &&
14624 "DefineImplicitDestructor - call it for implicit default dtor");
14625 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14626 return;
14627
14628 CXXRecordDecl *ClassDecl = Destructor->getParent();
14629 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14630
14632
14633 // The exception specification is needed because we are defining the
14634 // function.
14635 ResolveExceptionSpec(CurrentLocation,
14636 Destructor->getType()->castAs<FunctionProtoType>());
14637 MarkVTableUsed(CurrentLocation, ClassDecl);
14638
14639 // Add a context note for diagnostics produced after this point.
14640 Scope.addContextNote(CurrentLocation);
14641
14643 Destructor->getParent());
14644
14646 Destructor->setInvalidDecl();
14647 return;
14648 }
14649
14650 SourceLocation Loc = Destructor->getEndLoc().isValid()
14651 ? Destructor->getEndLoc()
14652 : Destructor->getLocation();
14653 Destructor->setBody(new (Context) CompoundStmt(Loc));
14654 Destructor->markUsed(Context);
14655
14657 L->CompletedImplicitDefinition(Destructor);
14658 }
14659}
14660
14663 if (Destructor->isInvalidDecl())
14664 return;
14665
14666 CXXRecordDecl *ClassDecl = Destructor->getParent();
14667 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14668 "implicit complete dtors unneeded outside MS ABI");
14669 assert(ClassDecl->getNumVBases() > 0 &&
14670 "complete dtor only exists for classes with vbases");
14671
14673
14674 // Add a context note for diagnostics produced after this point.
14675 Scope.addContextNote(CurrentLocation);
14676
14677 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14678}
14679
14681 // If the context is an invalid C++ class, just suppress these checks.
14682 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14683 if (Record->isInvalidDecl()) {
14686 return;
14687 }
14689 }
14690}
14691
14694
14695 if (!DelayedDllExportMemberFunctions.empty()) {
14697 std::swap(DelayedDllExportMemberFunctions, WorkList);
14698 for (CXXMethodDecl *M : WorkList) {
14699 DefineDefaultedFunction(*this, M, M->getLocation());
14700
14701 // Pass the method to the consumer to get emitted. This is not necessary
14702 // for explicit instantiation definitions, as they will get emitted
14703 // anyway.
14704 if (M->getParent()->getTemplateSpecializationKind() !=
14707 }
14708 }
14709}
14710
14712 if (!DelayedDllExportClasses.empty()) {
14713 // Calling ReferenceDllExportedMembers might cause the current function to
14714 // be called again, so use a local copy of DelayedDllExportClasses.
14716 std::swap(DelayedDllExportClasses, WorkList);
14717 for (CXXRecordDecl *Class : WorkList)
14719 }
14720}
14721
14723 assert(getLangOpts().CPlusPlus11 &&
14724 "adjusting dtor exception specs was introduced in c++11");
14725
14726 if (Destructor->isDependentContext())
14727 return;
14728
14729 // C++11 [class.dtor]p3:
14730 // A declaration of a destructor that does not have an exception-
14731 // specification is implicitly considered to have the same exception-
14732 // specification as an implicit declaration.
14733 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14734 if (DtorType->hasExceptionSpec())
14735 return;
14736
14737 // Replace the destructor's type, building off the existing one. Fortunately,
14738 // the only thing of interest in the destructor type is its extended info.
14739 // The return and arguments are fixed.
14740 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14743 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));
14744
14745 // FIXME: If the destructor has a body that could throw, and the newly created
14746 // spec doesn't allow exceptions, we should emit a warning, because this
14747 // change in behavior can break conforming C++03 programs at runtime.
14748 // However, we don't have a body or an exception specification yet, so it
14749 // needs to be done somewhere else.
14750}
14751
14752namespace {
14753/// An abstract base class for all helper classes used in building the
14754// copy/move operators. These classes serve as factory functions and help us
14755// avoid using the same Expr* in the AST twice.
14756class ExprBuilder {
14757 ExprBuilder(const ExprBuilder&) = delete;
14758 ExprBuilder &operator=(const ExprBuilder&) = delete;
14759
14760protected:
14761 static Expr *assertNotNull(Expr *E) {
14762 assert(E && "Expression construction must not fail.");
14763 return E;
14764 }
14765
14766public:
14767 ExprBuilder() {}
14768 virtual ~ExprBuilder() {}
14769
14770 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14771};
14772
14773class RefBuilder: public ExprBuilder {
14774 VarDecl *Var;
14775 QualType VarType;
14776
14777public:
14778 Expr *build(Sema &S, SourceLocation Loc) const override {
14779 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14780 }
14781
14782 RefBuilder(VarDecl *Var, QualType VarType)
14783 : Var(Var), VarType(VarType) {}
14784};
14785
14786class ThisBuilder: public ExprBuilder {
14787public:
14788 Expr *build(Sema &S, SourceLocation Loc) const override {
14789 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14790 }
14791};
14792
14793class CastBuilder: public ExprBuilder {
14794 const ExprBuilder &Builder;
14795 QualType Type;
14797 const CXXCastPath &Path;
14798
14799public:
14800 Expr *build(Sema &S, SourceLocation Loc) const override {
14801 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14802 CK_UncheckedDerivedToBase, Kind,
14803 &Path).get());
14804 }
14805
14806 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14807 const CXXCastPath &Path)
14808 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14809};
14810
14811class DerefBuilder: public ExprBuilder {
14812 const ExprBuilder &Builder;
14813
14814public:
14815 Expr *build(Sema &S, SourceLocation Loc) const override {
14816 return assertNotNull(
14817 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14818 }
14819
14820 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14821};
14822
14823class MemberBuilder: public ExprBuilder {
14824 const ExprBuilder &Builder;
14825 QualType Type;
14826 CXXScopeSpec SS;
14827 bool IsArrow;
14828 LookupResult &MemberLookup;
14829
14830public:
14831 Expr *build(Sema &S, SourceLocation Loc) const override {
14832 return assertNotNull(S.BuildMemberReferenceExpr(
14833 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14834 nullptr, MemberLookup, nullptr, nullptr).get());
14835 }
14836
14837 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14838 LookupResult &MemberLookup)
14839 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14840 MemberLookup(MemberLookup) {}
14841};
14842
14843class MoveCastBuilder: public ExprBuilder {
14844 const ExprBuilder &Builder;
14845
14846public:
14847 Expr *build(Sema &S, SourceLocation Loc) const override {
14848 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14849 }
14850
14851 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14852};
14853
14854class LvalueConvBuilder: public ExprBuilder {
14855 const ExprBuilder &Builder;
14856
14857public:
14858 Expr *build(Sema &S, SourceLocation Loc) const override {
14859 return assertNotNull(
14860 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14861 }
14862
14863 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14864};
14865
14866class SubscriptBuilder: public ExprBuilder {
14867 const ExprBuilder &Base;
14868 const ExprBuilder &Index;
14869
14870public:
14871 Expr *build(Sema &S, SourceLocation Loc) const override {
14872 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14873 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14874 }
14875
14876 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14877 : Base(Base), Index(Index) {}
14878};
14879
14880} // end anonymous namespace
14881
14882/// When generating a defaulted copy or move assignment operator, if a field
14883/// should be copied with __builtin_memcpy rather than via explicit assignments,
14884/// do so. This optimization only applies for arrays of scalars, and for arrays
14885/// of class type where the selected copy/move-assignment operator is trivial.
14886static StmtResult
14888 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14889 // Compute the size of the memory buffer to be copied.
14890 QualType SizeType = S.Context.getSizeType();
14891 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14893
14894 // Take the address of the field references for "from" and "to". We
14895 // directly construct UnaryOperators here because semantic analysis
14896 // does not permit us to take the address of an xvalue.
14897 Expr *From = FromB.build(S, Loc);
14898 From = UnaryOperator::Create(
14899 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14900 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14901 Expr *To = ToB.build(S, Loc);
14903 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14904 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14905
14906 bool NeedsCollectableMemCpy = false;
14907 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14908 NeedsCollectableMemCpy = RD->hasObjectMember();
14909
14910 // Create a reference to the __builtin_objc_memmove_collectable function
14911 StringRef MemCpyName = NeedsCollectableMemCpy ?
14912 "__builtin_objc_memmove_collectable" :
14913 "__builtin_memcpy";
14914 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14916 S.LookupName(R, S.TUScope, true);
14917
14918 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14919 if (!MemCpy)
14920 // Something went horribly wrong earlier, and we will have complained
14921 // about it.
14922 return StmtError();
14923
14924 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14925 VK_PRValue, Loc, nullptr);
14926 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14927
14928 Expr *CallArgs[] = {
14929 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14930 };
14931 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14932 Loc, CallArgs, Loc);
14933
14934 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14935 return Call.getAs<Stmt>();
14936}
14937
14938/// Builds a statement that copies/moves the given entity from \p From to
14939/// \c To.
14940///
14941/// This routine is used to copy/move the members of a class with an
14942/// implicitly-declared copy/move assignment operator. When the entities being
14943/// copied are arrays, this routine builds for loops to copy them.
14944///
14945/// \param S The Sema object used for type-checking.
14946///
14947/// \param Loc The location where the implicit copy/move is being generated.
14948///
14949/// \param T The type of the expressions being copied/moved. Both expressions
14950/// must have this type.
14951///
14952/// \param To The expression we are copying/moving to.
14953///
14954/// \param From The expression we are copying/moving from.
14955///
14956/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14957/// Otherwise, it's a non-static member subobject.
14958///
14959/// \param Copying Whether we're copying or moving.
14960///
14961/// \param Depth Internal parameter recording the depth of the recursion.
14962///
14963/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14964/// if a memcpy should be used instead.
14965static StmtResult
14967 const ExprBuilder &To, const ExprBuilder &From,
14968 bool CopyingBaseSubobject, bool Copying,
14969 unsigned Depth = 0) {
14970 // C++11 [class.copy]p28:
14971 // Each subobject is assigned in the manner appropriate to its type:
14972 //
14973 // - if the subobject is of class type, as if by a call to operator= with
14974 // the subobject as the object expression and the corresponding
14975 // subobject of x as a single function argument (as if by explicit
14976 // qualification; that is, ignoring any possible virtual overriding
14977 // functions in more derived classes);
14978 //
14979 // C++03 [class.copy]p13:
14980 // - if the subobject is of class type, the copy assignment operator for
14981 // the class is used (as if by explicit qualification; that is,
14982 // ignoring any possible virtual overriding functions in more derived
14983 // classes);
14984 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
14985 // Look for operator=.
14986 DeclarationName Name
14988 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14989 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14990
14991 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14992 // operator.
14993 if (!S.getLangOpts().CPlusPlus11) {
14994 LookupResult::Filter F = OpLookup.makeFilter();
14995 while (F.hasNext()) {
14996 NamedDecl *D = F.next();
14997 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14998 if (Method->isCopyAssignmentOperator() ||
14999 (!Copying && Method->isMoveAssignmentOperator()))
15000 continue;
15001
15002 F.erase();
15003 }
15004 F.done();
15005 }
15006
15007 // Suppress the protected check (C++ [class.protected]) for each of the
15008 // assignment operators we found. This strange dance is required when
15009 // we're assigning via a base classes's copy-assignment operator. To
15010 // ensure that we're getting the right base class subobject (without
15011 // ambiguities), we need to cast "this" to that subobject type; to
15012 // ensure that we don't go through the virtual call mechanism, we need
15013 // to qualify the operator= name with the base class (see below). However,
15014 // this means that if the base class has a protected copy assignment
15015 // operator, the protected member access check will fail. So, we
15016 // rewrite "protected" access to "public" access in this case, since we
15017 // know by construction that we're calling from a derived class.
15018 if (CopyingBaseSubobject) {
15019 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15020 L != LEnd; ++L) {
15021 if (L.getAccess() == AS_protected)
15022 L.setAccess(AS_public);
15023 }
15024 }
15025
15026 // Create the nested-name-specifier that will be used to qualify the
15027 // reference to operator=; this is required to suppress the virtual
15028 // call mechanism.
15029 CXXScopeSpec SS;
15030 // FIXME: Don't canonicalize this.
15031 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
15032 SS.MakeTrivial(S.Context, NestedNameSpecifier(CanonicalT), Loc);
15033
15034 // Create the reference to operator=.
15035 ExprResult OpEqualRef
15036 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
15037 SS, /*TemplateKWLoc=*/SourceLocation(),
15038 /*FirstQualifierInScope=*/nullptr,
15039 OpLookup,
15040 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15041 /*SuppressQualifierCheck=*/true);
15042 if (OpEqualRef.isInvalid())
15043 return StmtError();
15044
15045 // Build the call to the assignment operator.
15046
15047 Expr *FromInst = From.build(S, Loc);
15048 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
15049 OpEqualRef.getAs<Expr>(),
15050 Loc, FromInst, Loc);
15051 if (Call.isInvalid())
15052 return StmtError();
15053
15054 // If we built a call to a trivial 'operator=' while copying an array,
15055 // bail out. We'll replace the whole shebang with a memcpy.
15056 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
15057 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15058 return StmtResult((Stmt*)nullptr);
15059
15060 // Convert to an expression-statement, and clean up any produced
15061 // temporaries.
15062 return S.ActOnExprStmt(Call);
15063 }
15064
15065 // - if the subobject is of scalar type, the built-in assignment
15066 // operator is used.
15067 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
15068 if (!ArrayTy) {
15070 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
15071 if (Assignment.isInvalid())
15072 return StmtError();
15073 return S.ActOnExprStmt(Assignment);
15074 }
15075
15076 // - if the subobject is an array, each element is assigned, in the
15077 // manner appropriate to the element type;
15078
15079 // Construct a loop over the array bounds, e.g.,
15080 //
15081 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15082 //
15083 // that will copy each of the array elements.
15084 QualType SizeType = S.Context.getSizeType();
15085
15086 // Create the iteration variable.
15087 IdentifierInfo *IterationVarName = nullptr;
15088 {
15089 SmallString<8> Str;
15090 llvm::raw_svector_ostream OS(Str);
15091 OS << "__i" << Depth;
15092 IterationVarName = &S.Context.Idents.get(OS.str());
15093 }
15094 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
15095 IterationVarName, SizeType,
15096 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
15097 SC_None);
15098
15099 // Initialize the iteration variable to zero.
15100 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
15101 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
15102
15103 // Creates a reference to the iteration variable.
15104 RefBuilder IterationVarRef(IterationVar, SizeType);
15105 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15106
15107 // Create the DeclStmt that holds the iteration variable.
15108 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15109
15110 // Subscript the "from" and "to" expressions with the iteration variable.
15111 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15112 MoveCastBuilder FromIndexMove(FromIndexCopy);
15113 const ExprBuilder *FromIndex;
15114 if (Copying)
15115 FromIndex = &FromIndexCopy;
15116 else
15117 FromIndex = &FromIndexMove;
15118
15119 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15120
15121 // Build the copy/move for an individual element of the array.
15122 StmtResult Copy =
15124 ToIndex, *FromIndex, CopyingBaseSubobject,
15125 Copying, Depth + 1);
15126 // Bail out if copying fails or if we determined that we should use memcpy.
15127 if (Copy.isInvalid() || !Copy.get())
15128 return Copy;
15129
15130 // Create the comparison against the array bound.
15131 llvm::APInt Upper
15132 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
15134 S.Context, IterationVarRefRVal.build(S, Loc),
15135 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
15138
15139 // Create the pre-increment of the iteration variable. We can determine
15140 // whether the increment will overflow based on the value of the array
15141 // bound.
15142 Expr *Increment = UnaryOperator::Create(
15143 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
15144 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
15145
15146 // Construct the loop that copies all elements of this array.
15147 return S.ActOnForStmt(
15148 Loc, Loc, InitStmt,
15150 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
15151}
15152
15153static StmtResult
15155 const ExprBuilder &To, const ExprBuilder &From,
15156 bool CopyingBaseSubobject, bool Copying) {
15157 // Maybe we should use a memcpy?
15158 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
15159 T.isTriviallyCopyableType(S.Context))
15160 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15161
15162 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15163 CopyingBaseSubobject,
15164 Copying, 0));
15165
15166 // If we ended up picking a trivial assignment operator for an array of a
15167 // non-trivially-copyable class type, just emit a memcpy.
15168 if (!Result.isInvalid() && !Result.get())
15169 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
15170
15171 return Result;
15172}
15173
15175 // Note: The following rules are largely analoguous to the copy
15176 // constructor rules. Note that virtual bases are not taken into account
15177 // for determining the argument type of the operator. Note also that
15178 // operators taking an object instead of a reference are allowed.
15179 assert(ClassDecl->needsImplicitCopyAssignment());
15180
15181 DeclaringSpecialMember DSM(*this, ClassDecl,
15183 if (DSM.isAlreadyBeingDeclared())
15184 return nullptr;
15185
15187 /*Qualifier=*/std::nullopt, ClassDecl,
15188 /*OwnsTag=*/false);
15190 if (AS != LangAS::Default)
15191 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15192 QualType RetType = Context.getLValueReferenceType(ArgType);
15193 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15194 if (Const)
15195 ArgType = ArgType.withConst();
15196
15197 ArgType = Context.getLValueReferenceType(ArgType);
15198
15200 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
15201
15202 // An implicitly-declared copy assignment operator is an inline public
15203 // member of its class.
15204 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15205 SourceLocation ClassLoc = ClassDecl->getLocation();
15206 DeclarationNameInfo NameInfo(Name, ClassLoc);
15208 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15209 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15210 getCurFPFeatures().isFPConstrained(),
15211 /*isInline=*/true,
15213 SourceLocation());
15214 CopyAssignment->setAccess(AS_public);
15215 CopyAssignment->setDefaulted();
15216 CopyAssignment->setImplicit();
15217
15218 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
15219
15220 if (getLangOpts().CUDA)
15221 CUDA().inferTargetForImplicitSpecialMember(
15223 /* ConstRHS */ Const,
15224 /* Diagnose */ false);
15225
15226 // Add the parameter to the operator.
15228 ClassLoc, ClassLoc,
15229 /*Id=*/nullptr, ArgType,
15230 /*TInfo=*/nullptr, SC_None,
15231 nullptr);
15232 CopyAssignment->setParams(FromParam);
15233
15234 CopyAssignment->setTrivial(
15238 : ClassDecl->hasTrivialCopyAssignment());
15239
15240 // Note that we have added this copy-assignment operator.
15241 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15242
15243 Scope *S = getScopeForContext(ClassDecl);
15245
15249 SetDeclDeleted(CopyAssignment, ClassLoc);
15250 }
15251
15252 if (S)
15254 ClassDecl->addDecl(CopyAssignment);
15255
15256 return CopyAssignment;
15257}
15258
15259/// Diagnose an implicit copy operation for a class which is odr-used, but
15260/// which is deprecated because the class has a user-declared copy constructor,
15261/// copy assignment operator, or destructor.
15263 assert(CopyOp->isImplicit());
15264
15265 CXXRecordDecl *RD = CopyOp->getParent();
15266 CXXMethodDecl *UserDeclaredOperation = nullptr;
15267
15268 if (RD->hasUserDeclaredDestructor()) {
15269 UserDeclaredOperation = RD->getDestructor();
15270 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
15272 // Find any user-declared copy constructor.
15273 for (auto *I : RD->ctors()) {
15274 if (I->isCopyConstructor()) {
15275 UserDeclaredOperation = I;
15276 break;
15277 }
15278 }
15279 assert(UserDeclaredOperation);
15280 } else if (isa<CXXConstructorDecl>(CopyOp) &&
15282 // Find any user-declared move assignment operator.
15283 for (auto *I : RD->methods()) {
15284 if (I->isCopyAssignmentOperator()) {
15285 UserDeclaredOperation = I;
15286 break;
15287 }
15288 }
15289 assert(UserDeclaredOperation);
15290 }
15291
15292 if (UserDeclaredOperation) {
15293 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15294 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
15295 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
15296 unsigned DiagID =
15297 (UDOIsUserProvided && UDOIsDestructor)
15298 ? diag::warn_deprecated_copy_with_user_provided_dtor
15299 : (UDOIsUserProvided && !UDOIsDestructor)
15300 ? diag::warn_deprecated_copy_with_user_provided_copy
15301 : (!UDOIsUserProvided && UDOIsDestructor)
15302 ? diag::warn_deprecated_copy_with_dtor
15303 : diag::warn_deprecated_copy;
15304 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
15305 << RD << IsCopyAssignment;
15306 }
15307}
15308
15310 CXXMethodDecl *CopyAssignOperator) {
15311 assert((CopyAssignOperator->isDefaulted() &&
15312 CopyAssignOperator->isOverloadedOperator() &&
15313 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15314 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15315 !CopyAssignOperator->isDeleted()) &&
15316 "DefineImplicitCopyAssignment called for wrong function");
15317 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15318 return;
15319
15320 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15321 if (ClassDecl->isInvalidDecl()) {
15322 CopyAssignOperator->setInvalidDecl();
15323 return;
15324 }
15325
15326 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15327
15328 // The exception specification is needed because we are defining the
15329 // function.
15330 ResolveExceptionSpec(CurrentLocation,
15331 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15332
15333 // Add a context note for diagnostics produced after this point.
15334 Scope.addContextNote(CurrentLocation);
15335
15336 // C++11 [class.copy]p18:
15337 // The [definition of an implicitly declared copy assignment operator] is
15338 // deprecated if the class has a user-declared copy constructor or a
15339 // user-declared destructor.
15340 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15341 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15342
15343 // C++0x [class.copy]p30:
15344 // The implicitly-defined or explicitly-defaulted copy assignment operator
15345 // for a non-union class X performs memberwise copy assignment of its
15346 // subobjects. The direct base classes of X are assigned first, in the
15347 // order of their declaration in the base-specifier-list, and then the
15348 // immediate non-static data members of X are assigned, in the order in
15349 // which they were declared in the class definition.
15350
15351 // The statements that form the synthesized function body.
15352 SmallVector<Stmt*, 8> Statements;
15353
15354 // The parameter for the "other" object, which we are copying from.
15355 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15356 Qualifiers OtherQuals = Other->getType().getQualifiers();
15357 QualType OtherRefType = Other->getType();
15358 if (OtherRefType->isLValueReferenceType()) {
15359 OtherRefType = OtherRefType->getPointeeType();
15360 OtherQuals = OtherRefType.getQualifiers();
15361 }
15362
15363 // Our location for everything implicitly-generated.
15364 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15365 ? CopyAssignOperator->getEndLoc()
15366 : CopyAssignOperator->getLocation();
15367
15368 // Builds a DeclRefExpr for the "other" object.
15369 RefBuilder OtherRef(Other, OtherRefType);
15370
15371 // Builds the function object parameter.
15372 std::optional<ThisBuilder> This;
15373 std::optional<DerefBuilder> DerefThis;
15374 std::optional<RefBuilder> ExplicitObject;
15375 bool IsArrow = false;
15376 QualType ObjectType;
15377 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15378 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15379 if (ObjectType->isReferenceType())
15380 ObjectType = ObjectType->getPointeeType();
15381 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15382 } else {
15383 ObjectType = getCurrentThisType();
15384 This.emplace();
15385 DerefThis.emplace(*This);
15386 IsArrow = !LangOpts.HLSL;
15387 }
15388 ExprBuilder &ObjectParameter =
15389 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15390 : static_cast<ExprBuilder &>(*This);
15391
15392 // Assign base classes.
15393 bool Invalid = false;
15394 for (auto &Base : ClassDecl->bases()) {
15395 // Form the assignment:
15396 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15397 QualType BaseType = Base.getType().getUnqualifiedType();
15398 if (!BaseType->isRecordType()) {
15399 Invalid = true;
15400 continue;
15401 }
15402
15403 CXXCastPath BasePath;
15404 BasePath.push_back(&Base);
15405
15406 // Construct the "from" expression, which is an implicit cast to the
15407 // appropriately-qualified base type.
15408 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15409 VK_LValue, BasePath);
15410
15411 // Dereference "this".
15412 CastBuilder To(
15413 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15414 : static_cast<ExprBuilder &>(*DerefThis),
15415 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15416 VK_LValue, BasePath);
15417
15418 // Build the copy.
15419 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15420 To, From,
15421 /*CopyingBaseSubobject=*/true,
15422 /*Copying=*/true);
15423 if (Copy.isInvalid()) {
15424 CopyAssignOperator->setInvalidDecl();
15425 return;
15426 }
15427
15428 // Success! Record the copy.
15429 Statements.push_back(Copy.getAs<Expr>());
15430 }
15431
15432 // Assign non-static members.
15433 for (auto *Field : ClassDecl->fields()) {
15434 // FIXME: We should form some kind of AST representation for the implied
15435 // memcpy in a union copy operation.
15436 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15437 continue;
15438
15439 if (Field->isInvalidDecl()) {
15440 Invalid = true;
15441 continue;
15442 }
15443
15444 // Check for members of reference type; we can't copy those.
15445 if (Field->getType()->isReferenceType()) {
15446 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15447 << Context.getCanonicalTagType(ClassDecl) << 0
15448 << Field->getDeclName();
15449 Diag(Field->getLocation(), diag::note_declared_at);
15450 Invalid = true;
15451 continue;
15452 }
15453
15454 // Check for members of const-qualified, non-class type.
15455 QualType BaseType = Context.getBaseElementType(Field->getType());
15456 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15457 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15458 << Context.getCanonicalTagType(ClassDecl) << 1
15459 << Field->getDeclName();
15460 Diag(Field->getLocation(), diag::note_declared_at);
15461 Invalid = true;
15462 continue;
15463 }
15464
15465 // Suppress assigning zero-width bitfields.
15466 if (Field->isZeroLengthBitField())
15467 continue;
15468
15469 QualType FieldType = Field->getType().getNonReferenceType();
15470 if (FieldType->isIncompleteArrayType()) {
15471 assert(ClassDecl->hasFlexibleArrayMember() &&
15472 "Incomplete array type is not valid");
15473 continue;
15474 }
15475
15476 // Build references to the field in the object we're copying from and to.
15477 CXXScopeSpec SS; // Intentionally empty
15478 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15480 MemberLookup.addDecl(Field);
15481 MemberLookup.resolveKind();
15482
15483 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15484 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15485 // Build the copy of this field.
15486 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15487 To, From,
15488 /*CopyingBaseSubobject=*/false,
15489 /*Copying=*/true);
15490 if (Copy.isInvalid()) {
15491 CopyAssignOperator->setInvalidDecl();
15492 return;
15493 }
15494
15495 // Success! Record the copy.
15496 Statements.push_back(Copy.getAs<Stmt>());
15497 }
15498
15499 if (!Invalid) {
15500 // Add a "return *this;"
15501 Expr *ThisExpr =
15502 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15503 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15504 : static_cast<ExprBuilder &>(*DerefThis))
15505 .build(*this, Loc);
15506 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15507 if (Return.isInvalid())
15508 Invalid = true;
15509 else
15510 Statements.push_back(Return.getAs<Stmt>());
15511 }
15512
15513 if (Invalid) {
15514 CopyAssignOperator->setInvalidDecl();
15515 return;
15516 }
15517
15518 StmtResult Body;
15519 {
15520 CompoundScopeRAII CompoundScope(*this);
15521 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15522 /*isStmtExpr=*/false);
15523 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15524 }
15525 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15526 CopyAssignOperator->markUsed(Context);
15527
15529 L->CompletedImplicitDefinition(CopyAssignOperator);
15530 }
15531}
15532
15534 assert(ClassDecl->needsImplicitMoveAssignment());
15535
15536 DeclaringSpecialMember DSM(*this, ClassDecl,
15538 if (DSM.isAlreadyBeingDeclared())
15539 return nullptr;
15540
15541 // Note: The following rules are largely analoguous to the move
15542 // constructor rules.
15543
15545 /*Qualifier=*/std::nullopt, ClassDecl,
15546 /*OwnsTag=*/false);
15548 if (AS != LangAS::Default)
15549 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15550 QualType RetType = Context.getLValueReferenceType(ArgType);
15551 ArgType = Context.getRValueReferenceType(ArgType);
15552
15554 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15555
15556 // An implicitly-declared move assignment operator is an inline public
15557 // member of its class.
15558 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15559 SourceLocation ClassLoc = ClassDecl->getLocation();
15560 DeclarationNameInfo NameInfo(Name, ClassLoc);
15562 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15563 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15564 getCurFPFeatures().isFPConstrained(),
15565 /*isInline=*/true,
15567 SourceLocation());
15568 MoveAssignment->setAccess(AS_public);
15569 MoveAssignment->setDefaulted();
15570 MoveAssignment->setImplicit();
15571
15572 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15573
15574 if (getLangOpts().CUDA)
15575 CUDA().inferTargetForImplicitSpecialMember(
15577 /* ConstRHS */ false,
15578 /* Diagnose */ false);
15579
15580 // Add the parameter to the operator.
15582 ClassLoc, ClassLoc,
15583 /*Id=*/nullptr, ArgType,
15584 /*TInfo=*/nullptr, SC_None,
15585 nullptr);
15586 MoveAssignment->setParams(FromParam);
15587
15588 MoveAssignment->setTrivial(
15592 : ClassDecl->hasTrivialMoveAssignment());
15593
15594 // Note that we have added this copy-assignment operator.
15595 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15596
15597 Scope *S = getScopeForContext(ClassDecl);
15599
15603 SetDeclDeleted(MoveAssignment, ClassLoc);
15604 }
15605
15606 if (S)
15608 ClassDecl->addDecl(MoveAssignment);
15609
15610 return MoveAssignment;
15611}
15612
15613/// Check if we're implicitly defining a move assignment operator for a class
15614/// with virtual bases. Such a move assignment might move-assign the virtual
15615/// base multiple times.
15617 SourceLocation CurrentLocation) {
15618 assert(!Class->isDependentContext() && "should not define dependent move");
15619
15620 // Only a virtual base could get implicitly move-assigned multiple times.
15621 // Only a non-trivial move assignment can observe this. We only want to
15622 // diagnose if we implicitly define an assignment operator that assigns
15623 // two base classes, both of which move-assign the same virtual base.
15624 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15625 Class->getNumBases() < 2)
15626 return;
15627
15629 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15630 VBaseMap VBases;
15631
15632 for (auto &BI : Class->bases()) {
15633 Worklist.push_back(&BI);
15634 while (!Worklist.empty()) {
15635 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15636 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15637
15638 // If the base has no non-trivial move assignment operators,
15639 // we don't care about moves from it.
15640 if (!Base->hasNonTrivialMoveAssignment())
15641 continue;
15642
15643 // If there's nothing virtual here, skip it.
15644 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15645 continue;
15646
15647 // If we're not actually going to call a move assignment for this base,
15648 // or the selected move assignment is trivial, skip it.
15651 /*ConstArg*/ false, /*VolatileArg*/ false,
15652 /*RValueThis*/ true, /*ConstThis*/ false,
15653 /*VolatileThis*/ false);
15654 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15656 continue;
15657
15658 if (BaseSpec->isVirtual()) {
15659 // We're going to move-assign this virtual base, and its move
15660 // assignment operator is not trivial. If this can happen for
15661 // multiple distinct direct bases of Class, diagnose it. (If it
15662 // only happens in one base, we'll diagnose it when synthesizing
15663 // that base class's move assignment operator.)
15664 CXXBaseSpecifier *&Existing =
15665 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15666 .first->second;
15667 if (Existing && Existing != &BI) {
15668 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15669 << Class << Base;
15670 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15671 << (Base->getCanonicalDecl() ==
15673 << Base << Existing->getType() << Existing->getSourceRange();
15674 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15675 << (Base->getCanonicalDecl() ==
15676 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15677 << Base << BI.getType() << BaseSpec->getSourceRange();
15678
15679 // Only diagnose each vbase once.
15680 Existing = nullptr;
15681 }
15682 } else {
15683 // Only walk over bases that have defaulted move assignment operators.
15684 // We assume that any user-provided move assignment operator handles
15685 // the multiple-moves-of-vbase case itself somehow.
15686 if (!SMOR.getMethod()->isDefaulted())
15687 continue;
15688
15689 // We're going to move the base classes of Base. Add them to the list.
15690 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15691 }
15692 }
15693 }
15694}
15695
15697 CXXMethodDecl *MoveAssignOperator) {
15698 assert((MoveAssignOperator->isDefaulted() &&
15699 MoveAssignOperator->isOverloadedOperator() &&
15700 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15701 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15702 !MoveAssignOperator->isDeleted()) &&
15703 "DefineImplicitMoveAssignment called for wrong function");
15704 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15705 return;
15706
15707 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15708 if (ClassDecl->isInvalidDecl()) {
15709 MoveAssignOperator->setInvalidDecl();
15710 return;
15711 }
15712
15713 // C++0x [class.copy]p28:
15714 // The implicitly-defined or move assignment operator for a non-union class
15715 // X performs memberwise move assignment of its subobjects. The direct base
15716 // classes of X are assigned first, in the order of their declaration in the
15717 // base-specifier-list, and then the immediate non-static data members of X
15718 // are assigned, in the order in which they were declared in the class
15719 // definition.
15720
15721 // Issue a warning if our implicit move assignment operator will move
15722 // from a virtual base more than once.
15723 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15724
15725 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15726
15727 // The exception specification is needed because we are defining the
15728 // function.
15729 ResolveExceptionSpec(CurrentLocation,
15730 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15731
15732 // Add a context note for diagnostics produced after this point.
15733 Scope.addContextNote(CurrentLocation);
15734
15735 // The statements that form the synthesized function body.
15736 SmallVector<Stmt*, 8> Statements;
15737
15738 // The parameter for the "other" object, which we are move from.
15739 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15740 QualType OtherRefType =
15741 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15742
15743 // Our location for everything implicitly-generated.
15744 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15745 ? MoveAssignOperator->getEndLoc()
15746 : MoveAssignOperator->getLocation();
15747
15748 // Builds a reference to the "other" object.
15749 RefBuilder OtherRef(Other, OtherRefType);
15750 // Cast to rvalue.
15751 MoveCastBuilder MoveOther(OtherRef);
15752
15753 // Builds the function object parameter.
15754 std::optional<ThisBuilder> This;
15755 std::optional<DerefBuilder> DerefThis;
15756 std::optional<RefBuilder> ExplicitObject;
15757 QualType ObjectType;
15758 bool IsArrow = false;
15759 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15760 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15761 if (ObjectType->isReferenceType())
15762 ObjectType = ObjectType->getPointeeType();
15763 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15764 } else {
15765 ObjectType = getCurrentThisType();
15766 This.emplace();
15767 DerefThis.emplace(*This);
15768 IsArrow = !getLangOpts().HLSL;
15769 }
15770 ExprBuilder &ObjectParameter =
15771 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15772
15773 // Assign base classes.
15774 bool Invalid = false;
15775 for (auto &Base : ClassDecl->bases()) {
15776 // C++11 [class.copy]p28:
15777 // It is unspecified whether subobjects representing virtual base classes
15778 // are assigned more than once by the implicitly-defined copy assignment
15779 // operator.
15780 // FIXME: Do not assign to a vbase that will be assigned by some other base
15781 // class. For a move-assignment, this can result in the vbase being moved
15782 // multiple times.
15783
15784 // Form the assignment:
15785 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15786 QualType BaseType = Base.getType().getUnqualifiedType();
15787 if (!BaseType->isRecordType()) {
15788 Invalid = true;
15789 continue;
15790 }
15791
15792 CXXCastPath BasePath;
15793 BasePath.push_back(&Base);
15794
15795 // Construct the "from" expression, which is an implicit cast to the
15796 // appropriately-qualified base type.
15797 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15798
15799 // Implicitly cast "this" to the appropriately-qualified base type.
15800 // Dereference "this".
15801 CastBuilder To(
15802 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15803 : static_cast<ExprBuilder &>(*DerefThis),
15804 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15805 VK_LValue, BasePath);
15806
15807 // Build the move.
15808 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15809 To, From,
15810 /*CopyingBaseSubobject=*/true,
15811 /*Copying=*/false);
15812 if (Move.isInvalid()) {
15813 MoveAssignOperator->setInvalidDecl();
15814 return;
15815 }
15816
15817 // Success! Record the move.
15818 Statements.push_back(Move.getAs<Expr>());
15819 }
15820
15821 // Assign non-static members.
15822 for (auto *Field : ClassDecl->fields()) {
15823 // FIXME: We should form some kind of AST representation for the implied
15824 // memcpy in a union copy operation.
15825 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15826 continue;
15827
15828 if (Field->isInvalidDecl()) {
15829 Invalid = true;
15830 continue;
15831 }
15832
15833 // Check for members of reference type; we can't move those.
15834 if (Field->getType()->isReferenceType()) {
15835 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15836 << Context.getCanonicalTagType(ClassDecl) << 0
15837 << Field->getDeclName();
15838 Diag(Field->getLocation(), diag::note_declared_at);
15839 Invalid = true;
15840 continue;
15841 }
15842
15843 // Check for members of const-qualified, non-class type.
15844 QualType BaseType = Context.getBaseElementType(Field->getType());
15845 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15846 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15847 << Context.getCanonicalTagType(ClassDecl) << 1
15848 << Field->getDeclName();
15849 Diag(Field->getLocation(), diag::note_declared_at);
15850 Invalid = true;
15851 continue;
15852 }
15853
15854 // Suppress assigning zero-width bitfields.
15855 if (Field->isZeroLengthBitField())
15856 continue;
15857
15858 QualType FieldType = Field->getType().getNonReferenceType();
15859 if (FieldType->isIncompleteArrayType()) {
15860 assert(ClassDecl->hasFlexibleArrayMember() &&
15861 "Incomplete array type is not valid");
15862 continue;
15863 }
15864
15865 // Build references to the field in the object we're copying from and to.
15866 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15868 MemberLookup.addDecl(Field);
15869 MemberLookup.resolveKind();
15870 MemberBuilder From(MoveOther, OtherRefType,
15871 /*IsArrow=*/false, MemberLookup);
15872 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15873
15874 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15875 "Member reference with rvalue base must be rvalue except for reference "
15876 "members, which aren't allowed for move assignment.");
15877
15878 // Build the move of this field.
15879 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15880 To, From,
15881 /*CopyingBaseSubobject=*/false,
15882 /*Copying=*/false);
15883 if (Move.isInvalid()) {
15884 MoveAssignOperator->setInvalidDecl();
15885 return;
15886 }
15887
15888 // Success! Record the copy.
15889 Statements.push_back(Move.getAs<Stmt>());
15890 }
15891
15892 if (!Invalid) {
15893 // Add a "return *this;"
15894 Expr *ThisExpr =
15895 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15896 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15897 : static_cast<ExprBuilder &>(*DerefThis))
15898 .build(*this, Loc);
15899
15900 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15901 if (Return.isInvalid())
15902 Invalid = true;
15903 else
15904 Statements.push_back(Return.getAs<Stmt>());
15905 }
15906
15907 if (Invalid) {
15908 MoveAssignOperator->setInvalidDecl();
15909 return;
15910 }
15911
15912 StmtResult Body;
15913 {
15914 CompoundScopeRAII CompoundScope(*this);
15915 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15916 /*isStmtExpr=*/false);
15917 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15918 }
15919 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15920 MoveAssignOperator->markUsed(Context);
15921
15923 L->CompletedImplicitDefinition(MoveAssignOperator);
15924 }
15925}
15926
15928 CXXRecordDecl *ClassDecl) {
15929 // C++ [class.copy]p4:
15930 // If the class definition does not explicitly declare a copy
15931 // constructor, one is declared implicitly.
15932 assert(ClassDecl->needsImplicitCopyConstructor());
15933
15934 DeclaringSpecialMember DSM(*this, ClassDecl,
15936 if (DSM.isAlreadyBeingDeclared())
15937 return nullptr;
15938
15939 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
15940 /*Qualifier=*/std::nullopt, ClassDecl,
15941 /*OwnsTag=*/false);
15942 QualType ArgType = ClassType;
15943 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15944 if (Const)
15945 ArgType = ArgType.withConst();
15946
15948 if (AS != LangAS::Default)
15949 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15950
15951 ArgType = Context.getLValueReferenceType(ArgType);
15952
15954 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15955
15956 DeclarationName Name
15957 = Context.DeclarationNames.getCXXConstructorName(
15958 Context.getCanonicalType(ClassType));
15959 SourceLocation ClassLoc = ClassDecl->getLocation();
15960 DeclarationNameInfo NameInfo(Name, ClassLoc);
15961
15962 // An implicitly-declared copy constructor is an inline public
15963 // member of its class.
15965 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15966 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15967 /*isInline=*/true,
15968 /*isImplicitlyDeclared=*/true,
15971 CopyConstructor->setAccess(AS_public);
15972 CopyConstructor->setDefaulted();
15973
15974 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15975
15976 if (getLangOpts().CUDA)
15977 CUDA().inferTargetForImplicitSpecialMember(
15979 /* ConstRHS */ Const,
15980 /* Diagnose */ false);
15981
15982 // During template instantiation of special member functions we need a
15983 // reliable TypeSourceInfo for the parameter types in order to allow functions
15984 // to be substituted.
15985 TypeSourceInfo *TSI = nullptr;
15986 if (inTemplateInstantiation() && ClassDecl->isLambda())
15987 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15988
15989 // Add the parameter to the constructor.
15990 ParmVarDecl *FromParam =
15991 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15992 /*IdentifierInfo=*/nullptr, ArgType,
15993 /*TInfo=*/TSI, SC_None, nullptr);
15994 CopyConstructor->setParams(FromParam);
15995
15996 CopyConstructor->setTrivial(
16000 : ClassDecl->hasTrivialCopyConstructor());
16001
16002 CopyConstructor->setTrivialForCall(
16003 ClassDecl->hasAttr<TrivialABIAttr>() ||
16008 : ClassDecl->hasTrivialCopyConstructorForCall()));
16009
16010 // Note that we have declared this constructor.
16011 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16012
16013 Scope *S = getScopeForContext(ClassDecl);
16015
16020 }
16021
16022 if (S)
16024 ClassDecl->addDecl(CopyConstructor);
16025
16026 return CopyConstructor;
16027}
16028
16031 assert((CopyConstructor->isDefaulted() &&
16032 CopyConstructor->isCopyConstructor() &&
16033 !CopyConstructor->doesThisDeclarationHaveABody() &&
16034 !CopyConstructor->isDeleted()) &&
16035 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16036 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16037 return;
16038
16039 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16040 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16041
16043
16044 // The exception specification is needed because we are defining the
16045 // function.
16046 ResolveExceptionSpec(CurrentLocation,
16047 CopyConstructor->getType()->castAs<FunctionProtoType>());
16048 MarkVTableUsed(CurrentLocation, ClassDecl);
16049
16050 // Add a context note for diagnostics produced after this point.
16051 Scope.addContextNote(CurrentLocation);
16052
16053 // C++11 [class.copy]p7:
16054 // The [definition of an implicitly declared copy constructor] is
16055 // deprecated if the class has a user-declared copy assignment operator
16056 // or a user-declared destructor.
16057 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16059
16060 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
16061 CopyConstructor->setInvalidDecl();
16062 } else {
16063 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16064 ? CopyConstructor->getEndLoc()
16065 : CopyConstructor->getLocation();
16066 Sema::CompoundScopeRAII CompoundScope(*this);
16067 CopyConstructor->setBody(
16068 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16069 CopyConstructor->markUsed(Context);
16070 }
16071
16073 L->CompletedImplicitDefinition(CopyConstructor);
16074 }
16075}
16076
16078 CXXRecordDecl *ClassDecl) {
16079 assert(ClassDecl->needsImplicitMoveConstructor());
16080
16081 DeclaringSpecialMember DSM(*this, ClassDecl,
16083 if (DSM.isAlreadyBeingDeclared())
16084 return nullptr;
16085
16086 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,
16087 /*Qualifier=*/std::nullopt, ClassDecl,
16088 /*OwnsTag=*/false);
16089
16090 QualType ArgType = ClassType;
16092 if (AS != LangAS::Default)
16093 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
16094 ArgType = Context.getRValueReferenceType(ArgType);
16095
16097 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
16098
16099 DeclarationName Name
16100 = Context.DeclarationNames.getCXXConstructorName(
16101 Context.getCanonicalType(ClassType));
16102 SourceLocation ClassLoc = ClassDecl->getLocation();
16103 DeclarationNameInfo NameInfo(Name, ClassLoc);
16104
16105 // C++11 [class.copy]p11:
16106 // An implicitly-declared copy/move constructor is an inline public
16107 // member of its class.
16109 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
16110 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
16111 /*isInline=*/true,
16112 /*isImplicitlyDeclared=*/true,
16115 MoveConstructor->setAccess(AS_public);
16116 MoveConstructor->setDefaulted();
16117
16118 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
16119
16120 if (getLangOpts().CUDA)
16121 CUDA().inferTargetForImplicitSpecialMember(
16123 /* ConstRHS */ false,
16124 /* Diagnose */ false);
16125
16126 // Add the parameter to the constructor.
16128 ClassLoc, ClassLoc,
16129 /*IdentifierInfo=*/nullptr,
16130 ArgType, /*TInfo=*/nullptr,
16131 SC_None, nullptr);
16132 MoveConstructor->setParams(FromParam);
16133
16134 MoveConstructor->setTrivial(
16138 : ClassDecl->hasTrivialMoveConstructor());
16139
16140 MoveConstructor->setTrivialForCall(
16141 ClassDecl->hasAttr<TrivialABIAttr>() ||
16146 : ClassDecl->hasTrivialMoveConstructorForCall()));
16147
16148 // Note that we have declared this constructor.
16149 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16150
16151 Scope *S = getScopeForContext(ClassDecl);
16153
16158 }
16159
16160 if (S)
16162 ClassDecl->addDecl(MoveConstructor);
16163
16164 return MoveConstructor;
16165}
16166
16169 assert((MoveConstructor->isDefaulted() &&
16170 MoveConstructor->isMoveConstructor() &&
16171 !MoveConstructor->doesThisDeclarationHaveABody() &&
16172 !MoveConstructor->isDeleted()) &&
16173 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16174 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16175 return;
16176
16177 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16178 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16179
16181
16182 // The exception specification is needed because we are defining the
16183 // function.
16184 ResolveExceptionSpec(CurrentLocation,
16185 MoveConstructor->getType()->castAs<FunctionProtoType>());
16186 MarkVTableUsed(CurrentLocation, ClassDecl);
16187
16188 // Add a context note for diagnostics produced after this point.
16189 Scope.addContextNote(CurrentLocation);
16190
16191 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
16192 MoveConstructor->setInvalidDecl();
16193 } else {
16194 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16195 ? MoveConstructor->getEndLoc()
16196 : MoveConstructor->getLocation();
16197 Sema::CompoundScopeRAII CompoundScope(*this);
16198 MoveConstructor->setBody(
16199 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());
16200 MoveConstructor->markUsed(Context);
16201 }
16202
16204 L->CompletedImplicitDefinition(MoveConstructor);
16205 }
16206}
16207
16209 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
16210}
16211
16213 SourceLocation CurrentLocation,
16214 CXXConversionDecl *Conv) {
16215 SynthesizedFunctionScope Scope(*this, Conv);
16216 assert(!Conv->getReturnType()->isUndeducedType());
16217
16218 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16219 CallingConv CC =
16220 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16221
16222 CXXRecordDecl *Lambda = Conv->getParent();
16223 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16224 FunctionDecl *Invoker =
16225 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16226 ? CallOp
16227 : Lambda->getLambdaStaticInvoker(CC);
16228
16229 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16231 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
16232 if (!CallOp)
16233 return;
16234
16235 if (CallOp != Invoker) {
16237 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
16238 CurrentLocation);
16239 if (!Invoker)
16240 return;
16241 }
16242 }
16243
16244 if (CallOp->isInvalidDecl())
16245 return;
16246
16247 // Mark the call operator referenced (and add to pending instantiations
16248 // if necessary).
16249 // For both the conversion and static-invoker template specializations
16250 // we construct their body's in this function, so no need to add them
16251 // to the PendingInstantiations.
16252 MarkFunctionReferenced(CurrentLocation, CallOp);
16253
16254 if (Invoker != CallOp) {
16255 // Fill in the __invoke function with a dummy implementation. IR generation
16256 // will fill in the actual details. Update its type in case it contained
16257 // an 'auto'.
16258 Invoker->markUsed(Context);
16259 Invoker->setReferenced();
16260 Invoker->setType(Conv->getReturnType()->getPointeeType());
16261 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16262 }
16263
16264 // Construct the body of the conversion function { return __invoke; }.
16265 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
16266 Conv->getLocation());
16267 assert(FunctionRef && "Can't refer to __invoke function?");
16268 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
16270 Conv->getLocation(), Conv->getLocation()));
16271 Conv->markUsed(Context);
16272 Conv->setReferenced();
16273
16275 L->CompletedImplicitDefinition(Conv);
16276 if (Invoker != CallOp)
16277 L->CompletedImplicitDefinition(Invoker);
16278 }
16279}
16280
16282 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16283 assert(!Conv->getParent()->isGenericLambda());
16284
16285 SynthesizedFunctionScope Scope(*this, Conv);
16286
16287 // Copy-initialize the lambda object as needed to capture it.
16288 Expr *This = ActOnCXXThis(CurrentLocation).get();
16289 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
16290
16291 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16292 Conv->getLocation(),
16293 Conv, DerefThis);
16294
16295 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16296 // behavior. Note that only the general conversion function does this
16297 // (since it's unusable otherwise); in the case where we inline the
16298 // block literal, it has block literal lifetime semantics.
16299 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16300 BuildBlock = ImplicitCastExpr::Create(
16301 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
16302 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
16303
16304 if (BuildBlock.isInvalid()) {
16305 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16306 Conv->setInvalidDecl();
16307 return;
16308 }
16309
16310 // Create the return statement that returns the block from the conversion
16311 // function.
16312 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
16313 if (Return.isInvalid()) {
16314 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
16315 Conv->setInvalidDecl();
16316 return;
16317 }
16318
16319 // Set the body of the conversion function.
16320 Stmt *ReturnS = Return.get();
16322 Conv->getLocation(), Conv->getLocation()));
16323 Conv->markUsed(Context);
16324
16325 // We're done; notify the mutation listener, if any.
16327 L->CompletedImplicitDefinition(Conv);
16328 }
16329}
16330
16331/// Determine whether the given list arguments contains exactly one
16332/// "real" (non-default) argument.
16334 switch (Args.size()) {
16335 case 0:
16336 return false;
16337
16338 default:
16339 if (!Args[1]->isDefaultArgument())
16340 return false;
16341
16342 [[fallthrough]];
16343 case 1:
16344 return !Args[0]->isDefaultArgument();
16345 }
16346
16347 return false;
16348}
16349
16351 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16353 bool HadMultipleCandidates, bool IsListInitialization,
16354 bool IsStdInitListInitialization, bool RequiresZeroInit,
16355 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16356 bool Elidable = false;
16357
16358 // C++0x [class.copy]p34:
16359 // When certain criteria are met, an implementation is allowed to
16360 // omit the copy/move construction of a class object, even if the
16361 // copy/move constructor and/or destructor for the object have
16362 // side effects. [...]
16363 // - when a temporary class object that has not been bound to a
16364 // reference (12.2) would be copied/moved to a class object
16365 // with the same cv-unqualified type, the copy/move operation
16366 // can be omitted by constructing the temporary object
16367 // directly into the target of the omitted copy/move
16368 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16369 // FIXME: Converting constructors should also be accepted.
16370 // But to fix this, the logic that digs down into a CXXConstructExpr
16371 // to find the source object needs to handle it.
16372 // Right now it assumes the source object is passed directly as the
16373 // first argument.
16374 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16375 Expr *SubExpr = ExprArgs[0];
16376 // FIXME: Per above, this is also incorrect if we want to accept
16377 // converting constructors, as isTemporaryObject will
16378 // reject temporaries with different type from the
16379 // CXXRecord itself.
16380 Elidable = SubExpr->isTemporaryObject(
16382 }
16383
16384 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16385 FoundDecl, Constructor,
16386 Elidable, ExprArgs, HadMultipleCandidates,
16387 IsListInitialization,
16388 IsStdInitListInitialization, RequiresZeroInit,
16389 ConstructKind, ParenRange);
16390}
16391
16393 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16394 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16395 bool HadMultipleCandidates, bool IsListInitialization,
16396 bool IsStdInitListInitialization, bool RequiresZeroInit,
16397 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16398 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16399 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16400 // The only way to get here is if we did overload resolution to find the
16401 // shadow decl, so we don't need to worry about re-checking the trailing
16402 // requires clause.
16403 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16404 return ExprError();
16405 }
16406
16407 return BuildCXXConstructExpr(
16408 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16409 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16410 RequiresZeroInit, ConstructKind, ParenRange);
16411}
16412
16413/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16414/// including handling of its default argument expressions.
16416 SourceLocation ConstructLoc, QualType DeclInitType,
16417 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16418 bool HadMultipleCandidates, bool IsListInitialization,
16419 bool IsStdInitListInitialization, bool RequiresZeroInit,
16420 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16421 assert(declaresSameEntity(
16422 Constructor->getParent(),
16423 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16424 "given constructor for wrong type");
16425 MarkFunctionReferenced(ConstructLoc, Constructor);
16426 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
16427 return ExprError();
16428
16431 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16432 HadMultipleCandidates, IsListInitialization,
16433 IsStdInitListInitialization, RequiresZeroInit,
16434 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16435 Constructor);
16436}
16437
16439 if (VD->isInvalidDecl()) return;
16440 // If initializing the variable failed, don't also diagnose problems with
16441 // the destructor, they're likely related.
16442 if (VD->getInit() && VD->getInit()->containsErrors())
16443 return;
16444
16445 ClassDecl = ClassDecl->getDefinitionOrSelf();
16446 if (ClassDecl->isInvalidDecl()) return;
16447 if (ClassDecl->hasIrrelevantDestructor()) return;
16448 if (ClassDecl->isDependentContext()) return;
16449
16450 if (VD->isNoDestroy(getASTContext()))
16451 return;
16452
16454 // The result of `LookupDestructor` might be nullptr if the destructor is
16455 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16456 // will not be selected by `CXXRecordDecl::getDestructor()`.
16457 if (!Destructor)
16458 return;
16459 // If this is an array, we'll require the destructor during initialization, so
16460 // we can skip over this. We still want to emit exit-time destructor warnings
16461 // though.
16462 if (!VD->getType()->isArrayType()) {
16465 PDiag(diag::err_access_dtor_var)
16466 << VD->getDeclName() << VD->getType());
16468 }
16469
16470 if (Destructor->isTrivial()) return;
16471
16472 // If the destructor is constexpr, check whether the variable has constant
16473 // destruction now.
16474 if (Destructor->isConstexpr()) {
16475 bool HasConstantInit = false;
16476 if (VD->getInit() && !VD->getInit()->isValueDependent())
16477 HasConstantInit = VD->evaluateValue();
16479 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16480 HasConstantInit) {
16481 Diag(VD->getLocation(),
16482 diag::err_constexpr_var_requires_const_destruction) << VD;
16483 for (const PartialDiagnosticAt &Note : Notes)
16484 Diag(Note.first, Note.second);
16485 }
16486 }
16487
16488 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16489 return;
16490
16491 // Emit warning for non-trivial dtor in global scope (a real global,
16492 // class-static, function-static).
16493 if (!VD->hasAttr<AlwaysDestroyAttr>())
16494 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16495
16496 // TODO: this should be re-enabled for static locals by !CXAAtExit
16497 if (!VD->isStaticLocal())
16498 Diag(VD->getLocation(), diag::warn_global_destructor);
16499}
16500
16502 QualType DeclInitType, MultiExprArg ArgsPtr,
16503 SourceLocation Loc,
16504 SmallVectorImpl<Expr *> &ConvertedArgs,
16505 bool AllowExplicit,
16506 bool IsListInitialization) {
16507 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16508 unsigned NumArgs = ArgsPtr.size();
16509 Expr **Args = ArgsPtr.data();
16510
16511 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16512 unsigned NumParams = Proto->getNumParams();
16513
16514 // If too few arguments are available, we'll fill in the rest with defaults.
16515 if (NumArgs < NumParams)
16516 ConvertedArgs.reserve(NumParams);
16517 else
16518 ConvertedArgs.reserve(NumArgs);
16519
16520 VariadicCallType CallType = Proto->isVariadic()
16523 SmallVector<Expr *, 8> AllArgs;
16525 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16526 CallType, AllowExplicit, IsListInitialization);
16527 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16528
16529 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16530
16531 CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),
16532 Proto, Loc);
16533
16534 return Invalid;
16535}
16536
16538 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16539 return typeAwareAllocationModeFromBool(SeenTypedOperators);
16540}
16541
16544 QualType DeallocType, SourceLocation Loc) {
16545 if (DeallocType.isNull())
16546 return nullptr;
16547
16548 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16549 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16550 return nullptr;
16551
16552 if (FnDecl->isVariadic())
16553 return nullptr;
16554
16555 unsigned NumParams = FnDecl->getNumParams();
16556 constexpr unsigned RequiredParameterCount =
16558 // A usual deallocation function has no placement parameters
16559 if (NumParams != RequiredParameterCount)
16560 return nullptr;
16561
16562 // A type aware allocation is only usual if the only dependent parameter is
16563 // the first parameter.
16564 if (llvm::any_of(FnDecl->parameters().drop_front(),
16565 [](const ParmVarDecl *ParamDecl) {
16566 return ParamDecl->getType()->isDependentType();
16567 }))
16568 return nullptr;
16569
16570 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);
16571 if (SpecializedTypeIdentity.isNull())
16572 return nullptr;
16573
16575 ArgTypes.reserve(NumParams);
16576
16577 // The first parameter to a type aware operator delete is by definition the
16578 // type-identity argument, so we explicitly set this to the target
16579 // type-identity type, the remaining usual parameters should then simply match
16580 // the type declared in the function template.
16581 ArgTypes.push_back(SpecializedTypeIdentity);
16582 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16583 ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());
16584
16586 QualType ExpectedFunctionType =
16587 Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
16590 if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,
16592 return nullptr;
16593 return Result;
16594}
16595
16596static inline bool
16598 const FunctionDecl *FnDecl) {
16599 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16600 if (isa<NamespaceDecl>(DC)) {
16601 return SemaRef.Diag(FnDecl->getLocation(),
16602 diag::err_operator_new_delete_declared_in_namespace)
16603 << FnDecl->getDeclName();
16604 }
16605
16606 if (isa<TranslationUnitDecl>(DC) &&
16607 FnDecl->getStorageClass() == SC_Static) {
16608 return SemaRef.Diag(FnDecl->getLocation(),
16609 diag::err_operator_new_delete_declared_static)
16610 << FnDecl->getDeclName();
16611 }
16612
16613 return false;
16614}
16615
16617 const PointerType *PtrTy) {
16618 auto &Ctx = SemaRef.Context;
16619 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16620 PtrQuals.removeAddressSpace();
16622 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16623}
16624
16626
16628 const FunctionDecl *FD,
16629 bool *WasMalformed) {
16630 const Decl *MalformedDecl = nullptr;
16631 if (FD->getNumParams() > 0 &&
16632 SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
16633 /*TypeArgument=*/nullptr, &MalformedDecl))
16634 return true;
16635
16636 if (!MalformedDecl)
16637 return false;
16638
16639 if (WasMalformed)
16640 *WasMalformed = true;
16641
16642 return true;
16643}
16644
16646 auto *RD = Type->getAsCXXRecordDecl();
16647 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16648 RD->getIdentifier()->isStr("destroying_delete_t");
16649}
16650
16652 const FunctionDecl *FD) {
16653 // C++ P0722:
16654 // Within a class C, a single object deallocation function with signature
16655 // (T, std::destroying_delete_t, <more params>)
16656 // is a destroying operator delete.
16657 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16658 SemaRef, FD, /*WasMalformed=*/nullptr);
16659 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16660 return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&
16661 FD->getNumParams() > DestroyingDeleteIdx &&
16662 isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
16663}
16664
16666 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16667 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16668 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16669 auto NormalizeType = [&SemaRef](QualType T) {
16670 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16671 // The operator is valid on any address space for OpenCL.
16672 // Drop address space from actual and expected result types.
16673 if (const auto PtrTy = T->template getAs<PointerType>())
16674 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16675 }
16676 return SemaRef.Context.getCanonicalType(T);
16677 };
16678
16679 const unsigned NumParams = FnDecl->getNumParams();
16680 unsigned FirstNonTypeParam = 0;
16681 bool MalformedTypeIdentity = false;
16682 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16683 SemaRef, FnDecl, &MalformedTypeIdentity);
16684 unsigned MinimumMandatoryArgumentCount = 1;
16685 unsigned SizeParameterIndex = 0;
16686 if (IsPotentiallyTypeAware) {
16687 // We don't emit this diagnosis for template instantiations as we will
16688 // have already emitted it for the original template declaration.
16689 if (!FnDecl->isTemplateInstantiation())
16690 SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);
16691
16692 if (OperatorKind == AllocationOperatorKind::New) {
16693 SizeParameterIndex = 1;
16694 MinimumMandatoryArgumentCount =
16696 } else {
16697 SizeParameterIndex = 2;
16698 MinimumMandatoryArgumentCount =
16700 }
16701 FirstNonTypeParam = 1;
16702 }
16703
16704 bool IsPotentiallyDestroyingDelete =
16706
16707 if (IsPotentiallyDestroyingDelete) {
16708 ++MinimumMandatoryArgumentCount;
16709 ++SizeParameterIndex;
16710 }
16711
16712 if (NumParams < MinimumMandatoryArgumentCount)
16713 return SemaRef.Diag(FnDecl->getLocation(),
16714 diag::err_operator_new_delete_too_few_parameters)
16715 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16716 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16717
16718 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16719 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);
16720 if (ParamDecl->hasDefaultArg())
16721 return SemaRef.Diag(FnDecl->getLocation(),
16722 diag::err_operator_new_default_arg)
16723 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16724 }
16725
16726 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16727 QualType CanResultType = NormalizeType(FnType->getReturnType());
16728 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16729 QualType CanExpectedSizeOrAddressParamType =
16730 NormalizeType(ExpectedSizeOrAddressParamType);
16731
16732 // Check that the result type is what we expect.
16733 if (CanResultType != CanExpectedResultType) {
16734 // Reject even if the type is dependent; an operator delete function is
16735 // required to have a non-dependent result type.
16736 return SemaRef.Diag(
16737 FnDecl->getLocation(),
16738 CanResultType->isDependentType()
16739 ? diag::err_operator_new_delete_dependent_result_type
16740 : diag::err_operator_new_delete_invalid_result_type)
16741 << FnDecl->getDeclName() << ExpectedResultType;
16742 }
16743
16744 // A function template must have at least 2 parameters.
16745 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16746 return SemaRef.Diag(FnDecl->getLocation(),
16747 diag::err_operator_new_delete_template_too_few_parameters)
16748 << FnDecl->getDeclName();
16749
16750 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16751 auto FallbackType) -> bool {
16752 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);
16753 if (ExpectedType.isNull()) {
16754 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
16755 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16756 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16757 << ParamDecl->getSourceRange();
16758 }
16759 CanQualType CanExpectedTy =
16760 NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));
16761 auto ActualParamType =
16762 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16763 if (ActualParamType == CanExpectedTy)
16764 return false;
16765 unsigned Diagnostic = ActualParamType->isDependentType()
16766 ? DependentParamTypeDiag
16767 : InvalidParamTypeDiag;
16768 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)
16769 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16770 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16771 << FallbackType << ParamDecl->getSourceRange();
16772 };
16773
16774 // Check that the first parameter type is what we expect.
16775 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16776 return true;
16777
16778 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16779
16780 // If the first parameter type is not a type-identity we're done, otherwise
16781 // we need to ensure the size and alignment parameters have the correct type
16782 if (!IsPotentiallyTypeAware)
16783 return false;
16784
16785 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16786 return true;
16787 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16788 CanQualType StdAlignValT =
16789 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(StdAlignValTDecl)
16790 : CanQualType();
16791 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16792 return true;
16793
16795 return MalformedTypeIdentity;
16796}
16797
16798static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16799 // C++ [basic.stc.dynamic.allocation]p1:
16800 // A program is ill-formed if an allocation function is declared in a
16801 // namespace scope other than global scope or declared static in global
16802 // scope.
16803 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16804 return true;
16805
16806 CanQualType SizeTy =
16807 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16808
16809 // C++ [basic.stc.dynamic.allocation]p1:
16810 // The return type shall be void*. The first parameter shall have type
16811 // std::size_t.
16813 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,
16814 SizeTy, diag::err_operator_new_dependent_param_type,
16815 diag::err_operator_new_param_type);
16816}
16817
16818static bool
16820 // C++ [basic.stc.dynamic.deallocation]p1:
16821 // A program is ill-formed if deallocation functions are declared in a
16822 // namespace scope other than global scope or declared static in global
16823 // scope.
16824 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16825 return true;
16826
16827 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16828 auto ConstructDestroyingDeleteAddressType = [&]() {
16829 assert(MD);
16830 return SemaRef.Context.getPointerType(
16831 SemaRef.Context.getCanonicalTagType(MD->getParent()));
16832 };
16833
16834 // C++ P2719: A destroying operator delete cannot be type aware
16835 // so for QoL we actually check for this explicitly by considering
16836 // an destroying-delete appropriate address type and the presence of
16837 // any parameter of type destroying_delete_t as an erroneous attempt
16838 // to declare a type aware destroying delete, rather than emitting a
16839 // pile of incorrect parameter type errors.
16841 SemaRef, MD, /*WasMalformed=*/nullptr)) {
16842 QualType AddressParamType =
16843 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());
16844 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16845 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16846 // The address parameter type implies an author trying to construct a
16847 // type aware destroying delete, so we'll see if we can find a parameter
16848 // of type `std::destroying_delete_t`, and if we find it we'll report
16849 // this as being an attempt at a type aware destroying delete just stop
16850 // here. If we don't do this, the resulting incorrect parameter ordering
16851 // results in a pile mismatched argument type errors that don't explain
16852 // the core problem.
16853 for (auto Param : MD->parameters()) {
16854 if (isDestroyingDeleteT(Param->getType())) {
16855 SemaRef.Diag(MD->getLocation(),
16856 diag::err_type_aware_destroying_operator_delete)
16857 << Param->getSourceRange();
16858 return true;
16859 }
16860 }
16861 }
16862 }
16863
16864 // C++ P0722:
16865 // Within a class C, the first parameter of a destroying operator delete
16866 // shall be of type C *. The first parameter of any other deallocation
16867 // function shall be of type void *.
16868 CanQualType ExpectedAddressParamType =
16869 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)
16870 ? SemaRef.Context.getPointerType(
16871 SemaRef.Context.getCanonicalTagType(MD->getParent()))
16872 : SemaRef.Context.VoidPtrTy;
16873
16874 // C++ [basic.stc.dynamic.deallocation]p2:
16875 // Each deallocation function shall return void
16877 SemaRef, FnDecl, AllocationOperatorKind::Delete,
16878 SemaRef.Context.VoidTy, ExpectedAddressParamType,
16879 diag::err_operator_delete_dependent_param_type,
16880 diag::err_operator_delete_param_type))
16881 return true;
16882
16883 // C++ P0722:
16884 // A destroying operator delete shall be a usual deallocation function.
16885 if (MD && !MD->getParent()->isDependentContext() &&
16887 if (!SemaRef.isUsualDeallocationFunction(MD)) {
16888 SemaRef.Diag(MD->getLocation(),
16889 diag::err_destroying_operator_delete_not_usual);
16890 return true;
16891 }
16892 }
16893
16894 return false;
16895}
16896
16898 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16899 "Expected an overloaded operator declaration");
16900
16902
16903 // C++ [over.oper]p5:
16904 // The allocation and deallocation functions, operator new,
16905 // operator new[], operator delete and operator delete[], are
16906 // described completely in 3.7.3. The attributes and restrictions
16907 // found in the rest of this subclause do not apply to them unless
16908 // explicitly stated in 3.7.3.
16909 if (Op == OO_Delete || Op == OO_Array_Delete)
16910 return CheckOperatorDeleteDeclaration(*this, FnDecl);
16911
16912 if (Op == OO_New || Op == OO_Array_New)
16913 return CheckOperatorNewDeclaration(*this, FnDecl);
16914
16915 // C++ [over.oper]p7:
16916 // An operator function shall either be a member function or
16917 // be a non-member function and have at least one parameter
16918 // whose type is a class, a reference to a class, an enumeration,
16919 // or a reference to an enumeration.
16920 // Note: Before C++23, a member function could not be static. The only member
16921 // function allowed to be static is the call operator function.
16922 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16923 if (MethodDecl->isStatic()) {
16924 if (Op == OO_Call || Op == OO_Subscript)
16925 Diag(FnDecl->getLocation(),
16926 (LangOpts.CPlusPlus23
16927 ? diag::warn_cxx20_compat_operator_overload_static
16928 : diag::ext_operator_overload_static))
16929 << FnDecl;
16930 else
16931 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16932 << FnDecl;
16933 }
16934 } else {
16935 bool ClassOrEnumParam = false;
16936 for (auto *Param : FnDecl->parameters()) {
16937 QualType ParamType = Param->getType().getNonReferenceType();
16938 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16939 ParamType->isEnumeralType()) {
16940 ClassOrEnumParam = true;
16941 break;
16942 }
16943 }
16944
16945 if (!ClassOrEnumParam)
16946 return Diag(FnDecl->getLocation(),
16947 diag::err_operator_overload_needs_class_or_enum)
16948 << FnDecl->getDeclName();
16949 }
16950
16951 // C++ [over.oper]p8:
16952 // An operator function cannot have default arguments (8.3.6),
16953 // except where explicitly stated below.
16954 //
16955 // Only the function-call operator (C++ [over.call]p1) and the subscript
16956 // operator (CWG2507) allow default arguments.
16957 if (Op != OO_Call) {
16958 ParmVarDecl *FirstDefaultedParam = nullptr;
16959 for (auto *Param : FnDecl->parameters()) {
16960 if (Param->hasDefaultArg()) {
16961 FirstDefaultedParam = Param;
16962 break;
16963 }
16964 }
16965 if (FirstDefaultedParam) {
16966 if (Op == OO_Subscript) {
16967 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16968 ? diag::ext_subscript_overload
16969 : diag::error_subscript_overload)
16970 << FnDecl->getDeclName() << 1
16971 << FirstDefaultedParam->getDefaultArgRange();
16972 } else {
16973 return Diag(FirstDefaultedParam->getLocation(),
16974 diag::err_operator_overload_default_arg)
16975 << FnDecl->getDeclName()
16976 << FirstDefaultedParam->getDefaultArgRange();
16977 }
16978 }
16979 }
16980
16981 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16982 { false, false, false }
16983#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16984 , { Unary, Binary, MemberOnly }
16985#include "clang/Basic/OperatorKinds.def"
16986 };
16987
16988 bool CanBeUnaryOperator = OperatorUses[Op][0];
16989 bool CanBeBinaryOperator = OperatorUses[Op][1];
16990 bool MustBeMemberOperator = OperatorUses[Op][2];
16991
16992 // C++ [over.oper]p8:
16993 // [...] Operator functions cannot have more or fewer parameters
16994 // than the number required for the corresponding operator, as
16995 // described in the rest of this subclause.
16996 unsigned NumParams = FnDecl->getNumParams() +
16997 (isa<CXXMethodDecl>(FnDecl) &&
16999 ? 1
17000 : 0);
17001 if (Op != OO_Call && Op != OO_Subscript &&
17002 ((NumParams == 1 && !CanBeUnaryOperator) ||
17003 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17004 (NumParams > 2))) {
17005 // We have the wrong number of parameters.
17006 unsigned ErrorKind;
17007 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17008 ErrorKind = 2; // 2 -> unary or binary.
17009 } else if (CanBeUnaryOperator) {
17010 ErrorKind = 0; // 0 -> unary
17011 } else {
17012 assert(CanBeBinaryOperator &&
17013 "All non-call overloaded operators are unary or binary!");
17014 ErrorKind = 1; // 1 -> binary
17015 }
17016 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
17017 << FnDecl->getDeclName() << NumParams << ErrorKind;
17018 }
17019
17020 if (Op == OO_Subscript && NumParams != 2) {
17021 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
17022 ? diag::ext_subscript_overload
17023 : diag::error_subscript_overload)
17024 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17025 }
17026
17027 // Overloaded operators other than operator() and operator[] cannot be
17028 // variadic.
17029 if (Op != OO_Call &&
17030 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17031 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
17032 << FnDecl->getDeclName();
17033 }
17034
17035 // Some operators must be member functions.
17036 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
17037 return Diag(FnDecl->getLocation(),
17038 diag::err_operator_overload_must_be_member)
17039 << FnDecl->getDeclName();
17040 }
17041
17042 // C++ [over.inc]p1:
17043 // The user-defined function called operator++ implements the
17044 // prefix and postfix ++ operator. If this function is a member
17045 // function with no parameters, or a non-member function with one
17046 // parameter of class or enumeration type, it defines the prefix
17047 // increment operator ++ for objects of that type. If the function
17048 // is a member function with one parameter (which shall be of type
17049 // int) or a non-member function with two parameters (the second
17050 // of which shall be of type int), it defines the postfix
17051 // increment operator ++ for objects of that type.
17052 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17053 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
17054 QualType ParamType = LastParam->getType();
17055
17056 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
17057 !ParamType->isDependentType())
17058 return Diag(LastParam->getLocation(),
17059 diag::err_operator_overload_post_incdec_must_be_int)
17060 << LastParam->getType() << (Op == OO_MinusMinus);
17061 }
17062
17063 return false;
17064}
17065
17066static bool
17068 FunctionTemplateDecl *TpDecl) {
17069 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17070
17071 // Must have one or two template parameters.
17072 if (TemplateParams->size() == 1) {
17073 NonTypeTemplateParmDecl *PmDecl =
17074 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
17075
17076 // The template parameter must be a char parameter pack.
17077 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17078 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
17079 return false;
17080
17081 // C++20 [over.literal]p5:
17082 // A string literal operator template is a literal operator template
17083 // whose template-parameter-list comprises a single non-type
17084 // template-parameter of class type.
17085 //
17086 // As a DR resolution, we also allow placeholders for deduced class
17087 // template specializations.
17088 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17089 !PmDecl->isTemplateParameterPack() &&
17090 (PmDecl->getType()->isRecordType() ||
17091 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17092 return false;
17093 } else if (TemplateParams->size() == 2) {
17094 TemplateTypeParmDecl *PmType =
17095 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
17096 NonTypeTemplateParmDecl *PmArgs =
17097 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
17098
17099 // The second template parameter must be a parameter pack with the
17100 // first template parameter as its type.
17101 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17102 PmArgs->isTemplateParameterPack()) {
17103 if (const auto *TArgs =
17104 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17105 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17106 TArgs->getIndex() == PmType->getIndex()) {
17107 if (!SemaRef.inTemplateInstantiation())
17108 SemaRef.Diag(TpDecl->getLocation(),
17109 diag::ext_string_literal_operator_template);
17110 return false;
17111 }
17112 }
17113 }
17114
17115 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17116 diag::err_literal_operator_template)
17117 << TpDecl->getTemplateParameters()->getSourceRange();
17118 return true;
17119}
17120
17122 if (isa<CXXMethodDecl>(FnDecl)) {
17123 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
17124 << FnDecl->getDeclName();
17125 return true;
17126 }
17127
17128 if (FnDecl->isExternC()) {
17129 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
17130 if (const LinkageSpecDecl *LSD =
17131 FnDecl->getDeclContext()->getExternCContext())
17132 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
17133 return true;
17134 }
17135
17136 // This might be the definition of a literal operator template.
17138
17139 // This might be a specialization of a literal operator template.
17140 if (!TpDecl)
17141 TpDecl = FnDecl->getPrimaryTemplate();
17142
17143 // template <char...> type operator "" name() and
17144 // template <class T, T...> type operator "" name() are the only valid
17145 // template signatures, and the only valid signatures with no parameters.
17146 //
17147 // C++20 also allows template <SomeClass T> type operator "" name().
17148 if (TpDecl) {
17149 if (FnDecl->param_size() != 0) {
17150 Diag(FnDecl->getLocation(),
17151 diag::err_literal_operator_template_with_params);
17152 return true;
17153 }
17154
17156 return true;
17157
17158 } else if (FnDecl->param_size() == 1) {
17159 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
17160
17161 QualType ParamType = Param->getType().getUnqualifiedType();
17162
17163 // Only unsigned long long int, long double, any character type, and const
17164 // char * are allowed as the only parameters.
17165 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
17166 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
17167 Context.hasSameType(ParamType, Context.CharTy) ||
17168 Context.hasSameType(ParamType, Context.WideCharTy) ||
17169 Context.hasSameType(ParamType, Context.Char8Ty) ||
17170 Context.hasSameType(ParamType, Context.Char16Ty) ||
17171 Context.hasSameType(ParamType, Context.Char32Ty)) {
17172 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17173 QualType InnerType = Ptr->getPointeeType();
17174
17175 // Pointer parameter must be a const char *.
17176 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
17177 Context.CharTy) &&
17178 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17179 Diag(Param->getSourceRange().getBegin(),
17180 diag::err_literal_operator_param)
17181 << ParamType << "'const char *'" << Param->getSourceRange();
17182 return true;
17183 }
17184
17185 } else if (ParamType->isRealFloatingType()) {
17186 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17187 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17188 return true;
17189
17190 } else if (ParamType->isIntegerType()) {
17191 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
17192 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17193 return true;
17194
17195 } else {
17196 Diag(Param->getSourceRange().getBegin(),
17197 diag::err_literal_operator_invalid_param)
17198 << ParamType << Param->getSourceRange();
17199 return true;
17200 }
17201
17202 } else if (FnDecl->param_size() == 2) {
17203 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17204
17205 // First, verify that the first parameter is correct.
17206
17207 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17208
17209 // Two parameter function must have a pointer to const as a
17210 // first parameter; let's strip those qualifiers.
17211 const PointerType *PT = FirstParamType->getAs<PointerType>();
17212
17213 if (!PT) {
17214 Diag((*Param)->getSourceRange().getBegin(),
17215 diag::err_literal_operator_param)
17216 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17217 return true;
17218 }
17219
17220 QualType PointeeType = PT->getPointeeType();
17221 // First parameter must be const
17222 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17223 Diag((*Param)->getSourceRange().getBegin(),
17224 diag::err_literal_operator_param)
17225 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17226 return true;
17227 }
17228
17229 QualType InnerType = PointeeType.getUnqualifiedType();
17230 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17231 // const char32_t* are allowed as the first parameter to a two-parameter
17232 // function
17233 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
17234 Context.hasSameType(InnerType, Context.WideCharTy) ||
17235 Context.hasSameType(InnerType, Context.Char8Ty) ||
17236 Context.hasSameType(InnerType, Context.Char16Ty) ||
17237 Context.hasSameType(InnerType, Context.Char32Ty))) {
17238 Diag((*Param)->getSourceRange().getBegin(),
17239 diag::err_literal_operator_param)
17240 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17241 return true;
17242 }
17243
17244 // Move on to the second and final parameter.
17245 ++Param;
17246
17247 // The second parameter must be a std::size_t.
17248 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17249 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
17250 Diag((*Param)->getSourceRange().getBegin(),
17251 diag::err_literal_operator_param)
17252 << SecondParamType << Context.getSizeType()
17253 << (*Param)->getSourceRange();
17254 return true;
17255 }
17256 } else {
17257 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
17258 return true;
17259 }
17260
17261 // Parameters are good.
17262
17263 // A parameter-declaration-clause containing a default argument is not
17264 // equivalent to any of the permitted forms.
17265 for (auto *Param : FnDecl->parameters()) {
17266 if (Param->hasDefaultArg()) {
17267 Diag(Param->getDefaultArgRange().getBegin(),
17268 diag::err_literal_operator_default_argument)
17269 << Param->getDefaultArgRange();
17270 break;
17271 }
17272 }
17273
17274 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17277 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
17278 // C++23 [usrlit.suffix]p1:
17279 // Literal suffix identifiers that do not start with an underscore are
17280 // reserved for future standardization. Literal suffix identifiers that
17281 // contain a double underscore __ are reserved for use by C++
17282 // implementations.
17283 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
17284 << static_cast<int>(Status)
17286 }
17287
17288 return false;
17289}
17290
17292 Expr *LangStr,
17293 SourceLocation LBraceLoc) {
17294 StringLiteral *Lit = cast<StringLiteral>(LangStr);
17295 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17296
17297 StringRef Lang = Lit->getString();
17299 if (Lang == "C")
17301 else if (Lang == "C++")
17303 else {
17304 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
17305 << LangStr->getSourceRange();
17306 return nullptr;
17307 }
17308
17309 // FIXME: Add all the various semantics of linkage specifications
17310
17312 LangStr->getExprLoc(), Language,
17313 LBraceLoc.isValid());
17314
17315 /// C++ [module.unit]p7.2.3
17316 /// - Otherwise, if the declaration
17317 /// - ...
17318 /// - ...
17319 /// - appears within a linkage-specification,
17320 /// it is attached to the global module.
17321 ///
17322 /// If the declaration is already in global module fragment, we don't
17323 /// need to attach it again.
17324 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17325 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
17326 D->setLocalOwningModule(GlobalModule);
17327 }
17328
17329 CurContext->addDecl(D);
17330 PushDeclContext(S, D);
17331 return D;
17332}
17333
17335 Decl *LinkageSpec,
17336 SourceLocation RBraceLoc) {
17337 if (RBraceLoc.isValid()) {
17338 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
17339 LSDecl->setRBraceLoc(RBraceLoc);
17340 }
17341
17342 // If the current module doesn't has Parent, it implies that the
17343 // LinkageSpec isn't in the module created by itself. So we don't
17344 // need to pop it.
17345 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17346 getCurrentModule()->isImplicitGlobalModule() &&
17347 getCurrentModule()->Parent)
17348 PopImplicitGlobalModuleFragment();
17349
17351 return LinkageSpec;
17352}
17353
17355 const ParsedAttributesView &AttrList,
17356 SourceLocation SemiLoc) {
17357 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
17358 // Attribute declarations appertain to empty declaration so we handle
17359 // them here.
17360 ProcessDeclAttributeList(S, ED, AttrList);
17361
17362 CurContext->addDecl(ED);
17363 return ED;
17364}
17365
17367 SourceLocation StartLoc,
17368 SourceLocation Loc,
17369 const IdentifierInfo *Name) {
17370 bool Invalid = false;
17371 QualType ExDeclType = TInfo->getType();
17372
17373 // Arrays and functions decay.
17374 if (ExDeclType->isArrayType())
17375 ExDeclType = Context.getArrayDecayedType(ExDeclType);
17376 else if (ExDeclType->isFunctionType())
17377 ExDeclType = Context.getPointerType(ExDeclType);
17378
17379 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17380 // The exception-declaration shall not denote a pointer or reference to an
17381 // incomplete type, other than [cv] void*.
17382 // N2844 forbids rvalue references.
17383 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17384 Diag(Loc, diag::err_catch_rvalue_ref);
17385 Invalid = true;
17386 }
17387
17388 if (ExDeclType->isVariablyModifiedType()) {
17389 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
17390 Invalid = true;
17391 }
17392
17393 QualType BaseType = ExDeclType;
17394 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17395 unsigned DK = diag::err_catch_incomplete;
17396 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17397 BaseType = Ptr->getPointeeType();
17398 Mode = 1;
17399 DK = diag::err_catch_incomplete_ptr;
17400 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17401 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17402 BaseType = Ref->getPointeeType();
17403 Mode = 2;
17404 DK = diag::err_catch_incomplete_ref;
17405 }
17406 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17407 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
17408 Invalid = true;
17409
17410 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17411 Diag(Loc, diag::err_wasm_reftype_tc) << 1;
17412 Invalid = true;
17413 }
17414
17415 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17416 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17417 Invalid = true;
17418 }
17419
17420 if (!Invalid && !ExDeclType->isDependentType() &&
17421 RequireNonAbstractType(Loc, ExDeclType,
17422 diag::err_abstract_type_in_decl,
17424 Invalid = true;
17425
17426 // Only the non-fragile NeXT runtime currently supports C++ catches
17427 // of ObjC types, and no runtime supports catching ObjC types by value.
17428 if (!Invalid && getLangOpts().ObjC) {
17429 QualType T = ExDeclType;
17430 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17431 T = RT->getPointeeType();
17432
17433 if (T->isObjCObjectType()) {
17434 Diag(Loc, diag::err_objc_object_catch);
17435 Invalid = true;
17436 } else if (T->isObjCObjectPointerType()) {
17437 // FIXME: should this be a test for macosx-fragile specifically?
17439 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
17440 }
17441 }
17442
17443 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
17444 ExDeclType, TInfo, SC_None);
17445 ExDecl->setExceptionVariable(true);
17446
17447 // In ARC, infer 'retaining' for variables of retainable type.
17448 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
17449 Invalid = true;
17450
17451 if (!Invalid && !ExDeclType->isDependentType()) {
17452 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17453 // Insulate this from anything else we might currently be parsing.
17456
17457 // C++ [except.handle]p16:
17458 // The object declared in an exception-declaration or, if the
17459 // exception-declaration does not specify a name, a temporary (12.2) is
17460 // copy-initialized (8.5) from the exception object. [...]
17461 // The object is destroyed when the handler exits, after the destruction
17462 // of any automatic objects initialized within the handler.
17463 //
17464 // We just pretend to initialize the object with itself, then make sure
17465 // it can be destroyed later.
17466 QualType initType = Context.getExceptionObjectType(ExDeclType);
17467
17468 InitializedEntity entity =
17470 InitializationKind initKind =
17472
17473 Expr *opaqueValue =
17474 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17475 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17476 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
17477 if (result.isInvalid())
17478 Invalid = true;
17479 else {
17480 // If the constructor used was non-trivial, set this as the
17481 // "initializer".
17482 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17483 if (!construct->getConstructor()->isTrivial()) {
17484 Expr *init = MaybeCreateExprWithCleanups(construct);
17485 ExDecl->setInit(init);
17486 }
17487
17488 // And make sure it's destructable.
17489 FinalizeVarWithDestructor(ExDecl, ClassDecl);
17490 }
17491 }
17492 }
17493
17494 if (Invalid)
17495 ExDecl->setInvalidDecl();
17496
17497 return ExDecl;
17498}
17499
17502 bool Invalid = D.isInvalidType();
17503
17504 // Check for unexpanded parameter packs.
17507 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17508 D.getIdentifierLoc());
17509 Invalid = true;
17510 }
17511
17512 const IdentifierInfo *II = D.getIdentifier();
17513 if (NamedDecl *PrevDecl =
17516 // The scope should be freshly made just for us. There is just no way
17517 // it contains any previous declaration, except for function parameters in
17518 // a function-try-block's catch statement.
17519 assert(!S->isDeclScope(PrevDecl));
17520 if (isDeclInScope(PrevDecl, CurContext, S)) {
17521 Diag(D.getIdentifierLoc(), diag::err_redefinition)
17522 << D.getIdentifier();
17523 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17524 Invalid = true;
17525 } else if (PrevDecl->isTemplateParameter())
17526 // Maybe we will complain about the shadowed template parameter.
17528 }
17529
17530 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17531 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17532 << D.getCXXScopeSpec().getRange();
17533 Invalid = true;
17534 }
17535
17537 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17538 if (Invalid)
17539 ExDecl->setInvalidDecl();
17540
17541 // Add the exception declaration into this scope.
17542 if (II)
17543 PushOnScopeChains(ExDecl, S);
17544 else
17545 CurContext->addDecl(ExDecl);
17546
17547 ProcessDeclAttributes(S, ExDecl, D);
17548 return ExDecl;
17549}
17550
17552 Expr *AssertExpr,
17553 Expr *AssertMessageExpr,
17554 SourceLocation RParenLoc) {
17556 return nullptr;
17557
17558 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17559 AssertMessageExpr, RParenLoc, false);
17560}
17561
17562static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17563 switch (BTK) {
17564 case BuiltinType::Char_S:
17565 case BuiltinType::Char_U:
17566 break;
17567 case BuiltinType::Char8:
17568 OS << "u8";
17569 break;
17570 case BuiltinType::Char16:
17571 OS << 'u';
17572 break;
17573 case BuiltinType::Char32:
17574 OS << 'U';
17575 break;
17576 case BuiltinType::WChar_S:
17577 case BuiltinType::WChar_U:
17578 OS << 'L';
17579 break;
17580 default:
17581 llvm_unreachable("Non-character type");
17582 }
17583}
17584
17585/// Convert character's value, interpreted as a code unit, to a string.
17586/// The value needs to be zero-extended to 32-bits.
17587/// FIXME: This assumes Unicode literal encodings
17588static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17589 unsigned TyWidth,
17590 SmallVectorImpl<char> &Str) {
17591 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17592 char *Ptr = Arr;
17593 BuiltinType::Kind K = BTy->getKind();
17594 llvm::raw_svector_ostream OS(Str);
17595
17596 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17597 // other types.
17598 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17599 K == BuiltinType::Char8 || Value <= 0x7F) {
17600 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17601 if (!Escaped.empty())
17602 EscapeStringForDiagnostic(Escaped, Str);
17603 else
17604 OS << static_cast<char>(Value);
17605 return;
17606 }
17607
17608 switch (K) {
17609 case BuiltinType::Char16:
17610 case BuiltinType::Char32:
17611 case BuiltinType::WChar_S:
17612 case BuiltinType::WChar_U: {
17613 if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17614 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17615 else
17616 OS << "\\x"
17617 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17618 break;
17619 }
17620 default:
17621 llvm_unreachable("Non-character type is passed");
17622 }
17623}
17624
17625/// Convert \V to a string we can present to the user in a diagnostic
17626/// \T is the type of the expression that has been evaluated into \V
17629 ASTContext &Context) {
17630 if (!V.hasValue())
17631 return false;
17632
17633 switch (V.getKind()) {
17635 if (T->isBooleanType()) {
17636 // Bools are reduced to ints during evaluation, but for
17637 // diagnostic purposes we want to print them as
17638 // true or false.
17639 int64_t BoolValue = V.getInt().getExtValue();
17640 assert((BoolValue == 0 || BoolValue == 1) &&
17641 "Bool type, but value is not 0 or 1");
17642 llvm::raw_svector_ostream OS(Str);
17643 OS << (BoolValue ? "true" : "false");
17644 } else {
17645 llvm::raw_svector_ostream OS(Str);
17646 // Same is true for chars.
17647 // We want to print the character representation for textual types
17648 const auto *BTy = T->getAs<BuiltinType>();
17649 if (BTy) {
17650 switch (BTy->getKind()) {
17651 case BuiltinType::Char_S:
17652 case BuiltinType::Char_U:
17653 case BuiltinType::Char8:
17654 case BuiltinType::Char16:
17655 case BuiltinType::Char32:
17656 case BuiltinType::WChar_S:
17657 case BuiltinType::WChar_U: {
17658 unsigned TyWidth = Context.getIntWidth(T);
17659 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17660 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17661 WriteCharTypePrefix(BTy->getKind(), OS);
17662 OS << '\'';
17663 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17664 OS << "' (0x"
17665 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17666 /*Upper=*/true)
17667 << ", " << V.getInt() << ')';
17668 return true;
17669 }
17670 default:
17671 break;
17672 }
17673 }
17674 V.getInt().toString(Str);
17675 }
17676
17677 break;
17678
17680 V.getFloat().toString(Str);
17681 break;
17682
17684 if (V.isNullPointer()) {
17685 llvm::raw_svector_ostream OS(Str);
17686 OS << "nullptr";
17687 } else
17688 return false;
17689 break;
17690
17692 llvm::raw_svector_ostream OS(Str);
17693 OS << '(';
17694 V.getComplexFloatReal().toString(Str);
17695 OS << " + ";
17696 V.getComplexFloatImag().toString(Str);
17697 OS << "i)";
17698 } break;
17699
17701 llvm::raw_svector_ostream OS(Str);
17702 OS << '(';
17703 V.getComplexIntReal().toString(Str);
17704 OS << " + ";
17705 V.getComplexIntImag().toString(Str);
17706 OS << "i)";
17707 } break;
17708
17709 default:
17710 return false;
17711 }
17712
17713 return true;
17714}
17715
17716/// Some Expression types are not useful to print notes about,
17717/// e.g. literals and values that have already been expanded
17718/// before such as int-valued template parameters.
17719static bool UsefulToPrintExpr(const Expr *E) {
17720 E = E->IgnoreParenImpCasts();
17721 // Literals are pretty easy for humans to understand.
17724 return false;
17725
17726 // These have been substituted from template parameters
17727 // and appear as literals in the static assert error.
17729 return false;
17730
17731 // -5 is also simple to understand.
17732 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17733 return UsefulToPrintExpr(UnaryOp->getSubExpr());
17734
17735 // Only print nested arithmetic operators.
17736 if (const auto *BO = dyn_cast<BinaryOperator>(E))
17737 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17738 BO->isBitwiseOp());
17739
17740 return true;
17741}
17742
17744 if (const auto *Op = dyn_cast<BinaryOperator>(E);
17745 Op && Op->getOpcode() != BO_LOr) {
17746 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17747 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17748
17749 // Ignore comparisons of boolean expressions with a boolean literal.
17750 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17751 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17752 return;
17753
17754 // Don't print obvious expressions.
17755 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17756 return;
17757
17758 struct {
17759 const clang::Expr *Cond;
17761 SmallString<12> ValueString;
17762 bool Print;
17763 } DiagSides[2] = {{LHS, Expr::EvalResult(), {}, false},
17764 {RHS, Expr::EvalResult(), {}, false}};
17765 for (auto &DiagSide : DiagSides) {
17766 const Expr *Side = DiagSide.Cond;
17767
17768 Side->EvaluateAsRValue(DiagSide.Result, Context, true);
17769
17770 DiagSide.Print = ConvertAPValueToString(
17771 DiagSide.Result.Val, Side->getType(), DiagSide.ValueString, Context);
17772 }
17773 if (DiagSides[0].Print && DiagSides[1].Print) {
17774 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17775 << DiagSides[0].ValueString << Op->getOpcodeStr()
17776 << DiagSides[1].ValueString << Op->getSourceRange();
17777 }
17778 } else {
17780 }
17781}
17782
17783template <typename ResultType>
17784static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17785 ResultType &Result, ASTContext &Ctx,
17787 bool ErrorOnInvalidMessage) {
17788
17789 assert(Message);
17790 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17791 "can't evaluate a dependant static assert message");
17792
17793 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17794 assert(SL->isUnevaluated() && "expected an unevaluated string");
17795 if constexpr (std::is_same_v<APValue, ResultType>) {
17796 Result =
17797 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17798 const ConstantArrayType *CAT =
17799 SemaRef.getASTContext().getAsConstantArrayType(SL->getType());
17800 assert(CAT && "string literal isn't an array");
17801 QualType CharType = CAT->getElementType();
17802 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),
17803 CharType->isUnsignedIntegerType());
17804 for (unsigned I = 0; I < SL->getLength(); I++) {
17805 Value = SL->getCodeUnit(I);
17806 Result.getArrayInitializedElt(I) = APValue(Value);
17807 }
17808 } else {
17809 Result.assign(SL->getString().begin(), SL->getString().end());
17810 }
17811 return true;
17812 }
17813
17814 SourceLocation Loc = Message->getBeginLoc();
17815 QualType T = Message->getType().getNonReferenceType();
17816 auto *RD = T->getAsCXXRecordDecl();
17817 if (!RD) {
17818 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;
17819 return false;
17820 }
17821
17822 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17824 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17825 SemaRef.LookupQualifiedName(MemberLookup, RD);
17826 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17828 if (MemberLookup.empty())
17829 return std::nullopt;
17830 return std::move(MemberLookup);
17831 };
17832
17833 std::optional<LookupResult> SizeMember = FindMember("size");
17834 std::optional<LookupResult> DataMember = FindMember("data");
17835 if (!SizeMember || !DataMember) {
17836 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)
17837 << EvalContext
17838 << ((!SizeMember && !DataMember) ? 2
17839 : !SizeMember ? 0
17840 : 1);
17841 return false;
17842 }
17843
17844 auto BuildExpr = [&](LookupResult &LR) {
17846 Message, Message->getType(), Message->getBeginLoc(), false,
17847 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17848 if (Res.isInvalid())
17849 return ExprError();
17850 Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,
17851 false, true);
17852 if (Res.isInvalid())
17853 return ExprError();
17854 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17855 return ExprError();
17856 return SemaRef.TemporaryMaterializationConversion(Res.get());
17857 };
17858
17859 ExprResult SizeE = BuildExpr(*SizeMember);
17860 ExprResult DataE = BuildExpr(*DataMember);
17861
17862 QualType SizeT = SemaRef.Context.getSizeType();
17863 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17864 SemaRef.Context.getConstType(SemaRef.Context.CharTy));
17865
17866 ExprResult EvaluatedSize =
17867 SizeE.isInvalid()
17868 ? ExprError()
17871 if (EvaluatedSize.isInvalid()) {
17872 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17873 << EvalContext << /*size*/ 0;
17874 return false;
17875 }
17876
17877 ExprResult EvaluatedData =
17878 DataE.isInvalid()
17879 ? ExprError()
17881 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);
17882 if (EvaluatedData.isInvalid()) {
17883 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17884 << EvalContext << /*data*/ 1;
17885 return false;
17886 }
17887
17888 if (!ErrorOnInvalidMessage &&
17889 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))
17890 return true;
17891
17892 Expr::EvalResult Status;
17894 Status.Diag = &Notes;
17895 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17896 EvaluatedData.get(), Ctx, Status) ||
17897 !Notes.empty()) {
17898 SemaRef.Diag(Message->getBeginLoc(),
17899 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17900 : diag::warn_user_defined_msg_constexpr)
17901 << EvalContext;
17902 for (const auto &Note : Notes)
17903 SemaRef.Diag(Note.first, Note.second);
17904 return !ErrorOnInvalidMessage;
17905 }
17906 return true;
17907}
17908
17910 StringEvaluationContext EvalContext,
17911 bool ErrorOnInvalidMessage) {
17912 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17913 ErrorOnInvalidMessage);
17914}
17915
17916bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17917 StringEvaluationContext EvalContext,
17918 bool ErrorOnInvalidMessage) {
17919 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,
17920 ErrorOnInvalidMessage);
17921}
17922
17924 Expr *AssertExpr, Expr *AssertMessage,
17925 SourceLocation RParenLoc,
17926 bool Failed) {
17927 assert(AssertExpr != nullptr && "Expected non-null condition");
17928 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17929 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17930 !AssertMessage->isValueDependent())) &&
17931 !Failed) {
17932 // In a static_assert-declaration, the constant-expression shall be a
17933 // constant expression that can be contextually converted to bool.
17934 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17935 if (Converted.isInvalid())
17936 Failed = true;
17937
17938 ExprResult FullAssertExpr =
17939 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17940 /*DiscardedValue*/ false,
17941 /*IsConstexpr*/ true);
17942 if (FullAssertExpr.isInvalid())
17943 Failed = true;
17944 else
17945 AssertExpr = FullAssertExpr.get();
17946
17947 llvm::APSInt Cond;
17948 Expr *BaseExpr = AssertExpr;
17950
17951 if (!getLangOpts().CPlusPlus) {
17952 // In C mode, allow folding as an extension for better compatibility with
17953 // C++ in terms of expressions like static_assert("test") or
17954 // static_assert(nullptr).
17955 FoldKind = AllowFoldKind::Allow;
17956 }
17957
17958 if (!Failed && VerifyIntegerConstantExpression(
17959 BaseExpr, &Cond,
17960 diag::err_static_assert_expression_is_not_constant,
17961 FoldKind).isInvalid())
17962 Failed = true;
17963
17964 // If the static_assert passes, only verify that
17965 // the message is grammatically valid without evaluating it.
17966 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17967 std::string Str;
17968 EvaluateAsString(AssertMessage, Str, Context,
17970 /*ErrorOnInvalidMessage=*/false);
17971 }
17972
17973 // CWG2518
17974 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17975 // template definition, the declaration has no effect.
17976 bool InTemplateDefinition =
17977 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17978
17979 if (!Failed && !Cond && !InTemplateDefinition) {
17980 SmallString<256> MsgBuffer;
17981 llvm::raw_svector_ostream Msg(MsgBuffer);
17982 bool HasMessage = AssertMessage;
17983 if (AssertMessage) {
17984 std::string Str;
17985 HasMessage = EvaluateAsString(AssertMessage, Str, Context,
17987 /*ErrorOnInvalidMessage=*/true) ||
17988 !Str.empty();
17989 Msg << Str;
17990 }
17991 Expr *InnerCond = nullptr;
17992 std::string InnerCondDescription;
17993 std::tie(InnerCond, InnerCondDescription) =
17994 findFailedBooleanCondition(Converted.get());
17995 if (const auto *ConceptIDExpr =
17996 dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {
17997 const ASTConstraintSatisfaction &Satisfaction =
17998 ConceptIDExpr->getSatisfaction();
17999 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18000 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18001 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18002 // Drill down into concept specialization expressions to see why they
18003 // weren't satisfied.
18004 DiagnoseUnsatisfiedConstraint(ConceptIDExpr);
18005 }
18006 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&
18007 !isa<IntegerLiteral>(InnerCond)) {
18008 Diag(InnerCond->getBeginLoc(),
18009 diag::err_static_assert_requirement_failed)
18010 << InnerCondDescription << !HasMessage << Msg.str()
18011 << InnerCond->getSourceRange();
18012 DiagnoseStaticAssertDetails(InnerCond);
18013 } else {
18014 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
18015 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18017 }
18018 Failed = true;
18019 }
18020 } else {
18021 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
18022 /*DiscardedValue*/false,
18023 /*IsConstexpr*/true);
18024 if (FullAssertExpr.isInvalid())
18025 Failed = true;
18026 else
18027 AssertExpr = FullAssertExpr.get();
18028 }
18029
18031 AssertExpr, AssertMessage, RParenLoc,
18032 Failed);
18033
18034 CurContext->addDecl(Decl);
18035 return Decl;
18036}
18037
18039 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18040 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18041 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18042 MultiTemplateParamsArg TempParamLists) {
18044
18045 bool IsMemberSpecialization = false;
18046 bool Invalid = false;
18047
18048 if (TemplateParameterList *TemplateParams =
18050 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
18051 IsMemberSpecialization, Invalid)) {
18052 if (TemplateParams->size() > 0) {
18053 // This is a declaration of a class template.
18054 if (Invalid)
18055 return true;
18056
18057 return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,
18058 Name, NameLoc, Attr, TemplateParams, AS_public,
18059 /*ModulePrivateLoc=*/SourceLocation(),
18060 FriendLoc, TempParamLists.size() - 1,
18061 TempParamLists.data())
18062 .get();
18063 } else {
18064 // The "template<>" header is extraneous.
18065 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18066 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18067 IsMemberSpecialization = true;
18068 }
18069 }
18070
18071 if (Invalid) return true;
18072
18073 bool isAllExplicitSpecializations =
18074 llvm::all_of(TempParamLists, [](const TemplateParameterList *List) {
18075 return List->size() == 0;
18076 });
18077
18078 // FIXME: don't ignore attributes.
18079
18080 // If it's explicit specializations all the way down, just forget
18081 // about the template header and build an appropriate non-templated
18082 // friend. TODO: for source fidelity, remember the headers.
18084 if (isAllExplicitSpecializations) {
18085 if (SS.isEmpty()) {
18086 bool Owned = false;
18087 bool IsDependent = false;
18088 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
18089 Attr, AS_public,
18090 /*ModulePrivateLoc=*/SourceLocation(),
18091 MultiTemplateParamsArg(), Owned, IsDependent,
18092 /*ScopedEnumKWLoc=*/SourceLocation(),
18093 /*ScopedEnumUsesClassTag=*/false,
18094 /*UnderlyingType=*/TypeResult(),
18095 /*IsTypeSpecifier=*/false,
18096 /*IsTemplateParamOrArg=*/false,
18097 /*OOK=*/OffsetOfKind::Outside);
18098 }
18099
18100 TypeSourceInfo *TSI = nullptr;
18103 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name,
18104 NameLoc, &TSI, /*DeducedTSTContext=*/true);
18105 if (T.isNull())
18106 return true;
18107
18109 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18110 EllipsisLoc, TempParamLists);
18111 Friend->setAccess(AS_public);
18112 CurContext->addDecl(Friend);
18113 return Friend;
18114 }
18115
18116 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18117
18118 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
18119 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
18120 // shall not have been introduced by the template-declaration.
18122 collectUnexpandedParameterPacks(QualifierLoc, Unexpanded);
18123 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18124 for (UnexpandedParameterPack &U : Unexpanded) {
18125 if (std::optional<std::pair<unsigned, unsigned>> DI = getDepthAndIndex(U);
18126 DI && DI->first >= FriendDeclDepth) {
18127 auto *ND = dyn_cast<NamedDecl *>(U.first);
18128 if (!ND)
18129 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();
18130 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)
18131 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18132 return true;
18133 }
18134 }
18135
18136 // Handle the case of a templated-scope friend class. e.g.
18137 // template <class T> class A<T>::B;
18138 // FIXME: we don't support these right now.
18139 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
18142 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
18143 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18145 TL.setElaboratedKeywordLoc(TagLoc);
18147 TL.setNameLoc(NameLoc);
18148
18150 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,
18151 EllipsisLoc, TempParamLists);
18152 Friend->setAccess(AS_public);
18153 Friend->setUnsupportedFriend(true);
18154 CurContext->addDecl(Friend);
18155 return Friend;
18156}
18157
18159 MultiTemplateParamsArg TempParams,
18160 SourceLocation EllipsisLoc) {
18161 SourceLocation Loc = DS.getBeginLoc();
18162 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18163
18164 assert(DS.isFriendSpecified());
18166
18167 // C++ [class.friend]p3:
18168 // A friend declaration that does not declare a function shall have one of
18169 // the following forms:
18170 // friend elaborated-type-specifier ;
18171 // friend simple-type-specifier ;
18172 // friend typename-specifier ;
18173 //
18174 // If the friend keyword isn't first, or if the declarations has any type
18175 // qualifiers, then the declaration doesn't have that form.
18177 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
18178 if (DS.getTypeQualifiers()) {
18180 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
18182 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
18184 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
18186 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
18188 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
18189 }
18190
18191 // Try to convert the decl specifier to a type. This works for
18192 // friend templates because ActOnTag never produces a ClassTemplateDecl
18193 // for a TagUseKind::Friend.
18194 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18196 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
18197 QualType T = TSI->getType();
18198 if (TheDeclarator.isInvalidType())
18199 return nullptr;
18200
18201 // If '...' is present, the type must contain an unexpanded parameter
18202 // pack, and vice versa.
18203 bool Invalid = false;
18204 if (EllipsisLoc.isInvalid() &&
18206 return nullptr;
18207 if (EllipsisLoc.isValid() &&
18209 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
18210 << TSI->getTypeLoc().getSourceRange();
18211 Invalid = true;
18212 }
18213
18214 if (!T->isElaboratedTypeSpecifier()) {
18215 if (TempParams.size()) {
18216 // C++23 [dcl.pre]p5:
18217 // In a simple-declaration, the optional init-declarator-list can be
18218 // omitted only when declaring a class or enumeration, that is, when
18219 // the decl-specifier-seq contains either a class-specifier, an
18220 // elaborated-type-specifier with a class-key, or an enum-specifier.
18221 //
18222 // The declaration of a template-declaration or explicit-specialization
18223 // is never a member-declaration, so this must be a simple-declaration
18224 // with no init-declarator-list. Therefore, this is ill-formed.
18225 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
18226 return nullptr;
18227 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18228 SmallString<16> InsertionText(" ");
18229 InsertionText += RD->getKindName();
18230
18232 ? diag::warn_cxx98_compat_unelaborated_friend_type
18233 : diag::ext_unelaborated_friend_type)
18234 << (unsigned)RD->getTagKind() << T
18236 InsertionText);
18237 } else {
18238 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)
18239 << T << DS.getSourceRange();
18240 }
18241 }
18242
18243 // C++98 [class.friend]p1: A friend of a class is a function
18244 // or class that is not a member of the class . . .
18245 // This is fixed in DR77, which just barely didn't make the C++03
18246 // deadline. It's also a very silly restriction that seriously
18247 // affects inner classes and which nobody else seems to implement;
18248 // thus we never diagnose it, not even in -pedantic.
18249 //
18250 // But note that we could warn about it: it's always useless to
18251 // friend one of your own members (it's not, however, worthless to
18252 // friend a member of an arbitrary specialization of your template).
18253
18254 Decl *D;
18255 if (!TempParams.empty())
18256 // TODO: Support variadic friend template decls?
18257 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
18258 FriendLoc);
18259 else
18261 TSI, FriendLoc, EllipsisLoc);
18262
18263 if (!D)
18264 return nullptr;
18265
18266 D->setAccess(AS_public);
18267 CurContext->addDecl(D);
18268
18269 if (Invalid)
18270 D->setInvalidDecl();
18271
18272 return D;
18273}
18274
18276 MultiTemplateParamsArg TemplateParams) {
18277 const DeclSpec &DS = D.getDeclSpec();
18278
18279 assert(DS.isFriendSpecified());
18281
18284
18285 // C++ [class.friend]p1
18286 // A friend of a class is a function or class....
18287 // Note that this sees through typedefs, which is intended.
18288 // It *doesn't* see through dependent types, which is correct
18289 // according to [temp.arg.type]p3:
18290 // If a declaration acquires a function type through a
18291 // type dependent on a template-parameter and this causes
18292 // a declaration that does not use the syntactic form of a
18293 // function declarator to have a function type, the program
18294 // is ill-formed.
18295 if (!TInfo->getType()->isFunctionType()) {
18296 Diag(Loc, diag::err_unexpected_friend);
18297
18298 // It might be worthwhile to try to recover by creating an
18299 // appropriate declaration.
18300 return nullptr;
18301 }
18302
18303 // C++ [namespace.memdef]p3
18304 // - If a friend declaration in a non-local class first declares a
18305 // class or function, the friend class or function is a member
18306 // of the innermost enclosing namespace.
18307 // - The name of the friend is not found by simple name lookup
18308 // until a matching declaration is provided in that namespace
18309 // scope (either before or after the class declaration granting
18310 // friendship).
18311 // - If a friend function is called, its name may be found by the
18312 // name lookup that considers functions from namespaces and
18313 // classes associated with the types of the function arguments.
18314 // - When looking for a prior declaration of a class or a function
18315 // declared as a friend, scopes outside the innermost enclosing
18316 // namespace scope are not considered.
18317
18318 CXXScopeSpec &SS = D.getCXXScopeSpec();
18320 assert(NameInfo.getName());
18321
18322 // Check for unexpanded parameter packs.
18326 return nullptr;
18327
18328 // The context we found the declaration in, or in which we should
18329 // create the declaration.
18330 DeclContext *DC;
18331 Scope *DCScope = S;
18332 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18334
18335 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18336
18337 // There are five cases here.
18338 // - There's no scope specifier and we're in a local class. Only look
18339 // for functions declared in the immediately-enclosing block scope.
18340 // We recover from invalid scope qualifiers as if they just weren't there.
18341 FunctionDecl *FunctionContainingLocalClass = nullptr;
18342 if ((SS.isInvalid() || !SS.isSet()) &&
18343 (FunctionContainingLocalClass =
18344 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
18345 // C++11 [class.friend]p11:
18346 // If a friend declaration appears in a local class and the name
18347 // specified is an unqualified name, a prior declaration is
18348 // looked up without considering scopes that are outside the
18349 // innermost enclosing non-class scope. For a friend function
18350 // declaration, if there is no prior declaration, the program is
18351 // ill-formed.
18352
18353 // Find the innermost enclosing non-class scope. This is the block
18354 // scope containing the local class definition (or for a nested class,
18355 // the outer local class).
18356 DCScope = S->getFnParent();
18357
18358 // Look up the function name in the scope.
18360 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
18361
18362 if (!Previous.empty()) {
18363 // All possible previous declarations must have the same context:
18364 // either they were declared at block scope or they are members of
18365 // one of the enclosing local classes.
18366 DC = Previous.getRepresentativeDecl()->getDeclContext();
18367 } else {
18368 // This is ill-formed, but provide the context that we would have
18369 // declared the function in, if we were permitted to, for error recovery.
18370 DC = FunctionContainingLocalClass;
18371 }
18373
18374 // - There's no scope specifier, in which case we just go to the
18375 // appropriate scope and look for a function or function template
18376 // there as appropriate.
18377 } else if (SS.isInvalid() || !SS.isSet()) {
18378 // C++11 [namespace.memdef]p3:
18379 // If the name in a friend declaration is neither qualified nor
18380 // a template-id and the declaration is a function or an
18381 // elaborated-type-specifier, the lookup to determine whether
18382 // the entity has been previously declared shall not consider
18383 // any scopes outside the innermost enclosing namespace.
18384
18385 // Find the appropriate context according to the above.
18386 DC = CurContext;
18387
18388 // Skip class contexts. If someone can cite chapter and verse
18389 // for this behavior, that would be nice --- it's what GCC and
18390 // EDG do, and it seems like a reasonable intent, but the spec
18391 // really only says that checks for unqualified existing
18392 // declarations should stop at the nearest enclosing namespace,
18393 // not that they should only consider the nearest enclosing
18394 // namespace.
18395 while (DC->isRecord())
18396 DC = DC->getParent();
18397
18398 DeclContext *LookupDC = DC->getNonTransparentContext();
18399 while (true) {
18400 LookupQualifiedName(Previous, LookupDC);
18401
18402 if (!Previous.empty()) {
18403 DC = LookupDC;
18404 break;
18405 }
18406
18407 if (isTemplateId) {
18408 if (isa<TranslationUnitDecl>(LookupDC)) break;
18409 } else {
18410 if (LookupDC->isFileContext()) break;
18411 }
18412 LookupDC = LookupDC->getParent();
18413 }
18414
18415 DCScope = getScopeForDeclContext(S, DC);
18416
18417 // - There's a non-dependent scope specifier, in which case we
18418 // compute it and do a previous lookup there for a function
18419 // or function template.
18420 } else if (!SS.getScopeRep().isDependent()) {
18421 DC = computeDeclContext(SS);
18422 if (!DC) return nullptr;
18423
18424 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18425
18427
18428 // C++ [class.friend]p1: A friend of a class is a function or
18429 // class that is not a member of the class . . .
18430 if (DC->Equals(CurContext))
18433 diag::warn_cxx98_compat_friend_is_member :
18434 diag::err_friend_is_member);
18435
18436 // - There's a scope specifier that does not match any template
18437 // parameter lists, in which case we use some arbitrary context,
18438 // create a method or method template, and wait for instantiation.
18439 // - There's a scope specifier that does match some template
18440 // parameter lists, which we don't handle right now.
18441 } else {
18442 DC = CurContext;
18443 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18444 }
18445
18446 if (!DC->isRecord()) {
18447 int DiagArg = -1;
18448 switch (D.getName().getKind()) {
18451 DiagArg = 0;
18452 break;
18454 DiagArg = 1;
18455 break;
18457 DiagArg = 2;
18458 break;
18460 DiagArg = 3;
18461 break;
18467 break;
18468 }
18469 // This implies that it has to be an operator or function.
18470 if (DiagArg >= 0) {
18471 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18472 return nullptr;
18473 }
18474 }
18475
18476 // FIXME: This is an egregious hack to cope with cases where the scope stack
18477 // does not contain the declaration context, i.e., in an out-of-line
18478 // definition of a class.
18479 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18480 if (!DCScope) {
18481 FakeDCScope.setEntity(DC);
18482 DCScope = &FakeDCScope;
18483 }
18484
18485 bool AddToScope = true;
18486 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18487 TemplateParams, AddToScope);
18488 if (!ND) return nullptr;
18489
18490 assert(ND->getLexicalDeclContext() == CurContext);
18491
18492 // If we performed typo correction, we might have added a scope specifier
18493 // and changed the decl context.
18494 DC = ND->getDeclContext();
18495
18496 // Add the function declaration to the appropriate lookup tables,
18497 // adjusting the redeclarations list as necessary. We don't
18498 // want to do this yet if the friending class is dependent.
18499 //
18500 // Also update the scope-based lookup if the target context's
18501 // lookup context is in lexical scope.
18502 if (!CurContext->isDependentContext()) {
18503 DC = DC->getRedeclContext();
18505 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18506 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18507 }
18508
18510 D.getIdentifierLoc(), ND,
18511 DS.getFriendSpecLoc());
18512 FrD->setAccess(AS_public);
18513 CurContext->addDecl(FrD);
18514
18515 if (ND->isInvalidDecl()) {
18516 FrD->setInvalidDecl();
18517 } else {
18518 if (DC->isRecord()) CheckFriendAccess(ND);
18519
18520 FunctionDecl *FD;
18521 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18522 FD = FTD->getTemplatedDecl();
18523 else
18524 FD = cast<FunctionDecl>(ND);
18525
18526 // C++ [class.friend]p6:
18527 // A function may be defined in a friend declaration of a class if and
18528 // only if the class is a non-local class, and the function name is
18529 // unqualified.
18530 if (D.isFunctionDefinition()) {
18531 // Qualified friend function definition.
18532 if (SS.isNotEmpty()) {
18533 // FIXME: We should only do this if the scope specifier names the
18534 // innermost enclosing namespace; otherwise the fixit changes the
18535 // meaning of the code.
18537 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18538
18539 DB << SS.getScopeRep();
18540 if (DC->isFileContext())
18542
18543 // Friend function defined in a local class.
18544 } else if (FunctionContainingLocalClass) {
18545 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18546
18547 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18548 // a template-id, the function name is not unqualified because these is
18549 // no name. While the wording requires some reading in-between the
18550 // lines, GCC, MSVC, and EDG all consider a friend function
18551 // specialization definitions to be de facto explicit specialization
18552 // and diagnose them as such.
18553 } else if (isTemplateId) {
18554 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18555 }
18556 }
18557
18558 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18559 // default argument expression, that declaration shall be a definition
18560 // and shall be the only declaration of the function or function
18561 // template in the translation unit.
18563 // We can't look at FD->getPreviousDecl() because it may not have been set
18564 // if we're in a dependent context. If the function is known to be a
18565 // redeclaration, we will have narrowed Previous down to the right decl.
18566 if (D.isRedeclaration()) {
18567 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18568 Diag(Previous.getRepresentativeDecl()->getLocation(),
18569 diag::note_previous_declaration);
18570 } else if (!D.isFunctionDefinition())
18571 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18572 }
18573
18574 // Mark templated-scope function declarations as unsupported.
18575 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18576 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18577 << SS.getScopeRep() << SS.getRange()
18579 FrD->setUnsupportedFriend(true);
18580 }
18581 }
18582
18584
18585 return ND;
18586}
18587
18589 StringLiteral *Message) {
18591
18592 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18593 if (!Fn) {
18594 Diag(DelLoc, diag::err_deleted_non_function);
18595 return;
18596 }
18597
18598 // Deleted function does not have a body.
18599 Fn->setWillHaveBody(false);
18600
18601 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18602 // Don't consider the implicit declaration we generate for explicit
18603 // specializations. FIXME: Do not generate these implicit declarations.
18604 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18605 Prev->getPreviousDecl()) &&
18606 !Prev->isDefined()) {
18607 Diag(DelLoc, diag::err_deleted_decl_not_first);
18608 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18609 Prev->isImplicit() ? diag::note_previous_implicit_declaration
18610 : diag::note_previous_declaration);
18611 // We can't recover from this; the declaration might have already
18612 // been used.
18613 Fn->setInvalidDecl();
18614 return;
18615 }
18616
18617 // To maintain the invariant that functions are only deleted on their first
18618 // declaration, mark the implicitly-instantiated declaration of the
18619 // explicitly-specialized function as deleted instead of marking the
18620 // instantiated redeclaration.
18621 Fn = Fn->getCanonicalDecl();
18622 }
18623
18624 // dllimport/dllexport cannot be deleted.
18625 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18626 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18627 Fn->setInvalidDecl();
18628 }
18629
18630 // C++11 [basic.start.main]p3:
18631 // A program that defines main as deleted [...] is ill-formed.
18632 if (Fn->isMain())
18633 Diag(DelLoc, diag::err_deleted_main);
18634
18635 // C++11 [dcl.fct.def.delete]p4:
18636 // A deleted function is implicitly inline.
18637 Fn->setImplicitlyInline();
18638 Fn->setDeletedAsWritten(true, Message);
18639}
18640
18642 if (!Dcl || Dcl->isInvalidDecl())
18643 return;
18644
18645 auto *FD = dyn_cast<FunctionDecl>(Dcl);
18646 if (!FD) {
18647 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18648 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18649 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18650 return;
18651 }
18652 }
18653
18654 Diag(DefaultLoc, diag::err_default_special_members)
18655 << getLangOpts().CPlusPlus20;
18656 return;
18657 }
18658
18659 // Reject if this can't possibly be a defaultable function.
18661 if (!DefKind &&
18662 // A dependent function that doesn't locally look defaultable can
18663 // still instantiate to a defaultable function if it's a constructor
18664 // or assignment operator.
18665 (!FD->isDependentContext() ||
18667 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18668 Diag(DefaultLoc, diag::err_default_special_members)
18669 << getLangOpts().CPlusPlus20;
18670 return;
18671 }
18672
18673 // Issue compatibility warning. We already warned if the operator is
18674 // 'operator<=>' when parsing the '<=>' token.
18675 if (DefKind.isComparison() &&
18677 Diag(DefaultLoc, getLangOpts().CPlusPlus20
18678 ? diag::warn_cxx17_compat_defaulted_comparison
18679 : diag::ext_defaulted_comparison);
18680 }
18681
18682 FD->setDefaulted();
18683 FD->setExplicitlyDefaulted();
18684 FD->setDefaultLoc(DefaultLoc);
18685
18686 // Defer checking functions that are defaulted in a dependent context.
18687 if (FD->isDependentContext())
18688 return;
18689
18690 // Unset that we will have a body for this function. We might not,
18691 // if it turns out to be trivial, and we don't need this marking now
18692 // that we've marked it as defaulted.
18693 FD->setWillHaveBody(false);
18694
18695 if (DefKind.isComparison()) {
18696 // If this comparison's defaulting occurs within the definition of its
18697 // lexical class context, we have to do the checking when complete.
18698 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18699 if (!RD->isCompleteDefinition())
18700 return;
18701 }
18702
18703 // If this member fn was defaulted on its first declaration, we will have
18704 // already performed the checking in CheckCompletedCXXClass. Such a
18705 // declaration doesn't trigger an implicit definition.
18706 if (isa<CXXMethodDecl>(FD)) {
18707 const FunctionDecl *Primary = FD;
18708 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18709 // Ask the template instantiation pattern that actually had the
18710 // '= default' on it.
18711 Primary = Pattern;
18712 if (Primary->getCanonicalDecl()->isDefaulted())
18713 return;
18714 }
18715
18716 if (DefKind.isComparison()) {
18717 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18718 FD->setInvalidDecl();
18719 else
18720 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18721 } else {
18722 auto *MD = cast<CXXMethodDecl>(FD);
18723
18725 DefaultLoc))
18726 MD->setInvalidDecl();
18727 else
18728 DefineDefaultedFunction(*this, MD, DefaultLoc);
18729 }
18730}
18731
18733 for (Stmt *SubStmt : S->children()) {
18734 if (!SubStmt)
18735 continue;
18736 if (isa<ReturnStmt>(SubStmt))
18737 Self.Diag(SubStmt->getBeginLoc(),
18738 diag::err_return_in_constructor_handler);
18739 if (!isa<Expr>(SubStmt))
18740 SearchForReturnInStmt(Self, SubStmt);
18741 }
18742}
18743
18745 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18746 CXXCatchStmt *Handler = TryBlock->getHandler(I);
18747 SearchForReturnInStmt(*this, Handler);
18748 }
18749}
18750
18752 StringLiteral *DeletedMessage) {
18753 switch (BodyKind) {
18754 case FnBodyKind::Delete:
18755 SetDeclDeleted(D, Loc, DeletedMessage);
18756 break;
18758 SetDeclDefaulted(D, Loc);
18759 break;
18760 case FnBodyKind::Other:
18761 llvm_unreachable(
18762 "Parsed function body should be '= delete;' or '= default;'");
18763 }
18764}
18765
18767 const CXXMethodDecl *Old) {
18768 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18769 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18770
18771 if (OldFT->hasExtParameterInfos()) {
18772 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18773 // A parameter of the overriding method should be annotated with noescape
18774 // if the corresponding parameter of the overridden method is annotated.
18775 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18776 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18777 Diag(New->getParamDecl(I)->getLocation(),
18778 diag::warn_overriding_method_missing_noescape);
18779 Diag(Old->getParamDecl(I)->getLocation(),
18780 diag::note_overridden_marked_noescape);
18781 }
18782 }
18783
18784 // SME attributes must match when overriding a function declaration.
18785 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18786 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18787 << New << New->getType() << Old->getType();
18788 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18789 return true;
18790 }
18791
18792 // Virtual overrides must have the same code_seg.
18793 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18794 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18795 if ((NewCSA || OldCSA) &&
18796 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18797 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18798 Diag(Old->getLocation(), diag::note_previous_declaration);
18799 return true;
18800 }
18801
18802 // Virtual overrides: check for matching effects.
18803 if (Context.hasAnyFunctionEffects()) {
18804 const auto OldFX = Old->getFunctionEffects();
18805 const auto NewFXOrig = New->getFunctionEffects();
18806
18807 if (OldFX != NewFXOrig) {
18808 FunctionEffectSet NewFX(NewFXOrig);
18809 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18811 for (const auto &Diff : Diffs) {
18812 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18814 break;
18816 Diag(New->getLocation(), diag::warn_conflicting_func_effect_override)
18817 << Diff.effectName();
18818 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18819 << Old->getReturnTypeSourceRange();
18820 break;
18822 NewFX.insert(Diff.Old.value(), Errs);
18823 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18824 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18826 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18827 NewFT->getParamTypes(), EPI);
18828 New->setType(ModQT);
18829 if (Errs.empty()) {
18830 // A warning here is somewhat pedantic. Skip this if there was
18831 // already a merge conflict, which is more serious.
18832 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18833 << Diff.effectName();
18834 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18835 << Old->getReturnTypeSourceRange();
18836 }
18837 break;
18838 }
18839 }
18840 }
18841 if (!Errs.empty())
18842 diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
18843 Old->getLocation());
18844 }
18845 }
18846
18847 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18848
18849 // If the calling conventions match, everything is fine
18850 if (NewCC == OldCC)
18851 return false;
18852
18853 // If the calling conventions mismatch because the new function is static,
18854 // suppress the calling convention mismatch error; the error about static
18855 // function override (err_static_overrides_virtual from
18856 // Sema::CheckFunctionDeclaration) is more clear.
18857 if (New->getStorageClass() == SC_Static)
18858 return false;
18859
18860 Diag(New->getLocation(),
18861 diag::err_conflicting_overriding_cc_attributes)
18862 << New->getDeclName() << New->getType() << Old->getType();
18863 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18864 return true;
18865}
18866
18868 const CXXMethodDecl *Old) {
18869 // CWG2553
18870 // A virtual function shall not be an explicit object member function.
18871 if (!New->isExplicitObjectMemberFunction())
18872 return true;
18873 Diag(New->getParamDecl(0)->getBeginLoc(),
18874 diag::err_explicit_object_parameter_nonmember)
18875 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18876 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18877 New->setInvalidDecl();
18878 return false;
18879}
18880
18882 const CXXMethodDecl *Old) {
18883 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18884 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18885
18886 if (Context.hasSameType(NewTy, OldTy) ||
18887 NewTy->isDependentType() || OldTy->isDependentType())
18888 return false;
18889
18890 // Check if the return types are covariant
18891 QualType NewClassTy, OldClassTy;
18892
18893 /// Both types must be pointers or references to classes.
18894 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18895 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18896 NewClassTy = NewPT->getPointeeType();
18897 OldClassTy = OldPT->getPointeeType();
18898 }
18899 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18900 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18901 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18902 NewClassTy = NewRT->getPointeeType();
18903 OldClassTy = OldRT->getPointeeType();
18904 }
18905 }
18906 }
18907
18908 // The return types aren't either both pointers or references to a class type.
18909 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
18910 Diag(New->getLocation(),
18911 diag::err_different_return_type_for_overriding_virtual_function)
18912 << New->getDeclName() << NewTy << OldTy
18913 << New->getReturnTypeSourceRange();
18914 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18915 << Old->getReturnTypeSourceRange();
18916
18917 return true;
18918 }
18919
18920 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18921 // C++14 [class.virtual]p8:
18922 // If the class type in the covariant return type of D::f differs from
18923 // that of B::f, the class type in the return type of D::f shall be
18924 // complete at the point of declaration of D::f or shall be the class
18925 // type D.
18926 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
18927 if (!RD->isBeingDefined() &&
18928 RequireCompleteType(New->getLocation(), NewClassTy,
18929 diag::err_covariant_return_incomplete,
18930 New->getDeclName()))
18931 return true;
18932 }
18933
18934 // Check if the new class derives from the old class.
18935 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18936 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18937 << New->getDeclName() << NewTy << OldTy
18938 << New->getReturnTypeSourceRange();
18939 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18940 << Old->getReturnTypeSourceRange();
18941 return true;
18942 }
18943
18944 // Check if we the conversion from derived to base is valid.
18946 NewClassTy, OldClassTy,
18947 diag::err_covariant_return_inaccessible_base,
18948 diag::err_covariant_return_ambiguous_derived_to_base_conv,
18949 New->getLocation(), New->getReturnTypeSourceRange(),
18950 New->getDeclName(), nullptr)) {
18951 // FIXME: this note won't trigger for delayed access control
18952 // diagnostics, and it's impossible to get an undelayed error
18953 // here from access control during the original parse because
18954 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18955 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18956 << Old->getReturnTypeSourceRange();
18957 return true;
18958 }
18959 }
18960
18961 // The qualifiers of the return types must be the same.
18962 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18963 Diag(New->getLocation(),
18964 diag::err_covariant_return_type_different_qualifications)
18965 << New->getDeclName() << NewTy << OldTy
18966 << New->getReturnTypeSourceRange();
18967 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18968 << Old->getReturnTypeSourceRange();
18969 return true;
18970 }
18971
18972
18973 // The new class type must have the same or less qualifiers as the old type.
18974 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {
18975 Diag(New->getLocation(),
18976 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
18977 << New->getDeclName() << NewTy << OldTy
18978 << New->getReturnTypeSourceRange();
18979 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18980 << Old->getReturnTypeSourceRange();
18981 return true;
18982 }
18983
18984 return false;
18985}
18986
18988 SourceLocation EndLoc = InitRange.getEnd();
18989 if (EndLoc.isValid())
18990 Method->setRangeEnd(EndLoc);
18991
18992 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18993 Method->setIsPureVirtual();
18994 return false;
18995 }
18996
18997 if (!Method->isInvalidDecl())
18998 Diag(Method->getLocation(), diag::err_non_virtual_pure)
18999 << Method->getDeclName() << InitRange;
19000 return true;
19001}
19002
19004 if (D->getFriendObjectKind())
19005 Diag(D->getLocation(), diag::err_pure_friend);
19006 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
19007 CheckPureMethod(M, ZeroLoc);
19008 else
19009 Diag(D->getLocation(), diag::err_illegal_initializer);
19010}
19011
19012/// Invoked when we are about to parse an initializer for the declaration
19013/// 'Dcl'.
19014///
19015/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19016/// static data member of class X, names should be looked up in the scope of
19017/// class X. If the declaration had a scope specifier, a scope will have
19018/// been created and passed in for this purpose. Otherwise, S will be null.
19020 assert(D && !D->isInvalidDecl());
19021
19022 // We will always have a nested name specifier here, but this declaration
19023 // might not be out of line if the specifier names the current namespace:
19024 // extern int n;
19025 // int ::n = 0;
19026 if (S && D->isOutOfLine())
19028
19032}
19033
19035 assert(D);
19036
19037 if (S && D->isOutOfLine())
19039
19041}
19042
19044 // C++ 6.4p2:
19045 // The declarator shall not specify a function or an array.
19046 // The type-specifier-seq shall not contain typedef and shall not declare a
19047 // new class or enumeration.
19049 "Parser allowed 'typedef' as storage class of condition decl.");
19050
19051 Decl *Dcl = ActOnDeclarator(S, D);
19052 if (!Dcl)
19053 return true;
19054
19055 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
19056 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
19057 << D.getSourceRange();
19058 return true;
19059 }
19060
19061 if (auto *VD = dyn_cast<VarDecl>(Dcl))
19062 VD->setCXXCondDecl();
19063
19064 return Dcl;
19065}
19066
19068 if (!ExternalSource)
19069 return;
19070
19072 ExternalSource->ReadUsedVTables(VTables);
19074 for (const ExternalVTableUse &VTable : VTables) {
19075 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19076 VTablesUsed.find(VTable.Record);
19077 // Even if a definition wasn't required before, it may be required now.
19078 if (Pos != VTablesUsed.end()) {
19079 if (!Pos->second && VTable.DefinitionRequired)
19080 Pos->second = true;
19081 continue;
19082 }
19083
19084 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19085 NewUses.push_back(VTableUse(VTable.Record, VTable.Location));
19086 }
19087
19088 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
19089}
19090
19092 bool DefinitionRequired) {
19093 // Ignore any vtable uses in unevaluated operands or for classes that do
19094 // not have a vtable.
19095 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19096 CurContext->isDependentContext() || isUnevaluatedContext())
19097 return;
19098 // Do not mark as used if compiling for the device outside of the target
19099 // region.
19100 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19101 !OpenMP().isInOpenMPDeclareTargetContext() &&
19102 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19103 if (!DefinitionRequired)
19105 return;
19106 }
19107
19108 // Try to insert this class into the map.
19110 Class = Class->getCanonicalDecl();
19111 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19112 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
19113 if (!Pos.second) {
19114 // If we already had an entry, check to see if we are promoting this vtable
19115 // to require a definition. If so, we need to reappend to the VTableUses
19116 // list, since we may have already processed the first entry.
19117 if (DefinitionRequired && !Pos.first->second) {
19118 Pos.first->second = true;
19119 } else {
19120 // Otherwise, we can early exit.
19121 return;
19122 }
19123 } else {
19124 // The Microsoft ABI requires that we perform the destructor body
19125 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19126 // the deleting destructor is emitted with the vtable, not with the
19127 // destructor definition as in the Itanium ABI.
19128 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19129 CXXDestructorDecl *DD = Class->getDestructor();
19130 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19131 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19132 // If this is an out-of-line declaration, marking it referenced will
19133 // not do anything. Manually call CheckDestructor to look up operator
19134 // delete().
19135 ContextRAII SavedContext(*this, DD);
19136 CheckDestructor(DD);
19137 } else {
19138 MarkFunctionReferenced(Loc, Class->getDestructor());
19139 }
19140 }
19141 }
19142 }
19143
19144 // Local classes need to have their virtual members marked
19145 // immediately. For all other classes, we mark their virtual members
19146 // at the end of the translation unit.
19147 if (Class->isLocalClass())
19148 MarkVirtualMembersReferenced(Loc, Class->getDefinition());
19149 else
19150 VTableUses.push_back(std::make_pair(Class, Loc));
19151}
19152
19155 if (VTableUses.empty())
19156 return false;
19157
19158 // Note: The VTableUses vector could grow as a result of marking
19159 // the members of a class as "used", so we check the size each
19160 // time through the loop and prefer indices (which are stable) to
19161 // iterators (which are not).
19162 bool DefinedAnything = false;
19163 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19164 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19165 if (!Class)
19166 continue;
19168 Class->getTemplateSpecializationKind();
19169
19170 SourceLocation Loc = VTableUses[I].second;
19171
19172 bool DefineVTable = true;
19173
19174 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
19175 // V-tables for non-template classes with an owning module are always
19176 // uniquely emitted in that module.
19177 if (Class->isInCurrentModuleUnit()) {
19178 DefineVTable = true;
19179 } else if (KeyFunction && !KeyFunction->hasBody()) {
19180 // If this class has a key function, but that key function is
19181 // defined in another translation unit, we don't need to emit the
19182 // vtable even though we're using it.
19183 // The key function is in another translation unit.
19184 DefineVTable = false;
19186 KeyFunction->getTemplateSpecializationKind();
19189 "Instantiations don't have key functions");
19190 (void)TSK;
19191 } else if (!KeyFunction) {
19192 // If we have a class with no key function that is the subject
19193 // of an explicit instantiation declaration, suppress the
19194 // vtable; it will live with the explicit instantiation
19195 // definition.
19196 bool IsExplicitInstantiationDeclaration =
19198 for (auto *R : Class->redecls()) {
19200 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
19202 IsExplicitInstantiationDeclaration = true;
19203 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19204 IsExplicitInstantiationDeclaration = false;
19205 break;
19206 }
19207 }
19208
19209 if (IsExplicitInstantiationDeclaration) {
19210 const bool HasExcludeFromExplicitInstantiation =
19211 llvm::any_of(Class->methods(), [](CXXMethodDecl *method) {
19212 // If the class has a member function declared with
19213 // `__attribute__((exclude_from_explicit_instantiation))`, the
19214 // explicit instantiation declaration should not suppress emitting
19215 // the vtable, since the corresponding explicit instantiation
19216 // definition might not emit the vtable if a triggering method is
19217 // excluded.
19218 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19219 });
19220 if (!HasExcludeFromExplicitInstantiation)
19221 DefineVTable = false;
19222 }
19223 }
19224
19225 // The exception specifications for all virtual members may be needed even
19226 // if we are not providing an authoritative form of the vtable in this TU.
19227 // We may choose to emit it available_externally anyway.
19228 if (!DefineVTable) {
19230 continue;
19231 }
19232
19233 // Mark all of the virtual members of this class as referenced, so
19234 // that we can build a vtable. Then, tell the AST consumer that a
19235 // vtable for this class is required.
19236 DefinedAnything = true;
19238 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19239 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
19240 Consumer.HandleVTable(Class);
19241
19242 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19243 // no key function or the key function is inlined. Don't warn in C++ ABIs
19244 // that lack key functions, since the user won't be able to make one.
19245 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19246 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
19248 const FunctionDecl *KeyFunctionDef = nullptr;
19249 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
19250 KeyFunctionDef->isInlined()))
19251 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
19252 }
19253 }
19254 VTableUses.clear();
19255
19256 return DefinedAnything;
19257}
19258
19260 const CXXRecordDecl *RD) {
19261 for (const auto *I : RD->methods())
19262 if (I->isVirtual() && !I->isPureVirtual())
19263 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
19264}
19265
19267 const CXXRecordDecl *RD,
19268 bool ConstexprOnly) {
19269 // Mark all functions which will appear in RD's vtable as used.
19270 CXXFinalOverriderMap FinalOverriders;
19271 RD->getFinalOverriders(FinalOverriders);
19272 for (const auto &FinalOverrider : FinalOverriders) {
19273 for (const auto &OverridingMethod : FinalOverrider.second) {
19274 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19275 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19276
19277 // C++ [basic.def.odr]p2:
19278 // [...] A virtual member function is used if it is not pure. [...]
19279 if (!Overrider->isPureVirtual() &&
19280 (!ConstexprOnly || Overrider->isConstexpr()))
19281 MarkFunctionReferenced(Loc, Overrider);
19282 }
19283 }
19284
19285 // Only classes that have virtual bases need a VTT.
19286 if (RD->getNumVBases() == 0)
19287 return;
19288
19289 for (const auto &I : RD->bases()) {
19290 const auto *Base = I.getType()->castAsCXXRecordDecl();
19291 if (Base->getNumVBases() == 0)
19292 continue;
19294 }
19295}
19296
19297static
19302 Sema &S) {
19303 if (Ctor->isInvalidDecl())
19304 return;
19305
19307
19308 // Target may not be determinable yet, for instance if this is a dependent
19309 // call in an uninstantiated template.
19310 if (Target) {
19311 const FunctionDecl *FNTarget = nullptr;
19312 (void)Target->hasBody(FNTarget);
19313 Target = const_cast<CXXConstructorDecl*>(
19314 cast_or_null<CXXConstructorDecl>(FNTarget));
19315 }
19316
19317 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19318 // Avoid dereferencing a null pointer here.
19319 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19320
19321 if (!Current.insert(Canonical).second)
19322 return;
19323
19324 // We know that beyond here, we aren't chaining into a cycle.
19325 if (!Target || !Target->isDelegatingConstructor() ||
19326 Target->isInvalidDecl() || Valid.count(TCanonical)) {
19327 Valid.insert_range(Current);
19328 Current.clear();
19329 // We've hit a cycle.
19330 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
19331 Current.count(TCanonical)) {
19332 // If we haven't diagnosed this cycle yet, do so now.
19333 if (!Invalid.count(TCanonical)) {
19334 S.Diag((*Ctor->init_begin())->getSourceLocation(),
19335 diag::warn_delegating_ctor_cycle)
19336 << Ctor;
19337
19338 // Don't add a note for a function delegating directly to itself.
19339 if (TCanonical != Canonical)
19340 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
19341
19343 while (C->getCanonicalDecl() != Canonical) {
19344 const FunctionDecl *FNTarget = nullptr;
19345 (void)C->getTargetConstructor()->hasBody(FNTarget);
19346 assert(FNTarget && "Ctor cycle through bodiless function");
19347
19348 C = const_cast<CXXConstructorDecl*>(
19349 cast<CXXConstructorDecl>(FNTarget));
19350 S.Diag(C->getLocation(), diag::note_which_delegates_to);
19351 }
19352 }
19353
19354 Invalid.insert_range(Current);
19355 Current.clear();
19356 } else {
19358 }
19359}
19360
19361
19364
19365 for (DelegatingCtorDeclsType::iterator
19366 I = DelegatingCtorDecls.begin(ExternalSource.get()),
19367 E = DelegatingCtorDecls.end();
19368 I != E; ++I)
19369 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
19370
19371 for (CXXConstructorDecl *CI : Invalid)
19372 CI->setInvalidDecl();
19373}
19374
19375namespace {
19376 /// AST visitor that finds references to the 'this' expression.
19377class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19378 Sema &S;
19379
19380public:
19381 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19382
19383 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19384 S.Diag(E->getLocation(), diag::err_this_static_member_func)
19385 << E->isImplicit();
19386 return false;
19387 }
19388};
19389}
19390
19392 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19393 if (!TSInfo)
19394 return false;
19395
19396 TypeLoc TL = TSInfo->getTypeLoc();
19398 if (!ProtoTL)
19399 return false;
19400
19401 // C++11 [expr.prim.general]p3:
19402 // [The expression this] shall not appear before the optional
19403 // cv-qualifier-seq and it shall not appear within the declaration of a
19404 // static member function (although its type and value category are defined
19405 // within a static member function as they are within a non-static member
19406 // function). [ Note: this is because declaration matching does not occur
19407 // until the complete declarator is known. - end note ]
19408 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19409 FindCXXThisExpr Finder(*this);
19410
19411 // If the return type came after the cv-qualifier-seq, check it now.
19412 if (Proto->hasTrailingReturn() &&
19413 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
19414 return true;
19415
19416 // Check the exception specification.
19418 return true;
19419
19420 // Check the trailing requires clause
19421 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19422 if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))
19423 return true;
19424
19426}
19427
19429 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19430 if (!TSInfo)
19431 return false;
19432
19433 TypeLoc TL = TSInfo->getTypeLoc();
19435 if (!ProtoTL)
19436 return false;
19437
19438 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19439 FindCXXThisExpr Finder(*this);
19440
19441 switch (Proto->getExceptionSpecType()) {
19442 case EST_Unparsed:
19443 case EST_Uninstantiated:
19444 case EST_Unevaluated:
19445 case EST_BasicNoexcept:
19446 case EST_NoThrow:
19447 case EST_DynamicNone:
19448 case EST_MSAny:
19449 case EST_None:
19450 break;
19451
19453 case EST_NoexceptFalse:
19454 case EST_NoexceptTrue:
19455 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19456 return true;
19457 [[fallthrough]];
19458
19459 case EST_Dynamic:
19460 for (const auto &E : Proto->exceptions()) {
19461 if (!Finder.TraverseType(E))
19462 return true;
19463 }
19464 break;
19465 }
19466
19467 return false;
19468}
19469
19471 FindCXXThisExpr Finder(*this);
19472
19473 // Check attributes.
19474 for (const auto *A : Method->attrs()) {
19475 // FIXME: This should be emitted by tblgen.
19476 Expr *Arg = nullptr;
19477 ArrayRef<Expr *> Args;
19478 if (const auto *G = dyn_cast<GuardedByAttr>(A))
19479 Arg = G->getArg();
19480 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19481 Arg = G->getArg();
19482 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19483 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19484 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19485 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19486 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19487 Arg = LR->getArg();
19488 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19489 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19490 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19491 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19492 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19493 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19494 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {
19495 Arg = AC->getSuccessValue();
19496 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19497 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19498 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19499
19500 if (Arg && !Finder.TraverseStmt(Arg))
19501 return true;
19502
19503 for (Expr *A : Args) {
19504 if (!Finder.TraverseStmt(A))
19505 return true;
19506 }
19507 }
19508
19509 return false;
19510}
19511
19513 bool IsTopLevel, ExceptionSpecificationType EST,
19514 ArrayRef<ParsedType> DynamicExceptions,
19515 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19516 SmallVectorImpl<QualType> &Exceptions,
19518 Exceptions.clear();
19519 ESI.Type = EST;
19520 if (EST == EST_Dynamic) {
19521 Exceptions.reserve(DynamicExceptions.size());
19522 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19523 // FIXME: Preserve type source info.
19524 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19525
19526 if (IsTopLevel) {
19528 collectUnexpandedParameterPacks(ET, Unexpanded);
19529 if (!Unexpanded.empty()) {
19531 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19532 Unexpanded);
19533 continue;
19534 }
19535 }
19536
19537 // Check that the type is valid for an exception spec, and
19538 // drop it if not.
19539 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19540 Exceptions.push_back(ET);
19541 }
19542 ESI.Exceptions = Exceptions;
19543 return;
19544 }
19545
19546 if (isComputedNoexcept(EST)) {
19547 assert((NoexceptExpr->isTypeDependent() ||
19548 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19549 Context.BoolTy) &&
19550 "Parser should have made sure that the expression is boolean");
19551 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19552 ESI.Type = EST_BasicNoexcept;
19553 return;
19554 }
19555
19556 ESI.NoexceptExpr = NoexceptExpr;
19557 return;
19558 }
19559}
19560
19562 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19563 ArrayRef<ParsedType> DynamicExceptions,
19564 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19565 if (!D)
19566 return;
19567
19568 // Dig out the function we're referring to.
19569 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
19570 D = FTD->getTemplatedDecl();
19571
19572 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
19573 if (!FD)
19574 return;
19575
19576 // Check the exception specification.
19579 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19580 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19581 ESI);
19582
19583 // Update the exception specification on the function type.
19584 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19585
19586 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
19587 if (MD->isStatic())
19589
19590 if (MD->isVirtual()) {
19591 // Check overrides, which we previously had to delay.
19592 for (const CXXMethodDecl *O : MD->overridden_methods())
19594 }
19595 }
19596}
19597
19598/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19599///
19601 SourceLocation DeclStart, Declarator &D,
19602 Expr *BitWidth,
19603 InClassInitStyle InitStyle,
19604 AccessSpecifier AS,
19605 const ParsedAttr &MSPropertyAttr) {
19606 const IdentifierInfo *II = D.getIdentifier();
19607 if (!II) {
19608 Diag(DeclStart, diag::err_anonymous_property);
19609 return nullptr;
19610 }
19612
19614 QualType T = TInfo->getType();
19615 if (getLangOpts().CPlusPlus) {
19617
19620 D.setInvalidType();
19621 T = Context.IntTy;
19622 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19623 }
19624 }
19625
19627
19629 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19630 << getLangOpts().CPlusPlus17;
19633 diag::err_invalid_thread)
19635
19636 // Check to see if this name was declared as a member previously
19637 NamedDecl *PrevDecl = nullptr;
19638 LookupResult Previous(*this, II, Loc, LookupMemberName,
19640 LookupName(Previous, S);
19641 switch (Previous.getResultKind()) {
19644 PrevDecl = Previous.getAsSingle<NamedDecl>();
19645 break;
19646
19648 PrevDecl = Previous.getRepresentativeDecl();
19649 break;
19650
19654 break;
19655 }
19656
19657 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19658 // Maybe we will complain about the shadowed template parameter.
19660 // Just pretend that we didn't see the previous declaration.
19661 PrevDecl = nullptr;
19662 }
19663
19664 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19665 PrevDecl = nullptr;
19666
19667 SourceLocation TSSL = D.getBeginLoc();
19668 MSPropertyDecl *NewPD =
19669 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19670 MSPropertyAttr.getPropertyDataGetter(),
19671 MSPropertyAttr.getPropertyDataSetter());
19672 ProcessDeclAttributes(TUScope, NewPD, D);
19673 NewPD->setAccess(AS);
19674
19675 if (NewPD->isInvalidDecl())
19676 Record->setInvalidDecl();
19677
19679 NewPD->setModulePrivate();
19680
19681 if (NewPD->isInvalidDecl() && PrevDecl) {
19682 // Don't introduce NewFD into scope; there's already something
19683 // with the same name in the same scope.
19684 } else if (II) {
19685 PushOnScopeChains(NewPD, S);
19686 } else
19687 Record->addDecl(NewPD);
19688
19689 return NewPD;
19690}
19691
19693 Declarator &Declarator, unsigned TemplateParameterDepth) {
19694 auto &Info = InventedParameterInfos.emplace_back();
19695 TemplateParameterList *ExplicitParams = nullptr;
19696 ArrayRef<TemplateParameterList *> ExplicitLists =
19698 if (!ExplicitLists.empty()) {
19699 bool IsMemberSpecialization, IsInvalid;
19702 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19703 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19704 /*SuppressDiagnostic=*/true);
19705 }
19706 // C++23 [dcl.fct]p23:
19707 // An abbreviated function template can have a template-head. The invented
19708 // template-parameters are appended to the template-parameter-list after
19709 // the explicitly declared template-parameters.
19710 //
19711 // A template-head must have one or more template-parameters (read:
19712 // 'template<>' is *not* a template-head). Only append the invented
19713 // template parameters if we matched the nested-name-specifier to a non-empty
19714 // TemplateParameterList.
19715 if (ExplicitParams && !ExplicitParams->empty()) {
19716 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19717 llvm::append_range(Info.TemplateParams, *ExplicitParams);
19718 Info.NumExplicitTemplateParams = ExplicitParams->size();
19719 } else {
19720 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19721 Info.NumExplicitTemplateParams = 0;
19722 }
19723}
19724
19726 auto &FSI = InventedParameterInfos.back();
19727 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19728 if (FSI.NumExplicitTemplateParams != 0) {
19729 TemplateParameterList *ExplicitParams =
19733 Context, ExplicitParams->getTemplateLoc(),
19734 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19735 ExplicitParams->getRAngleLoc(),
19736 ExplicitParams->getRequiresClause()));
19737 } else {
19740 FSI.TemplateParams, Declarator.getEndLoc(),
19741 /*RequiresClause=*/nullptr));
19742 }
19743 }
19744 InventedParameterInfos.pop_back();
19745}
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.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static void ProcessAPINotes(Sema &S, Decl *D, const api_notes::CommonEntityInfo &Info, VersionedInfoMetadata Metadata)
This file declares semantic analysis for CUDA constructs.
static void DiagnoseUnsatisfiedConstraint(Sema &S, ArrayRef< UnsatisfiedConstraintRecord > Records, SourceLocation Loc, bool First=true, concepts::NestedRequirement *Req=nullptr)
static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD, SourceLocation Loc, bool &Res)
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial.
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we're implicitly defining a move assignment operator for a class with virtual bases.
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID)
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *Body, Sema::CheckConstexprKind Kind)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, CXXRecordDecl *Class)
static bool checkVectorDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT)
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
static CXXDestructorDecl * LookupDestructorIfRelevant(Sema &S, CXXRecordDecl *Class)
static void extendRight(SourceRange &R, SourceRange After)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in 'inline' qualifiers when a namespace is reopened.
static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef, const FunctionDecl *FD, bool *WasMalformed)
static bool RefersToRValueRef(Expr *MemRef)
static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallPtrSet< Decl *, 16 > &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind)
Check that the given field is initialized within a constexpr constructor.
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
#define CheckPolymorphic(Type)
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy, unsigned TyWidth, SmallVectorImpl< char > &Str)
Convert character's value, interpreted as a code unit, to a string.
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD)
Check for invalid uses of an abstract type in a function declaration.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, unsigned &OutSize)
static Expr * CastForMoving(Sema &SemaRef, Expr *E)
static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef, const FunctionDecl *FD)
static void extendLeft(SourceRange &R, SourceRange Before)
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D, unsigned Kind)
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class....
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, UnresolvedSetImpl &Operators, OverloadedOperatorKind Op)
Perform the unqualified lookups that might be needed to form a defaulted comparison function for the ...
static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS)
static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message, ResultType &Result, ASTContext &Ctx, Sema::StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl * > &Methods)
Add the most overridden methods from MD to Methods.
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD, QualType TypeParam, SourceLocation Loc)
AllocationOperatorKind
static NamespaceDecl * getNamespaceDecl(NamespaceBaseDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD, Sema::DefaultedComparisonKind DCK)
static bool isDestroyingDeleteT(QualType Type)
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, CXXRecordDecl *Class)
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, const CXXCtorInitializer *Previous, const CXXCtorInitializer *Current)
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
static bool IsUnusedPrivateField(const FieldDecl *FD)
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don't add Type itself.
static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl)
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, SourceLocation &Cxx2bLoc, Sema::CheckConstexprKind Kind)
Check the provided statement is allowed in a constexpr function definition.
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's parameter types are all literal types.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts.
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, VarDecl *Src, QualType DecompType, unsigned NumElems)
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
static bool HasAttribute(const QualType &T)
static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind, CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM, bool ConstArg, TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
static TemplateArgumentLoc getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T)
static void findImplicitlyDeclaredEqualityComparisons(ASTContext &Ctx, CXXRecordDecl *RD, llvm::SmallVectorImpl< FunctionDecl * > &Spaceships)
Find the equality comparison functions that should be implicitly declared in a given class definition...
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl< const void * > &IdealInits)
ImplicitInitializerKind
ImplicitInitializerKind - How an implicit base or member initializer should initialize its base or me...
@ IIK_Default
@ IIK_Move
@ IIK_Inherit
@ IIK_Copy
static bool ConvertAPValueToString(const APValue &V, QualType T, SmallVectorImpl< char > &Str, ASTContext &Context)
Convert \V to a string we can present to the user in a diagnostic \T is the type of the expression th...
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
static ClassTemplateDecl * LookupStdClassTemplate(Sema &S, SourceLocation Loc, const char *ClassName, bool *WasMalformed)
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class)
static bool UsefulToPrintExpr(const Expr *E)
Some Expression types are not useful to print notes about, e.g.
static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec)
Find the direct and/or virtual base specifiers that correspond to the given base type,...
static bool checkLiteralOperatorTemplateParameterList(Sema &SemaRef, FunctionTemplateDecl *TpDecl)
static bool ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, llvm::function_ref< bool(const CXXMethodDecl *)> Report)
Report an error regarding overriding, along with any relevant overridden methods.
static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD, QualType DecompType, ArrayRef< BindingDecl * > Bindings, unsigned MemberCount)
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, TemplateArgumentListInfo &Args, const TemplateParameterList *Params)
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind)
Check whether a function's return type is a literal type.
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer * > Inits)
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD)
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location, FieldDecl *Field)
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
@ TSK_CompleteObject
The object is actually the complete object.
@ TSK_Field
The subobject is a non-static data member.
@ TSK_BaseClass
The subobject is a base class.
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument.
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg, const char *ClassName, ClassTemplateDecl **CachedDecl, const Decl **MalformedDecl)
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, SourceLocation DefaultLoc)
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location, CXXRecordDecl *ClassDecl)
static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc, const CXXRecordDecl *OrigRD, QualType DecompType, DeclAccessPair BasePair)
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, CXXSpecialMemberKind CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Determine whether the specified special member function would be constexpr if it were implicitly defi...
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, CXXSpecialMemberKind CSM, TrivialSubobjectKind Kind, TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected, Sema &S)
static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying)
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, CXXMethodDecl *MD)
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, unsigned I, QualType T)
static Sema::ImplicitExceptionSpecification ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM, Sema::InheritedConstructorInfo *ICI)
static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
static bool checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
static bool InitializationHasSideEffects(const FieldDecl &FD)
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl * > Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc, Sema::CheckConstexprKind Kind)
Check the given declaration statement is legal within a constexpr function body.
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent",...
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, const CXXDestructorDecl *DD, Sema::CheckConstexprKind Kind)
Determine whether a destructor cannot be constexpr due to.
static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, const BaseSet &Bases)
Determines if the given class is provably not derived from all of the prospective base classes.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
static void collectUnexpandedParameterPacks(Sema &S, TemplateParameterList *Params, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool isInvalid(LocType Loc, bool *Invalid)
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
a trap message and trap category.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
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:801
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:797
const LangOptions & getLangOpts() const
Definition ASTContext.h:951
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:850
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:916
CanQualType getCanonicalTagType(const TagDecl *TD) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition DeclCXX.h:86
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition DeclCXX.h:117
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
TypeLoc getElementLoc() const
Definition TypeLoc.h:1807
QualType getElementType() const
Definition TypeBase.h:3742
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
bool isInherited() const
Definition Attr.h:101
Attr * clone(ASTContext &C) const
SourceLocation getLocation() const
Definition Attr.h:99
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3499
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3577
void addShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3474
shadow_iterator shadow_begin() const
Definition DeclCXX.h:3569
void removeShadowDecl(UsingShadowDecl *S)
Definition DeclCXX.cpp:3483
Expr * getLHS() const
Definition Expr.h:4091
Expr * getRHS() const
Definition Expr.h:4093
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:5076
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4182
Opcode getOpcode() const
Definition Expr.h:4086
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2142
A binding in a decomposition declaration.
Definition DeclCXX.h:4188
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition DeclCXX.cpp:3665
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:4226
void setDecomposedDecl(ValueDecl *Decomposed)
Set the decomposed variable for this BindingDecl.
Definition DeclCXX.h:4232
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6671
Wrapper for source info for block pointers.
Definition TypeLoc.h:1526
This class is used for builtin types like 'int'.
Definition TypeBase.h:3172
Kind getKind() const
Definition TypeBase.h:3220
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:724
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:28
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
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:1180
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1692
bool isImmediateEscalating() const
Definition ExprCXX.h:1707
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
Represents a C++ constructor within a class.
Definition DeclCXX.h:2611
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2854
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:3031
ExplicitSpecifier getExplicitSpecifier()
Definition DeclCXX.h:2683
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition DeclCXX.h:2708
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition DeclCXX.cpp:3008
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:3026
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3017
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition DeclCXX.h:2849
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:2986
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2946
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2986
Represents a C++ base or member initializer.
Definition DeclCXX.h:2376
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition DeclCXX.h:2548
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition DeclCXX.cpp:2934
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition DeclCXX.cpp:2921
bool isAnyMemberInitializer() const
Definition DeclCXX.h:2456
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition DeclCXX.h:2510
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2522
Represents a C++ destructor within a class.
Definition DeclCXX.h:2876
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:3116
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:1752
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:180
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:741
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
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:2721
bool isVirtual() const
Definition DeclCXX.h:2191
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:2506
unsigned getNumExplicitParams() const
Definition DeclCXX.h:2290
CXXMethodDecl * getMostRecentDecl()
Definition DeclCXX.h:2239
overridden_method_range overridden_methods() const
Definition DeclCXX.cpp:2796
unsigned size_overridden_methods() const
Definition DeclCXX.cpp:2790
method_iterator begin_overridden_methods() const
Definition DeclCXX.cpp:2780
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2262
bool isInstance() const
Definition DeclCXX.h:2163
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2753
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2286
bool isStatic() const
Definition DeclCXX.cpp:2419
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2232
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:769
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:1276
friend_range friends() const
Definition DeclFriend.h:258
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition DeclCXX.h:1347
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition DeclCXX.cpp:610
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1246
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1679
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1372
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition DeclCXX.h:1001
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition DeclCXX.h:820
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition DeclCXX.h:714
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator.
Definition DeclCXX.h:1426
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1397
bool hasTrivialDestructorForCall() const
Definition DeclCXX.h:1376
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition DeclCXX.h:706
bool isLiteral() const
Determine whether this class is a literal type.
Definition DeclCXX.cpp:1506
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition DeclCXX.h:961
bool defaultedDestructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1362
base_class_range bases()
Definition DeclCXX.h:608
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:603
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1307
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition DeclCXX.h:766
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition DeclCXX.h:892
bool hasUserDeclaredCopyAssignment() const
Determine whether this class has a user-declared copy assignment operator.
Definition DeclCXX.h:910
bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is provably not derived from the type Base.
method_range methods() const
Definition DeclCXX.h:650
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class.
Definition DeclCXX.h:931
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition DeclCXX.h:1727
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1269
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1284
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition DeclCXX.h:973
bool hasConstexprDestructor() const
Determine whether this class has a constexpr destructor.
Definition DeclCXX.cpp:598
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition DeclCXX.h:697
bool hasTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1288
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:729
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2060
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition DeclCXX.h:1334
base_class_range vbases()
Definition DeclCXX.h:625
base_class_iterator vbases_begin()
Definition DeclCXX.h:632
ctor_range ctors() const
Definition DeclCXX.h:670
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition DeclCXX.h:867
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1221
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition DeclCXX.h:1236
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition DeclCXX.h:858
bool isDynamicClass() const
Definition DeclCXX.h:574
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1148
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition DeclCXX.h:799
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition DeclCXX.h:1408
bool hasNonTrivialCopyConstructorForCall() const
Definition DeclCXX.h:1299
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition DeclCXX.h:1200
bool hasUserDeclaredCopyConstructor() const
Determine whether this class has a user-declared copy constructor.
Definition DeclCXX.h:793
bool hasDefinition() const
Definition DeclCXX.h:561
void setImplicitCopyAssignmentIsDeleted()
Set that we attempted to declare an implicit copy assignment operator, but overload resolution failed...
Definition DeclCXX.h:916
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition DeclCXX.h:1007
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2052
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
bool needsOverloadResolutionForMoveConstructor() const
Determine whether we need to eagerly declare a defaulted move constructor for this class.
Definition DeclCXX.h:902
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2156
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition DeclCXX.h:994
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2131
bool hasNonTrivialDestructorForCall() const
Definition DeclCXX.h:1386
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition DeclCXX.h:1013
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition DeclCXX.h:1420
CXXMethodDecl * getLambdaStaticInvoker() const
Retrieve the lambda static invoker, the address of which is returned by the conversion operator,...
Definition DeclCXX.cpp:1754
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class.
Definition DeclCXX.h:805
CXXRecordDecl * getDefinitionOrSelf() const
Definition DeclCXX.h:555
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition DeclCXX.h:846
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition DeclCXX.h:983
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition DeclCXX.h:925
bool hasTrivialMoveConstructorForCall() const
Definition DeclCXX.h:1312
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition DeclCXX.h:946
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:181
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:186
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:80
SourceLocation getBeginLoc() const
Definition DeclSpec.h:84
bool isSet() const
Deprecated.
Definition DeclSpec.h:199
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:95
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:184
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:179
Represents the this expression in C++.
Definition ExprCXX.h:1155
SourceLocation getBeginLoc() const
Definition ExprCXX.h:1175
bool isImplicit() const
Definition ExprCXX.h:1178
SourceLocation getLocation() const
Definition ExprCXX.h:1172
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:69
CXXCatchStmt * getHandler(unsigned i)
Definition StmtCXX.h:108
unsigned getNumHandlers() const
Definition StmtCXX.h:107
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
bool isCallToStdMove() const
Definition Expr.cpp:3624
Expr * getCallee()
Definition Expr.h:3093
arg_range arguments()
Definition Expr.h:3198
QualType withConst() const
Retrieves a version of this type with const applied.
CastKind getCastKind() const
Definition Expr.h:3723
Expr * getSubExpr()
Definition Expr.h:3729
static CharSourceRange getTokenRange(SourceRange R)
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
static StringRef getCategoryString(ComparisonCategoryType Kind)
static StringRef getResultString(ComparisonCategoryResult Kind)
static std::vector< ComparisonCategoryResult > getPossibleResultsForType(ComparisonCategoryType Type)
Return the list of results which are valid for the specified comparison category type.
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
ComparisonCategoryType Kind
The Kind of the comparison category type.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3283
QualType getElementType() const
Definition TypeBase.h:3293
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1732
body_range body()
Definition Stmt.h:1795
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:3768
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3824
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:3680
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared.
Definition DeclCXX.h:3744
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition DeclCXX.cpp:3456
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:1382
DeclListNode::iterator iterator
Definition DeclBase.h:1392
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition DeclBase.h:2393
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
lookup_result::iterator lookup_iterator
Definition DeclBase.h:2578
bool isFileContext() const
Definition DeclBase.h:2180
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:2185
bool isRecord() const
Definition DeclBase.h:2189
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:2375
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
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:2102
DeclContext * getNonTransparentContext()
decl_iterator decls_begin() const
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
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:488
ValueDecl * getDecl()
Definition Expr.h:1341
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1471
SourceLocation getBeginLoc() const
Definition Expr.h:1352
bool isImmediateEscalating() const
Definition Expr.h:1481
Captures information about "declaration specifiers".
Definition DeclSpec.h:218
bool isVirtualSpecified() const
Definition DeclSpec.h:653
bool isModulePrivateSpecified() const
Definition DeclSpec.h:834
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:696
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition DeclSpec.cpp:631
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:235
Expr * getPackIndexingExpr() const
Definition DeclSpec.h:543
void ClearStorageClassSpecs()
Definition DeclSpec.h:498
TST getTypeSpecType() const
Definition DeclSpec.h:520
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:493
SCS getStorageClassSpec() const
Definition DeclSpec.h:484
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:558
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:557
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:600
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:659
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:832
ParsedType getRepAsType() const
Definition DeclSpec.h:530
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:485
bool isFriendSpecifiedFirst() const
Definition DeclSpec.h:830
ParsedAttributes & getAttributes()
Definition DeclSpec.h:878
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:607
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:601
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:660
Expr * getRepAsExpr() const
Definition DeclSpec.h:538
bool isInlineSpecified() const
Definition DeclSpec.h:642
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:602
TypeSpecifierType TST
Definition DeclSpec.h:248
bool SetTypeQual(TQ T, SourceLocation Loc)
void ClearConstexprSpec()
Definition DeclSpec.h:846
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:532
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:494
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:604
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:654
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:841
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:565
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition DeclSpec.cpp:427
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:645
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:605
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:603
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:826
bool hasExplicitSpecifier() const
Definition DeclSpec.h:656
bool hasConstexprSpecifier() const
Definition DeclSpec.h:842
static const TST TST_auto
Definition DeclSpec.h:289
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1623
decl_range decls()
Definition Stmt.h:1671
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.h:1649
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:1061
bool isInStdNamespace() const
Definition DeclBase.cpp:449
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
Kind
Lists the kind of concrete classes of Decl.
Definition DeclBase.h:89
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:590
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1219
@ FOK_None
Not a friend object.
Definition DeclBase.h:1217
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:2793
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
Definition DeclBase.h:588
unsigned getIdentifierNamespace() const
Definition DeclBase.h:889
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1169
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
@ 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:829
void setImplicit(bool I=true)
Definition DeclBase.h:594
void setReferenced(bool R=true)
Definition DeclBase.h:623
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:575
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void dropAttr()
Definition DeclBase.h:556
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
@ 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:881
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
std::string getAsString() const
Retrieve the human-readable string for this name.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2000
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
unsigned getNumTemplateParameterLists() const
Definition Decl.h:862
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1921
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2477
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:2419
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2068
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2531
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2357
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2360
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2105
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2432
bool hasGroupingParens() const
Definition DeclSpec.h:2740
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2734
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2415
bool isRedeclaration() const
Definition DeclSpec.h:2786
DeclaratorContext getContext() const
Definition DeclSpec.h:2093
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2089
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2104
bool isFunctionDefinition() const
Definition DeclSpec.h:2758
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2087
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2083
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition DeclSpec.h:2670
void setInventedTemplateParameterList(TemplateParameterList *Invented)
Sets the template parameter list generated from the explicit template parameters along with any inven...
Definition DeclSpec.h:2677
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition DeclSpec.h:2232
bool isInvalidType() const
Definition DeclSpec.h:2735
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2103
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2347
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2075
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2508
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2351
A decomposition declaration.
Definition DeclCXX.h:4252
ArrayRef< BindingDecl * > bindings() const
Definition DeclCXX.h:4290
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1809
ArrayRef< Binding > bindings() const
Definition DeclSpec.h:1849
SourceRange getSourceRange() const
Definition DeclSpec.h:1857
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1855
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2601
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2590
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:959
virtual bool TraverseConstructorInitializer(MaybeConst< CXXCtorInitializer > *Init)
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5891
RAII object that enters a new expression evaluation context.
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
Represents an enum.
Definition Decl.h:4013
enumerator_range enumerators() const
Definition Decl.h:4159
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1931
const Expr * getExpr() const
Definition DeclCXX.h:1940
void setExpr(Expr *E)
Definition DeclCXX.h:1965
void setKind(ExplicitSpecKind Kind)
Definition DeclCXX.h:1964
This represents one expression.
Definition Expr.h:112
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3090
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3078
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3086
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3253
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition Decl.h:3260
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4726
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3340
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4716
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3334
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition Decl.cpp:4736
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3407
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3266
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:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
void setUnsupportedFriend(bool Unsupported)
Definition DeclFriend.h:186
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList * > Params, FriendUnion Friend, SourceLocation FriendLoc)
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition Decl.cpp:3141
Represents a function declaration or definition.
Definition Decl.h:2000
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2642
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3280
ExceptionSpecificationType getExceptionSpecType() const
Gets the ExceptionSpecificationType as declared.
Definition Decl.h:2869
bool isTrivialForCall() const
Definition Decl.h:2380
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2476
DefaultedOrDeletedFunctionInfo * getDefaultedOrDeletedInfo() const
Definition Decl.cpp:3195
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3848
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4194
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2314
bool isImmediateFunction() const
Definition Decl.cpp:3341
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition Decl.cpp:3161
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4025
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition Decl.cpp:3552
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3866
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2921
SourceLocation getDefaultLoc() const
Definition Decl.h:2398
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2389
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2377
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4314
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition Decl.h:2782
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3748
param_iterator param_begin()
Definition Decl.h:2786
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2823
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3134
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2326
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2540
void setBodyContainsImmediateEscalatingExpressions(bool Set)
Definition Decl.h:2486
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4330
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3134
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4258
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2888
void setTrivial(bool IT)
Definition Decl.h:2378
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4145
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
static constexpr unsigned RequiredTypeAwareNewParameterCount
Count of mandatory parameters for type aware operator new.
Definition Decl.h:2638
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2353
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3619
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isImmediateEscalating() const
Definition Decl.cpp:3312
void setIsDestroyingOperatorDelete(bool IsDestroyingDelete)
Definition Decl.cpp:3556
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3560
void setIsTypeAwareOperatorNewOrDelete(bool IsTypeAwareOperator=true)
Definition Decl.cpp:3564
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2385
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4550
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2933
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4131
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2473
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4418
void setDefaulted(bool D=true)
Definition Decl.h:2386
bool isConsteval() const
Definition Decl.h:2482
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2410
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:2862
void setBody(Stmt *B)
Definition Decl.cpp:3292
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2344
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition Decl.cpp:3880
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3827
size_t param_size() const
Definition Decl.h:2790
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2211
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3200
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:3247
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:2805
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2685
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5251
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:5668
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5283
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5115
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ValueDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ValueDecl * > Params)
Definition ExprCXX.cpp:1816
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5315
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5819
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5622
unsigned getNumParams() const
Definition TypeBase.h:5593
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5735
const QualType * param_type_iterator
Definition TypeBase.h:5753
QualType getParamType(unsigned i) const
Definition TypeBase.h:5595
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5719
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5604
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5680
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5600
ArrayRef< QualType > exceptions() const
Definition TypeBase.h:5769
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5784
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Wrapper for source info for functions.
Definition TypeLoc.h:1644
unsigned getNumParams() const
Definition TypeLoc.h:1716
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1722
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1723
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1725
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4734
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4511
CallingConv getCallConv() const
Definition TypeBase.h:4866
QualType getReturnType() const
Definition TypeBase.h:4851
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:2251
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1734
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2073
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6060
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3488
void setInherited(bool I)
Definition Attr.h:161
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2582
ConstructorUsingShadowDecl * getShadowDecl() const
Definition DeclCXX.h:2594
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5302
unsigned getNumInits() const
Definition Expr.h:5332
const Expr * getInit(unsigned Init) const
Definition Expr.h:5356
child_range children()
Definition Expr.h:5501
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
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 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:975
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3625
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition ExprCXX.cpp:1358
capture_range captures() const
Retrieve this lambda's captures.
Definition ExprCXX.cpp:1371
@ 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:1038
Represents a linkage specification.
Definition DeclCXX.h:3018
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3271
void setRBraceLoc(SourceLocation L)
Definition DeclCXX.h:3060
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
iterator end() const
Definition Lookup.h:359
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition Lookup.h:358
An instance of this class represents the declaration of a property member.
Definition DeclCXX.h:4347
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition DeclCXX.cpp:3740
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
Expr * getBase() const
Definition Expr.h:3444
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3562
Wrapper for source info for member pointers.
Definition TypeLoc.h:1544
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3661
Describes a module or submodule.
Definition Module.h:144
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:732
bool isExplicitGlobalModule() const
Definition Module.h:242
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:706
Represents a C++ namespace alias.
Definition DeclCXX.h:3204
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamespaceBaseDecl *Namespace)
Definition DeclCXX.cpp:3372
Represents C++ namespaces and their aliases.
Definition Decl.h:573
NamespaceDecl * getNamespace()
Definition DeclCXX.cpp:3309
Represent a C++ namespace.
Definition Decl.h:592
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition Decl.h:648
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3332
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace that inhabits this namespace, if any.
Definition Decl.h:675
void setRBraceLoc(SourceLocation L)
Definition Decl.h:694
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ Global
The global specifier '::'. There is no stored value.
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:1181
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1171
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:277
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4948
Represents a parameter to a function.
Definition Decl.h:1790
void setDefaultArg(Expr *defarg)
Definition Decl.cpp:3023
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1931
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1919
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition Decl.cpp:3028
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3048
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1823
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1923
bool hasInheritedDefaultArg() const
Definition Decl.h:1935
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:2958
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3053
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3059
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1939
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2981
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
IdentifierInfo * getPropertyDataSetter() const
Definition ParsedAttr.h:470
IdentifierInfo * getPropertyDataGetter() const
Definition ParsedAttr.h:464
static const ParsedAttributesView & none()
Definition ParsedAttr.h:817
const ParsedAttr * getMSPropertyAttr() const
Definition ParsedAttr.h:903
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:897
bool isAddressDiscriminated() const
Definition TypeBase.h:265
Wrapper for source info for pointers.
Definition TypeLoc.h:1513
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3336
QualType getPointeeType() const
Definition TypeBase.h:3346
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
IdentifierTable & getIdentifierTable()
ArrayRef< Expr * > semantics()
Definition Expr.h:6875
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1463
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8472
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8477
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1459
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1231
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1162
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8388
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8428
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1444
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:8573
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8482
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1089
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8461
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8434
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1338
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1448
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2738
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:8553
Represents a template name as written in source code.
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
void removeAddressSpace()
Definition TypeBase.h:596
void removeVolatile()
Definition TypeBase.h:469
LangAS getAddressSpace() const
Definition TypeBase.h:571
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3643
Represents a struct/union/class.
Definition Decl.h:4327
bool hasFlexibleArrayMember() const
Definition Decl.h:4360
bool hasObjectMember() const
Definition Decl.h:4387
field_iterator field_end() const
Definition Decl.h:4533
field_range fields() const
Definition Decl.h:4530
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4527
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4515
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4379
bool field_empty() const
Definition Decl.h:4538
field_iterator field_begin() const
Definition Decl.cpp:5276
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:5332
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3581
QualType getPointeeType() const
Definition TypeBase.h:3599
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:409
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:291
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:398
void RemoveDecl(Decl *D)
Definition Scope.h:370
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
Scope * getDeclParent()
Definition Scope.h:335
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
void PushUsingDirective(UsingDirectiveDecl *UDir)
Definition Scope.h:643
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:90
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:1307
A RAII object to temporarily push a declaration context.
Definition Sema.h:3518
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6408
DefaultedComparisonKind asComparison() const
Definition Sema.h:6440
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6437
Helper class that collects exception specifications for implicitly-declared special member functions.
Definition Sema.h:5506
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:5548
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:9343
CXXMethodDecl * getMethod() const
Definition Sema.h:9355
RAII object to handle the state changes required to synthesize a function body.
Definition Sema.h:13599
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7771
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range)
CheckSpecifiedExceptionType - Check if the given type is valid in an exception specification.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13117
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
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:6597
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6359
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9385
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9412
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9420
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition Sema.h:9408
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9393
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:415
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:13741
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:1525
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6334
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:1254
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:6570
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:6551
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:1465
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:7892
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:1680
@ AR_accessible
Definition Sema.h:1678
@ AR_inaccessible
Definition Sema.h:1679
@ AR_delayed
Definition Sema.h:1681
DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, SourceLocation EllipsisLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2350
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
Annotation attributes are the only attributes allowed after an access specifier.
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, StringLiteral *DeletedMessage=nullptr)
void referenceDLLExportedClassMethods()
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec)
tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
@ Other
C++26 [dcl.fct.def.general]p1 function-body: ctor-initializer[opt] compound-statement function-try-bl...
Definition Sema.h:4189
@ Default
= default ;
Definition Sema.h:4191
@ Delete
deleted-function-body
Definition Sema.h:4197
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:48
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:2069
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:1300
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:225
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
void DiagnoseTypeTraitDetails(const Expr *E)
If E represents a built-in type trait, or a known standard type trait, try to print more information ...
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument, const Decl **MalformedDecl=nullptr)
Tests whether Ty is an instance of std::type_identity and, if it is and TypeArgument is not NULL,...
SemaObjC & ObjC()
Definition Sema.h:1510
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TrivialABIHandling::IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
void CheckDelayedMemberExceptionSpecs()
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
ASTContext & getASTContext() const
Definition Sema.h:939
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6577
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:6661
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:757
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Sema.h:6129
@ Relational
This is an <, <=, >, or >= that should be implemented as a rewrite in terms of a <=> comparison.
Definition Sema.h:6143
@ NotEqual
This is an operator!= that should be implemented as a rewrite in terms of a == comparison.
Definition Sema.h:6140
@ ThreeWay
This is an operator<=> that should be implemented as a series of subobject comparisons.
Definition Sema.h:6137
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6131
@ Equal
This is an operator== that should be implemented as a series of subobject comparisons.
Definition Sema.h:6134
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:6592
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:1204
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:12218
EnumDecl * getStdAlignValT() const
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1694
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8416
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2369
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
FPOptions & getCurFPFeatures()
Definition Sema.h:934
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_RequiresClause
Definition Sema.h:14546
@ UPPC_UsingDeclaration
A using declaration.
Definition Sema.h:14501
@ UPPC_ExceptionType
The type of an exception.
Definition Sema.h:14519
@ UPPC_Initializer
An initializer.
Definition Sema.h:14510
@ UPPC_BaseType
The base type of a class type.
Definition Sema.h:14480
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14504
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14513
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14483
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14486
@ UPPC_StaticAssertExpression
The expression in a static assertion.
Definition Sema.h:14492
Decl * ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl, bool IsNested)
ActOnStartNamespaceDef - This is called at the start of a namespace definition.
const LangOptions & getLangOpts() const
Definition Sema.h:932
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent)
DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was not used in the declaration of ...
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition Sema.h:5908
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:2481
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:1299
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
const LangOptions & LangOpts
Definition Sema.h:1298
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:6555
SemaHLSL & HLSL()
Definition Sema.h:1475
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:5914
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
ComparisonCategoryUsage
Definition Sema.h:5288
@ DefaultedOperator
A defaulted 'operator<=>' needed the comparison category.
Definition Sema.h:5295
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6548
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:6653
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6585
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.
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.
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, SkipBodyInfo *SkipBody=nullptr)
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition Sema.h:13129
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:5904
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:643
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:15578
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:9911
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:7027
std::unique_ptr< RecordDeclSetTy > PureVirtualClassDiagSet
PureVirtualClassDiagSet - a set of class declarations which we have emitted a list of pure virtual fu...
Definition Sema.h:6562
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1438
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:6581
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:8231
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:14029
SourceManager & getSourceManager() const
Definition Sema.h:937
FunctionDecl * SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship)
Substitute the name and return type of a defaulted 'operator<=>' to form an implicit 'operator=='.
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK)
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this' shows up in the exception specification of a static member function.
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition Sema.h:9371
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification,...
void FilterUsingLookup(Scope *S, LookupResult &lookup)
Remove decls we can't actually see from a lookup being used to declare shadow using decls.
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
StringEvaluationContext
Definition Sema.h:6024
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc)
PushNamespaceVisibilityAttr - Note that we've entered a namespace with a visibility attribute.
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer * > MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
FunctionDecl * BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl, QualType AllocType, SourceLocation)
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
void DiagnoseUnknownAttribute(const ParsedAttr &AL)
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15533
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
void CheckCompleteVariableDeclaration(VarDecl *VD)
ExprResult ActOnRequiresClause(ExprResult ConstraintExpr)
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
RedeclarationKind forRedeclarationInCurContext() const
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6573
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:1576
ASTConsumer & Consumer
Definition Sema.h:1301
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:4689
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:124
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:6783
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6793
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6762
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:1259
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:1303
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > Expansions)
MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc)
Handle a C++ member initializer using parentheses syntax.
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class,...
DiagnosticsEngine & Diags
Definition Sema.h:1302
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition Sema.h:7841
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:6557
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
friend class InitializationSequence
Definition Sema.h:1580
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:6589
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:337
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:6333
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)
Decl * ActOnDeclarator(Scope *S, Declarator &D)
AbstractDiagSelID
Definition Sema.h:6279
@ AbstractVariableType
Definition Sema.h:6283
@ AbstractReturnType
Definition Sema.h:6281
@ AbstractNone
Definition Sema.h:6280
@ AbstractFieldType
Definition Sema.h:6284
@ AbstractArrayType
Definition Sema.h:6287
@ AbstractParamType
Definition Sema.h:6282
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:8420
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
CheckConstexprKind
Definition Sema.h:6468
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6473
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6470
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:436
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:3511
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
ExprResult ActOnCXXThis(SourceLocation Loc)
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
void warnOnReservedIdentifier(const NamedDecl *D)
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, SourceLocation DefaultLoc)
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We've already started a delayed C++ method declaration.
bool isAbstractType(SourceLocation Loc, QualType T)
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:652
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer * > Initializers={})
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8713
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:3638
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
child_range children()
Definition Stmt.cpp:304
StmtClass getStmtClass() const
Definition Stmt.h:1485
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:1802
bool isUnevaluated() const
Definition Expr.h:1924
StringRef getString() const
Definition Expr.h:1870
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3838
StringRef getKindName() const
Definition Decl.h:3913
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3818
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4900
bool isUnion() const
Definition Decl.h:3928
TagKind getTagKind() const
Definition Decl.h:3917
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3863
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
A convenient class for passing around template argument information.
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
TypeSourceInfo * getTypeSourceInfo() const
Represents a template argument.
@ Type
The template argument is a type.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:1917
Declaration of a template type parameter.
unsigned getIndex() const
Retrieve the index of the template parameter.
unsigned getDepth() const
Retrieve the depth of the template parameter.
The top declaration context.
Definition Decl.h:105
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3688
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5813
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition Decl.h:3707
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:3513
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1437
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:160
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:116
bool isNull() const
Definition TypeLoc.h:121
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8359
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:8370
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1839
bool isVoidType() const
Definition TypeBase.h:8991
bool isBooleanType() const
Definition TypeBase.h:9128
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:1934
bool isIncompleteArrayType() const
Definition TypeBase.h:8732
bool isUndeducedAutoType() const
Definition TypeBase.h:8821
bool isRValueReferenceType() const
Definition TypeBase.h:8657
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:8724
bool isPointerType() const
Definition TypeBase.h:8625
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9035
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9285
bool isReferenceType() const
Definition TypeBase.h:8649
bool isEnumeralType() const
Definition TypeBase.h:8756
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
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:8653
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8960
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2790
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2411
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3127
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9171
bool isFunctionProtoType() const
Definition TypeBase.h:2607
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9141
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2808
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9134
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isFunctionType() const
Definition TypeBase.h:8621
bool isStructureOrClassType() const
Definition Type.cpp:707
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2357
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2929
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:2284
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
bool isRecordType() const
Definition TypeBase.h:8752
bool isUnionType() const
Definition Type.cpp:719
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
QualType getUnderlyingType() const
Definition Decl.h:3617
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:2288
Opcode getOpcode() const
Definition Expr.h:2283
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2343
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:5133
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1033
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1069
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1245
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1242
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1077
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1091
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1080
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1061
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1115
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1085
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:432
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:4121
static UnresolvedUsingIfExistsDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation Loc, DeclarationName Name)
Definition DeclCXX.cpp:3617
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:3596
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition DeclCXX.cpp:3568
Represents a C++ using-declaration.
Definition DeclCXX.h:3594
bool hasTypename() const
Return true if the using declaration has 'typename'.
Definition DeclCXX.h:3643
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition DeclCXX.h:3631
DeclarationNameInfo getNameInfo() const
Definition DeclCXX.h:3635
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition DeclCXX.cpp:3505
SourceLocation getUsingLoc() const
Return the source location of the 'using' keyword.
Definition DeclCXX.h:3621
Represents C++ using-directive.
Definition DeclCXX.h:3099
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition DeclCXX.cpp:3288
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3795
static UsingEnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, SourceLocation EnumL, SourceLocation NameL, TypeSourceInfo *EnumType)
Definition DeclCXX.cpp:3526
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl * > UsingDecls)
Definition DeclCXX.cpp:3548
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3402
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, DeclarationName Name, BaseUsingDecl *Introducer, NamedDecl *Target)
Definition DeclCXX.h:3438
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3466
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:3445
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5594
Represents a variable declaration or definition.
Definition Decl.h:926
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2822
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2163
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1569
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2272
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2202
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed?
Definition Decl.cpp:2848
void setCXXCondDecl()
Definition Decl.h:1615
bool isInlineSpecified() const
Definition Decl.h:1554
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2587
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1226
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1208
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2863
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1177
const Expr * getInit() const
Definition Decl.h:1368
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:952
void setInit(Expr *I)
Definition Decl.cpp:2489
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1168
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:2540
void setExceptionVariable(bool EV)
Definition Decl.h:1497
Declaration of a variable template.
Represents a GCC generic vector type.
Definition TypeBase.h:4183
unsigned getNumElements() const
Definition TypeBase.h:4198
QualType getElementType() const
Definition TypeBase.h:4197
Represents a C++11 virt-specifier-seq.
Definition DeclSpec.h:2801
SourceLocation getOverrideLoc() const
Definition DeclSpec.h:2821
SourceLocation getLastLocation() const
Definition DeclSpec.h:2833
bool isOverrideSpecified() const
Definition DeclSpec.h:2820
SourceLocation getFinalLoc() const
Definition DeclSpec.h:2825
bool isFinalSpecified() const
Definition DeclSpec.h:2823
bool isFinalSpelledSealed() const
Definition DeclSpec.h:2824
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
bool FoundImmediateEscalatingExpression
Whether we found an immediate-escalating expression.
Definition ScopeInfo.h:179
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool Comp(InterpState &S, CodePtr OpPC)
1) Pops the value from the stack.
Definition Interp.h:1036
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:820
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Stencil access(llvm::StringRef BaseId, Stencil Member)
Constructs a MemberExpr that accesses the named member (Member) of the object bound to BaseId.
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_decltype
Definition Specifiers.h:89
@ TST_typename_pack_indexing
Definition Specifiers.h:97
@ TST_decltype_auto
Definition Specifiers.h:93
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:212
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus26
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
VariadicCallType
Definition Sema.h:513
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:35
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition DeclCXX.h:3010
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
LLVM_READONLY auto escapeCStyle(CharT Ch) -> StringRef
Return C-style escaped string for special characters, or an empty string if there is no such mapping.
Definition CharInfo.h:191
@ Comparison
A comparison.
Definition Sema.h:667
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:271
@ ICIS_ListInit
Direct list-initialization.
Definition Specifiers.h:274
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1788
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1794
@ 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:1541
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:633
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:238
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:1029
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1027
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1025
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1021
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1019
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1017
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1011
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1023
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1013
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1015
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_protected
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:127
@ AS_private
Definition Specifiers.h:126
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:248
@ SC_Static
Definition Specifiers.h:252
@ SC_None
Definition Specifiers.h:250
ComparisonCategoryType commonComparisonType(ComparisonCategoryType A, ComparisonCategoryType B)
Determine the common comparison type, as defined in C++2a [class.spaceship]p4.
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
Language
The language for the input, used to select and validate the language standard and possible actions.
StmtResult StmtError()
Definition Ownership.h:266
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
ActionResult< CXXCtorInitializer * > MemInitResult
Definition Ownership.h:253
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:5939
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5944
@ Struct
The "struct" keyword.
Definition TypeBase.h:5941
@ Class
The "class" keyword.
Definition TypeBase.h:5950
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
@ Type
The name was classified as a type.
Definition Sema.h:564
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ CanPassInRegs
The argument of this type can be passed directly in registers.
Definition Decl.h:4306
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4320
@ CannotPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4315
AllowFoldKind
Definition Sema.h:655
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
@ TNK_Concept_template
The name refers to a concept.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:150
TypeAwareAllocationMode
Definition ExprCXX.h:2252
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TrivialABIHandling
Definition Sema.h:645
@ ConsiderTrivialABI
The triviality of a method affected by "trivial_abi".
Definition Sema.h:650
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:647
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:385
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
TypeAwareAllocationMode typeAwareAllocationModeFromBool(bool IsTypeAwareAllocation)
Definition ExprCXX.h:2259
U cast(CodeGen::Address addr)
Definition Address.h:327
@ StaticAssertMessageData
Call to data() in a static assert message.
Definition Sema.h:849
@ StaticAssertMessageSize
Call to size() in a static assert message.
Definition Sema.h:847
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:845
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5914
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5935
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5925
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5928
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:177
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:91
Represents an element in a path from a derived class to a base class.
bool hasValidIntValue() const
True iff we've successfully evaluated the variable as a constant expression and extracted its integer...
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
SourceLocation getEndLoc() const LLVM_READONLY
bool containsUnexpandedParameterPack() const
Determine whether this name contains an unexpanded parameter pack.
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition DeclSpec.h:1381
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1441
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1390
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1444
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1542
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1416
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition DeclSpec.h:1571
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1574
void freeParams()
Reset the parameter list to having zero parameters.
Definition DeclSpec.h:1480
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1567
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter's default argument cannot be parsed immediately (because it occ...
Definition DeclSpec.h:1356
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1256
SourceRange getSourceRange() const
Definition DeclSpec.h:1268
FunctionTypeInfo Fun
Definition DeclSpec.h:1655
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
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:5372
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition TypeBase.h:5384
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5374
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5377
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5380
Extra information about a function prototype.
Definition TypeBase.h:5400
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:5978
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3330
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3312
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:13168
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13299
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13262
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13259
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13212
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13230
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13302
Abstract class used to diagnose incomplete types.
Definition Sema.h:8312
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
Information about a template-id annotation token.
TemplateNameKind Kind
The kind of template that Template refers to.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
OpaquePtr< T > get() const
Definition Ownership.h:105